import os from mido import MetaMessage from Song import Song import mido class Library(object): def __init__(self): self.songs = [] def initialize(self, songs_dir: str): print("Initializing library") for root, dirs, files in os.walk(songs_dir): for i, file in enumerate(files): if file.endswith('.mid'): name = file.split('-')[0] author = file.split('-')[1].split('.')[0] path = os.path.join(root, file) song = Song(i, name, author, path, self.get_request_count_from_midi_file(path)) print(f"Loaded song: {song.name} by {song.author} with {song.total_requests} requests") self.songs.append(song) def get_request_count_from_midi_file(self, file_path): mid = mido.MidiFile(file_path) for i, track in enumerate(mid.tracks): for msg in track: if msg.type == 'text' and 'Request count:' in msg.text: return int(msg.text.split(': ')[1]) # If no 'text' MetaMessage with the request count is found, add one with a count of 0 msg = MetaMessage('text', text='Request count: 0') mid.tracks[0].append(msg) mid.save(file_path) return 0 def get_song_list(self) -> str: sorted = self.songs.copy() sorted.sort(key=lambda x: x.total_requests, reverse=True) song_list = "" for song in sorted: song_list += f"{song.id}: {song.name} by {song.author}\n" return song_list def get_song_by_id(self, id: int) -> Song: for song in self.songs: if song.id == id: # Increment the request count song.total_requests += 1 # Load the MIDI file mid = mido.MidiFile(song.path) # Remove the old 'text' MetaMessage with the request count for i, track in enumerate(mid.tracks): for j, msg in enumerate(track): if msg.type == 'text' and 'Request count:' in msg.text: del track[j] # Add a new 'text' MetaMessage with the updated request count mid.tracks[0].append(MetaMessage('text', text=f'Request count: {song.total_requests}')) # Save the MIDI file mid.save(song.path) return song return None