import gradio as gr from time import sleep from src.evolutionary_alrogithm import Individual, differential_mutation, simple_mutation, MUTATION_OPTIONS, CROSSOVER_OPTIONS, THUMBS_UP, THUMBS_DOWN, ADD_TO_PLAYLIST from src.spotipy_utils import add_tracks_to_playlist, search_for_track, SpotifyTrack # IMGs ADDED_TO_PLAYLIST = "✅ Added to Library!" FAILED_TO_ADD = """❌ Failed to connect to your account. Make sure to that you clicked the link in the description to login and use the app from the window that opens there.\n Also check to make sure have entered a valid playlist name and have reached out to the listed email to be added to the user list.""" # Evolutionary Algorithm Parameters. SEED_OPTIONS = ["yes", "no"] def set_crossover_option(radio_selection:str): """ Set the crossover option for the internal evolutionary algorithm. Args: radio_selection (str): Selected crossover option. Returns: bool: The state value flagging whether or not to do crossover. """ if radio_selection == CROSSOVER_OPTIONS[0]: do_crossover = False else: do_crossover = True return do_crossover def set_mutation_option(population, do_crossover, radio_selection:str) -> bool: """ Set the mutation option for the internal evolutionary algorithm. Args: population (Population): Population of tracks. radio_selection (str): Selected mutation option. Returns: tuple: Slider update for mutation rate and Radio update for crossover options. """ if radio_selection == MUTATION_OPTIONS[0]: do_mutation = False updated_slider = gr.Slider.update(visible=False) updated_crossover_button = gr.Radio.update(visible=True) elif radio_selection == MUTATION_OPTIONS[2]: do_mutation = True updated_slider = gr.Slider.update(visible=True) updated_crossover_button = gr.Radio.update(visible=False, value=CROSSOVER_OPTIONS[0]) do_crossover = False population.mutation_function = differential_mutation else: do_mutation = True updated_slider = gr.Slider.update(visible=True) updated_crossover_button = gr.Radio.update(visible=True) population.mutation_function = simple_mutation return updated_slider, updated_crossover_button, do_crossover, do_mutation, population def update_mutation_size(population, mutation_size_slider_value:str): """Update the mutation rate according the slider value. Args: mutation_size_slider_value (str): Value from the slider input. """ population.mutation_size = float(mutation_size_slider_value) return population def set_track_state(population, track_index:str, dropdown_value:str): """Sets the decision status of the track for the corresponding dropdown menu. Args: track_index (str): Index of the track in the population array. dropdown_value (str): Value selected from the track's decision dropdown. """ population.pop[int(track_index)].status = dropdown_value return population def get_next_generation(population, do_mutation, do_crossover): """ Updates the display grid, the playlist display, and the historical tracking vizualization for the next generation. Returns: tuple: Current playlist display, track image, name, option, and preview blocks, and tracking history visualization. """ if not population.pop and not population.search_seed: pop_container = gr.Box().update(visible=True) options_container = gr.Box().update(visible=True) population.reinitialize_pop() elif population.search_seed: pop_container = gr.Box().update(visible=True) options_container = gr.Box().update(visible=False) else: pop_container = gr.Box().update() options_container = gr.Box().update() thumbs_up = population.get_tracks_with_status(THUMBS_UP) thumbs_down = population.get_tracks_with_status(THUMBS_DOWN) added_songs = population.get_tracks_with_status(ADD_TO_PLAYLIST) for added_track in added_songs: population.add_to_playlist(added_track) playlist_display = gr.TextArea.update( value=population.get_playlist_block_value() ) # HANDLING FOR IF NO SONGS ARE SELECTED! if population.search_seed: population.mutate([population.search_seed], [], []) elif not thumbs_up and not added_songs: population.reinitialize_pop() else: if do_crossover and do_mutation: population.crossover(thumbs_up, thumbs_down, added_songs) population.mutate(population.pop, [], []) elif do_crossover: population.crossover(thumbs_up, thumbs_down, added_songs) elif do_mutation: population.mutate(thumbs_up, thumbs_down, added_songs) # GET IMAGES AND PREVIEWS FOR NEW POPULATION. image_blocks = [] name_blocks = [] preview_blocks = [] dropdown_blocks = [] for track in population.pop: image_blocks.append(gr.Image.update(value=track.get_image_url())) name_blocks.append(gr.Markdown.update(value=f"{track.name} by {track.artist}")) dropdown_blocks.append(gr.Dropdown.update(value=None)) song_preview = track.get_preview_url() if song_preview: preview_blocks.append(gr.Audio.update(value=song_preview, visible=True)) else: preview_blocks.append(gr.Audio.update(value=song_preview, visible=False)) # Update historical df and traversal visualization. population.update_population_history(thumbs_up, thumbs_down, added_songs) updated_viz = population.generate_traversal_viz() new_traversal_tracker = gr.Plot.update(updated_viz) return (pop_container, options_container, population, playlist_display, *image_blocks, *name_blocks, *dropdown_blocks, *preview_blocks, new_traversal_tracker) def change_seed_option(seed_option, population): """Change the option for whether or not to seed the next generation. Args: seed_option (str): Selected option. population (Population): The population for the evolutionary algorithm. Returns: tuple: Updated seed search input, seed dropdown, and population. """ if seed_option == SEED_OPTIONS[0]: seed_options_container = gr.Box().update(visible=True) search_results = gr.Dropdown.update() seed_artist_search = gr.Textbox().update() seed_track_search = gr.Textbox().update() mutation_options_container = gr.Box().update(visible=False) else: population.search_results = None population.search_seed = None search_results = gr.Dropdown.update(choices=[]) seed_artist_search = gr.Textbox().update(value="") seed_track_search = gr.Textbox().update(value="") seed_options_container = gr.Box().update(visible=False) mutation_options_container = gr.Box().update(visible=True) return seed_options_container, mutation_options_container, seed_track_search, seed_artist_search, search_results, population def search_for_seed(population, artist, track): """Facilitate the UI input for a track query to the Spotify API. Args: population (Population): The population for the evolutionary algorithm. search_term (str): Search query. Returns: tuple: Updated population with the search results, track choices for the seed dropdown in the UI. """ results_dict = search_for_track(track, artist) population.search_results = results_dict return population, gr.Dropdown.update(choices=[f"{info['name']} by {info['artist']}" for info in results_dict.values()]) def set_pop_seed(population, population_seed:str): """Set the seed for the next generation via the seed results dropdown. Args: population (Population): The population for the evolutionary algorithm. population_seed (str): Query string for the Spotify API. Returns: Population: The old population with the generation seed updated. """ track_name, artist_name = population_seed.split(" by ") seed_track_id = population.search_results[track_name+"_"+artist_name]["track_id"] seed_track = SpotifyTrack(seed_track_id) population.search_seed = Individual(None, seed_track) population.mutation = simple_mutation return population def add_playlist_to_spotify(population, playlist_name:str, request: gr.Request): """Add curated playlist to authenticated user's playlist library. Playlist will be added as public. Args: population (Population): The population for the evolutionary algorithm. playlist_name (str): Name of the playlist to be created. auth_url (str): Authorization URL provided by user. Returns: gr.Markdown.update: Message displaying the success of the attempt to add to library. """ added = add_tracks_to_playlist(playlist_name, population, request) if not added: return gr.Markdown.update(FAILED_TO_ADD, visible=True) return gr.Markdown.update(ADDED_TO_PLAYLIST, visible=True) def generate_population_direction_tracking_viz(population): population.generate_direction_tracking()