### Install libpytunes Python Library Source: https://github.com/liamks/libpytunes/blob/master/README.md Instructions to install the libpytunes library from its GitHub repository. This involves cloning the repository, navigating into the directory, installing dependencies, and finally installing the library itself. ```shell git clone https://github.com/liamks/libpytunes.git cd libpytunes pip install -r requirements.txt python setup.py install ``` -------------------------------- ### Export Playlist to XSPF Format Source: https://context7.com/liamks/libpytunes/llms.txt This code snippet demonstrates how to export an iTunes playlist to the XSPF (XML Shareable Playlist Format). It utilizes the `getPlaylistxspf` method from the `libpytunes` library. If the optional `xspf` library is not installed, it provides instructions on how to install it and an example of the expected XSPF output structure. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") # Export playlist to XSPF format xspf_output = l.getPlaylistxspf("Summer Hits") if xspf_output: # Save to file with open("summer_hits.xspf", "w") as f: f.write(xspf_output) print("Playlist exported to XSPF format") else: print("XSPF library not installed") print("Install with: pip install xspf") # XSPF format can be used with VLC, Amarok, and other players # Example XSPF output structure: # # # Summer Hits # # # Song Name # Artist Name # file:///path/to/song.mp3 # # # ``` -------------------------------- ### Load and Iterate iTunes Library with libpytunes Source: https://github.com/liamks/libpytunes/blob/master/README.md Example of how to load an iTunes Library XML file using libpytunes and iterate through songs to find those with a rating above 80. It also demonstrates how to retrieve playlist names and iterate through tracks within a specific playlist. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") for id, song in l.songs.items(): if song and song.rating: if song.rating > 80: print(song.name, song.rating) playlists=l.getPlaylistNames() for song in l.getPlaylist(playlists[0]).tracks: print("[{t}] {a} - {n}".format(t=song.track_number, a=song.artist, n=song.name)) ``` -------------------------------- ### Iterate Song Attributes in libpytunes Source: https://github.com/liamks/libpytunes/blob/master/README.md Illustrates how to iterate through the attributes of a Song object provided by the libpytunes library. This example shows a generic loop to access each key-value pair of attributes within a SongItem. ```python for key, value in SongItem: . ``` -------------------------------- ### Get Total Track Count with libpytunes Source: https://github.com/liamks/libpytunes/blob/master/README.md Shows how to get the total number of tracks in the iTunes library using libpytunes. It highlights that libpytunes counts all track types (including Podcasts and Voice Memos), which might result in a higher count than displayed in iTunes. ```python l = Library("iTunes Library.xml") len(l.songs) ``` -------------------------------- ### Initialize iTunes Library Parser in Python Source: https://context7.com/liamks/libpytunes/llms.txt Demonstrates how to load and parse an iTunes Library XML file using the `libpytunes.Library` class. This includes basic usage, handling cross-platform music paths, and a files-only mode to skip tracks without file locations. ```python from libpytunes import Library # Basic usage - load iTunes library l = Library("/Users/username/Music/iTunes/iTunes Library.xml") # Access all songs (returns dict keyed by track_id) print(f"Total tracks: {len(l.songs)}") # Cross-platform path conversion (process XML from different OS) l = Library( "/path/to/iTunes Library.xml", musicPathXML="/Users/username/Music", musicPathSystem="C:\\Users\\username\\Music" ) # Files-only mode (skip tracks without file locations) l = Library("/path/to/iTunes Library.xml", filesOnly=True) ``` -------------------------------- ### Cache iTunes Library using Pickle for Faster Access Source: https://github.com/liamks/libpytunes/blob/master/README.md Demonstrates how to use Python's pickle module to create a cached binary representation of the iTunes Library XML. This significantly speeds up repeated access to the library data, especially for large libraries. The code checks for an existing pickled file and refreshes it if it's stale. ```python import os.path import pickle import time from libpytunes import Library lib_path = "/Users/[username]/Music/iTunes/iTunes Library.xml" pickle_file = "itl.p" expiry = 60 * 60 # Refresh pickled file if older than epoch_time = int(time.time()) # Now # Generate pickled version of database if stale or doesn't exist if not os.path.isfile(pickle_file) or os.path.getmtime(pickle_file) + expiry < epoch_time: itl_source = Library(lib_path) pickle.dump(itl_source, open(pickle_file, "wb")) itl = pickle.load(open(pickle_file, "rb")) for id, song in itl.songs.items(): if song and song.rating: if song.rating > 80: print("{n}, {r}".format(n=song.name, r=song.rating)) ``` -------------------------------- ### Performance Optimization with Pickle Caching Source: https://context7.com/liamks/libpytunes/llms.txt This snippet demonstrates how to significantly speed up repeated access to large iTunes library files by using Python's `pickle` module for caching. It checks if a cached file exists and is recent, otherwise it parses the library and saves it to a pickle file. Loading from the cache is much faster than re-parsing. ```python import os.path import pickle import time from libpytunes import Library lib_path = "/Users/username/Music/iTunes/iTunes Library.xml" pickle_file = "/tmp/itl.pickle" expiry = 60 * 60 # Refresh if older than 1 hour epoch_time = int(time.time()) # Generate or refresh pickled cache if not os.path.isfile(pickle_file) or os.path.getmtime(pickle_file) + expiry < epoch_time: print("Parsing iTunes library and creating cache...") itl_source = Library(lib_path) pickle.dump(itl_source, open(pickle_file, "wb")) print(f"Cached {len(itl_source.songs)} songs to {pickle_file}") else: print("Using cached library data") # Load from cache (up to 10x faster) while True: try: itl = pickle.load(open(pickle_file, "rb")) break except EOFError: print("Cache file is empty or corrupted. Rebuilding.") itl_source = Library(lib_path) pickle.dump(itl_source, open(pickle_file, "wb")) itl = itl_source # Use the loaded library for track_id, song in itl.songs.items(): if song and song.rating and song.rating > 80: print(f"{song.name} - {song.artist} ({song.rating})") # Access playlists from cached data playlists = itl.getPlaylistNames() workout_playlist = itl.getPlaylist("Workout Mix") print(f"Workout playlist has {len(workout_playlist.tracks)} songs") ``` -------------------------------- ### Analyze Playlist Metadata and Types in Python Source: https://context7.com/liamks/libpytunes/llms.txt Shows how to access detailed information about playlists parsed by `libpytunes`, including identifying if a playlist is a smart playlist, a Genius playlist, or a folder containing other playlists. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") # Analyze playlist characteristics playlist = l.getPlaylist("Top 25 Most Played") # Check playlist type if playlist.is_smart_playlist: print("This is a smart playlist with automatic rules") if playlist.is_genius_playlist: print("This is a Genius playlist generated by iTunes") if playlist.is_folder: print("This is a folder containing other playlists") ``` -------------------------------- ### Work with Playlists and Filter Songs in Python Source: https://context7.com/liamks/libpytunes/llms.txt Explains how to retrieve playlist names, access songs within specific playlists using `libpytunes`, and maintain their original order. It also demonstrates filtering songs within a playlist based on criteria like duration. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") # Get all playlist names (excluding default iTunes playlists) playlists = l.getPlaylistNames() print(f"Found {len(playlists)} playlists: {playlists}") # Output: "Found 12 playlists: ['Road Trip', 'Workout Mix', 'Chill Vibes']" # Get all playlists including system ones all_playlists = l.getPlaylistNames(ignoreList=[]) # Access a specific playlist playlist = l.getPlaylist("Road Trip") print(f"Playlist: {playlist.name}") print(f"Playlist ID: {playlist.playlist_id}") print(f"Is Smart Playlist: {playlist.is_smart_playlist}") print(f"Is Genius Playlist: {playlist.is_genius_playlist}") print(f"Total tracks: {len(playlist.tracks)}") # Iterate through songs in playlist order for song in playlist.tracks: print(f"[{song.playlist_order}] {song.artist} - {song.name} (Track {song.track_number})") # Output: "[1] The Beatles - Come Together (Track 1)" # Output: "[2] Queen - Bohemian Rhapsody (Track 11)" # Filter playlist songs long_songs = [s for s in playlist.tracks if s.length and s.length > 300000] # > 5 minutes ``` -------------------------------- ### Calculate Total Library Size and Duration (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This code calculates the total storage size and playback duration of an iTunes library. It sums the 'size' and 'length' attributes of all songs, converting the results to GB and hours for better readability. Songs without size or length information are excluded from the calculation. ```python # Assuming 'l' is an initialized libpytunes library object # Calculate total library statistics total_size = sum(song.size for tid, song in l.songs.items() if song.size) total_duration = sum(song.length for tid, song in l.songs.items() if song.length) print(f"Total library size: {total_size / (1024**3):.2f} GB") print(f"Total play time: {total_duration / 3600000:.2f} hours") ``` -------------------------------- ### Access and Filter Songs by Metadata in Python Source: https://context7.com/liamks/libpytunes/llms.txt Illustrates how to iterate through songs in an iTunes library loaded by `libpytunes` and filter them based on attributes like rating, genre, and play count. It also shows how to access detailed metadata for individual songs. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") # Filter high-rated songs for track_id, song in l.songs.items(): if song and song.rating: if song.rating > 80: print(f"{song.name} - {song.artist} (Rating: {song.rating})") # Output: "Bohemian Rhapsody - Queen (Rating: 100)" # Find songs by genre rock_songs = [song for tid, song in l.songs.items() if song.genre and "Rock" in song.genre] # Find frequently played songs popular = [song for tid, song in l.songs.items() if song.play_count and song.play_count > 50] for song in popular[:5]: print(f"{song.name}: {song.play_count} plays") # Access detailed metadata song = l.songs[12345] # Get song by track_id print(f"Title: {song.name}") print(f"Artist: {song.artist}") print(f"Album: {song.album}") print(f"Year: {song.year}") print(f"Duration: {song.total_time}") print(f"Bit Rate: {song.bit_rate} kbps") print(f"File: {song.location}") print(f"Last Played: {song.lastplayed}") print(f"Play Count: {song.play_count}") print(f"Skip Count: {song.skip_count}") ``` -------------------------------- ### Access Playlist Identifiers and Hierarchy Source: https://context7.com/liamks/libpytunes/llms.txt Demonstrates how to retrieve unique identifiers for playlists, such as playlist_id, persistent_id, and parent_persistent_id. It also shows how to build a hierarchical structure of all playlists, including information about their names, IDs, parent relationships, folder status, and track counts. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") # Access playlist identifiers print(f"Playlist ID: {playlist.playlist_id}") print(f"Persistent ID: {playlist.persistent_id}") print(f"Parent Persistent ID: {playlist.parent_persistent_id}") print(f"Distinguished Kind: {playlist.distinguished_kind}") # Build playlist hierarchy all_playlists = [] for name in l.getPlaylistNames(ignoreList=[]): pl = l.getPlaylist(name) all_playlists.append({ 'name': pl.name, 'id': pl.persistent_id, 'parent': pl.parent_persistent_id, 'is_folder': pl.is_folder, 'track_count': len(pl.tracks) }) ``` -------------------------------- ### Analyze Genre Distribution in iTunes Library (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This code analyzes the genre distribution of songs in an iTunes library. It extracts genres from each song, counts their occurrences using `collections.Counter`, and prints the top 5 most common genres along with their counts. This is useful for understanding the diversity of music within the library. ```python from collections import Counter # Assuming 'l' is an initialized libpytunes library object # Analyze genre distribution genres = [song.genre for tid, song in l.songs.items() if song.genre] genre_counts = Counter(genres) print("Top 5 genres:") for genre, count in genre_counts.most_common(5): print(f" {genre}: {count} songs") ``` -------------------------------- ### Access Comprehensive Song Attributes Source: https://context7.com/liamks/libpytunes/llms.txt Shows how to access a wide range of metadata for individual songs within an iTunes library. This includes basic information, classical music specifics, track and disc details, technical specifications, usage statistics, boolean flags, and file locations. The code iterates through all available attributes of a song object. ```python from libpytunes import Library l = Library("/path/to/iTunes Library.xml") # Access comprehensive song attributes song = list(l.songs.values())[0] # Basic metadata print(f"Name: {song.name}") print(f"Artist: {song.artist}") print(f"Album Artist: {song.album_artist}") print(f"Composer: {song.composer}") print(f"Album: {song.album}") print(f"Genre: {song.genre}") print(f"Year: {song.year}") # Classical music support if song.work: print(f"Work: {song.work}") print(f"Movement: {song.movement_number}/{song.movement_count} - {song.movement_name}") # Track and disc information print(f"Track: {song.track_number}/{song.track_count}") print(f"Disc: {song.disc_number}/{song.disc_count}") # Technical details print(f"Size: {song.size} bytes") print(f"Duration: {song.total_time}") print(f"Bit Rate: {song.bit_rate} kbps") print(f"Sample Rate: {song.sample_rate} Hz") print(f"Kind: {song.kind}") # Ratings and usage print(f"Rating: {song.rating}/100") print(f"Album Rating: {song.album_rating}") print(f"Play Count: {song.play_count}") print(f"Skip Count: {song.skip_count}") print(f"Last Played: {song.lastplayed}") # Booleans and flags print(f"Compilation: {song.compilation}") print(f"Podcast: {song.podcast}") print(f"Movie: {song.movie}") print(f"Has Video: {song.has_video}") print(f"Loved: {song.loved}") print(f"Apple Music: {song.apple_music}") print(f"Protected: {song.protected}") print(f"Disabled: {song.disabled}") # File location print(f"Location: {song.location}") print(f"Location (escaped): {song.location_escaped}") # Iterate through all attributes for key, value in song.__dict__.items(): if value is not None: print(f"{key}: {value}") ``` -------------------------------- ### Find Videos and Movies in iTunes Library (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This snippet shows how to identify video and movie content within an iTunes library. It filters songs based on the 'has_video' and 'movie' attributes, respectively. The output provides the counts for both videos and movies found. ```python # Assuming 'l' is an initialized libpytunes library object # Find videos and movies videos = [song for tid, song in l.songs.items() if song.has_video] movies = [song for tid, song in l.songs.items() if song.movie] print(f"Videos: {len(videos)}, Movies: {len(movies)}") ``` -------------------------------- ### Find Podcasts in iTunes Library (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This snippet demonstrates how to filter songs in an iTunes library to find all podcast episodes. It iterates through the library's songs and checks the 'podcast' attribute. The output is the total count of found podcast episodes. ```python from collections import Counter # Assuming 'l' is an initialized libpytunes library object # Find all podcasts podcasts = [song for tid, song in l.songs.items() if song.podcast] print(f"Found {len(podcasts)} podcast episodes") ``` -------------------------------- ### Find Disabled or Protected Tracks in iTunes Library (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This snippet demonstrates how to find disabled and protected tracks within an iTunes library. It filters songs based on the 'disabled' and 'protected' attributes, respectively. The output provides the counts for both disabled and protected tracks. ```python # Assuming 'l' is an initialized libpytunes library object # Find disabled or protected tracks disabled = [song for tid, song in l.songs.items() if song.disabled] protected = [song for tid, song in l.songs.items() if song.protected] print(f"Disabled: {len(disabled)}, Protected: {len(protected)}") ``` -------------------------------- ### Find Compilation Tracks in iTunes Library (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This code snippet filters an iTunes library to find all tracks that are part of compilations. It iterates through the songs and checks the 'compilation' attribute. The output is the total count of compilation tracks found. ```python # Assuming 'l' is an initialized libpytunes library object # Find compilations compilations = [song for tid, song in l.songs.items() if song.compilation] print(f"{len(compilations)} compilation tracks") ``` -------------------------------- ### Playlist Class Attributes Definition (Python) Source: https://github.com/liamks/libpytunes/blob/master/README.md Defines the attributes for the Playlist class in libpytunes. These attributes represent properties of a music playlist, including its name, IDs, type (folder, genius, smart), and a list of associated songs. No external dependencies are noted for this definition. ```python is_folder: bool = False persistent_id: int = None parent_persistent_id: int = None distinguished_kind = None playlist_id: int = None name: str = None is_genius_playlist: bool = False is_smart_playlist: bool = False tracks: list[Song] = [] ``` -------------------------------- ### Find Unplayed Songs in iTunes Library (Python) Source: https://context7.com/liamks/libpytunes/llms.txt This snippet identifies songs that have never been played or have a play count of zero in an iTunes library. It filters songs where the 'play_count' attribute is either None or 0. The output is the number of such unplayed songs. ```python # Assuming 'l' is an initialized libpytunes library object # Find songs never played unplayed = [song for tid, song in l.songs.items() if song.play_count is None or song.play_count == 0] print(f"{len(unplayed)} songs never played") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.