Skip to content

itunes

songbirdcore.itunes

artwork_searcher(url)

Album artwork searcher.

Parameters:

  • url (str) –

    the url for the artwork

Returns:

  • Response ( Optional[Response] ) –

    the response for the artwork request

Source code in songbirdcore/itunes.py
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
def artwork_searcher(url: str) -> Optional[Response]:
    """Album artwork searcher.

    Args:
        url (str): the url for the artwork

    Returns:
        Response: the response for the artwork request
    """
    artwork_size_list = [
        "100x100",
        "500x500",
        "1000x1000",
        "1500x1500",
        "2000x2000",
        "2500x2500",
        "3000x3000",
    ]
    i = len(artwork_size_list) - 1

    response = requests.get(url.replace("100x100", artwork_size_list[i]))
    while response.status_code != 200 and i != 0:
        logger.info(f"- Size not found -- Trying size: {artwork_size_list[i]}")
        response = requests.get(url.replace("100x100", artwork_size_list[i]))
        i -= 1

    if i == 0:
        logger.info("Couldnt find album art. Your file wont have the art.")
        return None

    else:
        logger.info(f"Found art at size: {artwork_size_list[i]}")

    return response

Performs a search on users iTunes library by album, artist and genre

Parameters:

  • itunes_lib_path (str) –

    path to itunes song library on disk

  • search_parameters (str) –

    search term

  • album_properties (ItunesApiAlbumKeys, default: None ) –

    determines whether to do a smarter search based on given album properties

Returns: a list of songpaths found

Source code in songbirdcore/itunes.py
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
def itunes_lib_search(
    itunes_lib_path: str,
    search_parameters: str,
    album_properties: Optional[itunes_api.ItunesApiAlbumKeys] = None,
) -> List[str]:
    """
    Performs a search on users iTunes library by album, artist and genre

    Args:
        itunes_lib_path (str): path to itunes song library on disk
        search_parameters (str): search term
        album_properties (itunes_api.ItunesApiAlbumKeys): determines whether to do a smarter search based on given album properties

    Returns: a list of songpaths found
    """
    itunes_songs = glob.glob(
        os.path.join(itunes_lib_path, "*", "*", f"*.*"), recursive=True
    )
    matches = []
    for song_path in itunes_songs:
        # song_name_split is list of itunes file path.. artist is -3 from length, song is -1
        song_name_split = song_path.split(os.sep)
        song_name = common.remove_illegal_characters(
            song_name_split[len(song_name_split) - 1].lower()
        )
        album_name = common.remove_illegal_characters(
            song_name_split[len(song_name_split) - 2].lower()
        )
        artist_name = common.remove_illegal_characters(
            song_name_split[len(song_name_split) - 3].lower()
        )
        search_parameters = common.remove_illegal_characters(search_parameters.lower())
        if album_properties == None:
            formatted_name = song_name + " " + album_name + " " + artist_name
            if search_parameters in formatted_name:
                matches.append(song_path)
        else:
            if (
                album_properties.artistName.lower() in artist_name
                and search_parameters in song_name
            ):
                matches.append(song_path)

    # returns sorted alphabetical list of matches.
    matches.sort()
    return matches

m4aID3TaggerNoArtwork(file_path, song_tag_data)

Tag an m4a file with metadata only — no artwork fetch.

Source code in songbirdcore/itunes.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def m4aID3TaggerNoArtwork(
    file_path: str, song_tag_data: itunes_api.ItunesApiSongModel
) -> bool:
    """Tag an m4a file with metadata only — no artwork fetch."""
    try:
        logger.info(f"Adding tags (no artwork) to m4a file: {file_path}")
        audiofile = MP4(file_path)
        audiofile["\xa9ART"] = song_tag_data.artistName
        audiofile["\xa9alb"] = song_tag_data.collectionName
        audiofile["\xa9nam"] = song_tag_data.trackName
        audiofile["\xa9gen"] = song_tag_data.primaryGenreName
        audiofile["trkn"] = [(song_tag_data.trackNumber, song_tag_data.trackCount)]
        audiofile["disk"] = [(song_tag_data.discNumber, song_tag_data.discCount)]
        audiofile["\xa9day"] = song_tag_data.releaseDate
        if song_tag_data.collectionArtistName is not None:
            audiofile["aART"] = song_tag_data.collectionArtistName
        audiofile.save()
        logger.info("Your tags have been set.")
        return True
    except Exception as e:
        logger.exception(
            f"Unexpected error occured while trying to tag your m4a file: {e}"
        )
        return False

m4a_tag_reader(m4a_path)

Read tags and embedded artwork from an M4A file.

Returns:

  • tuple[Optional[ItunesApiSongModel], Optional[bytes]] –

    (ItunesApiSongModel or None, artwork bytes or None)

Source code in songbirdcore/itunes.py
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
def m4a_tag_reader(
    m4a_path: str,
) -> tuple[Optional[itunes_api.ItunesApiSongModel], Optional[bytes]]:
    """Read tags and embedded artwork from an M4A file.

    Returns:
        (ItunesApiSongModel or None, artwork bytes or None)
    """
    try:
        audiofile = MP4(m4a_path)
        tags = audiofile.tags or {}

        def _get(key: str, default: str = "") -> str:
            val = tags.get(key)
            return str(val[0]) if val else default

        trkn = tags.get("trkn", [(0, 0)])[0]
        disk = tags.get("disk", [(1, 1)])[0]
        model = itunes_api.ItunesApiSongModel(
            trackName=_get("\xa9nam"),
            artistName=_get("\xa9ART"),
            collectionName=_get("\xa9alb"),
            artworkUrl100="",
            primaryGenreName=_get("\xa9gen"),
            trackNumber=trkn[0] if trkn else 0,
            trackCount=trkn[1] if trkn else 0,
            collectionArtistName=_get("aART"),
            discNumber=disk[0] if disk else 1,
            discCount=disk[1] if disk else 1,
            releaseDate=_get("\xa9day"),
        )
        covers = tags.get("covr", [])
        artwork_bytes = bytes(covers[0]) if covers else None
        return model, artwork_bytes
    except Exception as e:
        logger.exception(f"Error reading M4A tags from {m4a_path}: {e}")
        return None, None

m4a_tagger(file_path, song_tag_data)

Tag an m4a file using iTunes recognized tags.

The below is a tag legend taken from mutagen website. Text values:

'\xa9nam' - track title
'\xa9alb' - album
'\xa9ART' - artist
'aART' - album artist
'\xa9day' - year
'purd' - purchase date
'\xa9gen' - genre
Tuples of ints (multiple values per key are supported):
'trkn' - track number, total tracks
'disk' - disc number, total discs
'covr' - cover artwork, list of MP4Cover objects (which are tagged strs)

Parameters:

  • file_path (str) –

    path to the m4a file

  • song_tag_data (ItunesApiSongModel) –

    The model for the songs relevant metadata collected from itunes search api

Returns:

  • bool ( bool ) –

    true if tagging was successful.

Source code in songbirdcore/itunes.py
 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
def m4a_tagger(file_path: str, song_tag_data: itunes_api.ItunesApiSongModel) -> bool:
    """Tag an m4a file using iTunes recognized tags.

    The below is a tag legend taken from mutagen website.
    Text values:

    ```
    '\\xa9nam' - track title
    '\\xa9alb' - album
    '\\xa9ART' - artist
    'aART' - album artist
    '\\xa9day' - year
    'purd' - purchase date
    '\\xa9gen' - genre
    Tuples of ints (multiple values per key are supported):
    'trkn' - track number, total tracks
    'disk' - disc number, total discs
    'covr' - cover artwork, list of MP4Cover objects (which are tagged strs)
    ```

    Args:
        file_path (str): path to the m4a file
        song_tag_data (itunes_api.ItunesApiSongModel): The model for the songs relevant metadata collected from itunes search api

    Returns:
        bool: true if tagging was successful.
    """
    try:
        logger.info(f"Adding tags to m4a file : {file_path}")

        response = artwork_searcher(url=song_tag_data.artworkUrl100)
        audiofile = MP4(file_path)

        # Set all the tags for the mp3, all without if statement were checked for existence.
        audiofile["\xa9ART"] = song_tag_data.artistName
        audiofile["\xa9alb"] = song_tag_data.collectionName
        audiofile["\xa9nam"] = song_tag_data.trackName
        audiofile["\xa9gen"] = song_tag_data.primaryGenreName
        audiofile["trkn"] = [(song_tag_data.trackNumber, song_tag_data.trackCount)]
        audiofile["disk"] = [(song_tag_data.discNumber, song_tag_data.discCount)]
        audiofile["\xa9day"] = song_tag_data.releaseDate

        if (
            song_tag_data.collectionArtistName is not None
        ):  # check if collection_artist_name exists before adding to tags
            audiofile["aART"] = song_tag_data.collectionArtistName

        if response.status_code == 200:
            audiofile["covr"] = [
                MP4Cover(response.content, imageformat=MP4Cover.FORMAT_PNG)
            ]

        audiofile.save()
        logger.info("Your tags have been set.")
        return True
    except Exception as e:
        logger.exception(
            f"Unexpected error occured while trying to tag your m4a file: {e}"
        )
        return False

mp3ID3Tagger(mp3_path, song_tag_data)

Tags an mp3 file at mp3_path given a itunes_api.ItunesApiSongModel object

Parameters:

  • mp3_path (str) –

    file path of mp3 file

  • song_tag_data (ItunesApiSongModel) –

    the model with tag fields

Returns:

  • bool ( bool ) –

    true if tagging was a success

Source code in songbirdcore/itunes.py
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
def mp3ID3Tagger(mp3_path: str, song_tag_data: itunes_api.ItunesApiSongModel) -> bool:
    """
    Tags an mp3 file at mp3_path given a itunes_api.ItunesApiSongModel object

    Args:
        mp3_path (str): file path of mp3 file
        song_tag_data (itunes_api.ItunesApiSongModel): the model with tag fields

    Returns:
        bool: true if tagging was a success
    """
    try:
        # Create MP3File instance.
        logger.info(f"Adding your tags to mp3 file: {mp3_path}")
        # Have to call MP3File twice for it to work.

        # Get the image to show for a song .. but get high res
        # get album artwork from the list of sizes

        response = artwork_searcher(url=song_tag_data.artworkUrl100)

        # Set all the tags for the mp3, all without if statement were checked for existence.
        audiofile = eyed3.load(mp3_path)
        audiofile.tag.artist = song_tag_data.artistName
        audiofile.tag.album = song_tag_data.collectionName
        audiofile.tag.title = song_tag_data.trackName
        audiofile.tag.genre = song_tag_data.primaryGenreName
        audiofile.tag.track_num = (song_tag_data.trackNumber, song_tag_data.trackCount)
        audiofile.tag.disc_num = (song_tag_data.discNumber, song_tag_data.discCount)
        audiofile.tag.recording_date = song_tag_data.releaseDate

        if (
            song_tag_data.collectionArtistName is not None
        ):  # check if collection_artist_name exists before adding to tags
            audiofile.tag.album_artist = song_tag_data.collectionArtistName

        if response.status_code == 200:
            audiofile.tag.images.set(
                type_=3,
                img_data=response.content,
                mime_type="image/png",
                description="Art",
                img_url=None,
            )

        audiofile.tag.save()
        logger.info("Your tags have been set.")
        return True

    except Exception as e:
        logger.exception(
            f"Unexpected error occured while trying to tag your mp3 file: {e}"
        )
        return False

mp3ID3TaggerNoArtwork(mp3_path, song_tag_data)

Tag an mp3 file with metadata only — no artwork fetch.

Source code in songbirdcore/itunes.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def mp3ID3TaggerNoArtwork(
    mp3_path: str, song_tag_data: itunes_api.ItunesApiSongModel
) -> bool:
    """Tag an mp3 file with metadata only — no artwork fetch."""
    try:
        logger.info(f"Adding tags (no artwork) to mp3 file: {mp3_path}")
        audiofile = eyed3.load(mp3_path)
        audiofile.tag.artist = song_tag_data.artistName
        audiofile.tag.album = song_tag_data.collectionName
        audiofile.tag.title = song_tag_data.trackName
        audiofile.tag.genre = song_tag_data.primaryGenreName
        audiofile.tag.track_num = (song_tag_data.trackNumber, song_tag_data.trackCount)
        audiofile.tag.disc_num = (song_tag_data.discNumber, song_tag_data.discCount)
        audiofile.tag.recording_date = song_tag_data.releaseDate
        if song_tag_data.collectionArtistName is not None:
            audiofile.tag.album_artist = song_tag_data.collectionArtistName
        audiofile.tag.save()
        logger.info("Your tags have been set.")
        return True
    except Exception as e:
        logger.exception(
            f"Unexpected error occured while trying to tag your mp3 file: {e}"
        )
        return False

mp3_tag_reader(mp3_path)

Read ID3 tags and embedded artwork from an MP3 file.

Returns:

  • tuple[Optional[ItunesApiSongModel], Optional[bytes]] –

    (ItunesApiSongModel or None, artwork bytes or None)

Source code in songbirdcore/itunes.py
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
def mp3_tag_reader(
    mp3_path: str,
) -> tuple[Optional[itunes_api.ItunesApiSongModel], Optional[bytes]]:
    """Read ID3 tags and embedded artwork from an MP3 file.

    Returns:
        (ItunesApiSongModel or None, artwork bytes or None)
    """
    try:
        audiofile = eyed3.load(mp3_path)
        if audiofile is None or audiofile.tag is None:
            return None, None
        tag = audiofile.tag
        track_num, track_count = tag.track_num or (0, 0)
        disc_num, disc_count = tag.disc_num or (1, 1)
        model = itunes_api.ItunesApiSongModel(
            trackName=tag.title or "",
            artistName=tag.artist or "",
            collectionName=tag.album or "",
            artworkUrl100="",
            primaryGenreName=tag.genre.name if tag.genre else "",
            trackNumber=track_num or 0,
            trackCount=track_count or 0,
            collectionArtistName=tag.album_artist or "",
            discNumber=disc_num or 1,
            discCount=disc_count or 1,
            releaseDate=str(tag.recording_date) if tag.recording_date else "",
        )
        artwork_bytes = next(
            (img.image_data for img in tag.images if img.image_data), None
        )
        return model, artwork_bytes
    except Exception as e:
        logger.exception(f"Error reading MP3 tags from {mp3_path}: {e}")
        return None, None

query_api(search_variable, limit, mode, lookup=False)

Parameters:

  • search_variable (str) –

    the term to search itunes api for

  • limit (int) –

    limit of the search in the api

  • mode (Modes) –

    value of album, or song for now

  • lookup (bool, default: False ) –

    if true, perform a lookup search via itunes api rather than a default search

Returns List[Union[itunes_api.ItunesApiSongModel, itunes_api.ItunesApiAlbumKeys]]: a list containing a tuple with itunes song properties and album properties

Source code in songbirdcore/itunes.py
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
def query_api(
    search_variable: str, limit: int, mode: modes.Modes, lookup: bool = False
) -> List[Union[itunes_api.ItunesApiSongModel, itunes_api.ItunesApiAlbumKeys]]:
    """
    Args:
        search_variable (str): the term to search itunes api for
        limit  (int): limit of the search in the api
        mode (modes.Modes): value of album, or song for now
        lookup (bool): if true, perform a lookup search via itunes api rather than a default search
    Returns
        List[Union[itunes_api.ItunesApiSongModel, itunes_api.ItunesApiAlbumKeys]]: a list containing a
            tuple with itunes song properties and album properties
    """
    parsed_results_list = []
    result_dict = {}
    if not lookup:  # perform general search
        search_parameters = {
            "term": search_variable,
            "entity": mode.value,
            "limit": limit,
        }
        itunes_response = requests.get(
            "https://itunes.apple.com/search", params=search_parameters
        )
    else:  # perform lookup query by itunes id
        search_parameters = {
            "id": search_variable,
            "entity": mode.value,
            "limit": limit,
        }
        itunes_response = requests.get(
            "https://itunes.apple.com/lookup", params=search_parameters
        )

    # itunesResponse = requests.get('https://itunes.apple.com/search?term=jack+johnson')
    logger.info(f"Connected to {itunes_response.url}")
    if itunes_response.status_code != 200:
        logger.error(
            "Oops. Something went wrong trying to connect to the itunes server."
        )
        logger.error(
            f"Code: {itunes_response.status_code}, Body: {itunes_response.content}"
        )
        return None

    itunes_json_dict = json.loads(itunes_response.content)
    for index, search_result in enumerate(itunes_json_dict["results"]):
        try:
            if mode == modes.Modes.SONG:
                result = itunes_api.ItunesApiSongModel.model_validate(search_result)
                year = search_result[result.releaseDateKey].split("-")[
                    0
                ]  # will grab the year from date formatted 2016-06-01
                result.releaseDate = year
            elif mode == modes.Modes.ALBUM:
                result = itunes_api.ItunesApiAlbumKeys.model_validate(search_result)

            parsed_results_list.append(result)
        except ValidationError as e:
            logger.warning(
                f"Skipping the display of song at index [{index}] as it could not be loaded into expected format.\n{e}"
            )

    return parsed_results_list