File size: 9,227 Bytes
9b43d0b
6c99a56
 
 
9b43d0b
 
 
 
 
 
 
 
 
 
f3862e0
 
9b43d0b
f3862e0
 
9b43d0b
f3862e0
 
 
 
 
 
 
9b43d0b
f3862e0
9b43d0b
 
f3862e0
 
9b43d0b
f3862e0
 
 
9b43d0b
f3862e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c99a56
9b43d0b
f3862e0
9b43d0b
 
f3862e0
 
9b43d0b
f3862e0
 
 
 
 
9b43d0b
 
f3862e0
 
9b43d0b
f3862e0
 
 
 
25d03ce
f3862e0
9b43d0b
 
f3862e0
 
9b43d0b
f3862e0
 
 
36e9149
98682ad
dfaebc9
 
98682ad
36e9149
 
 
98682ad
 
dfaebc9
 
771ead9
f3862e0
 
 
98682ad
f3862e0
 
9b43d0b
f3862e0
 
 
9b43d0b
f3862e0
36e9149
6c99a56
 
f3862e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b43d0b
f3862e0
 
 
 
 
 
98682ad
dfaebc9
f3862e0
 
6c99a56
771ead9
 
 
 
 
 
 
 
 
6c99a56
36e9149
 
 
 
 
6c99a56
 
 
36e9149
 
 
 
 
 
 
 
6c99a56
 
36e9149
771ead9
 
 
 
 
 
 
 
 
36e9149
6c99a56
 
 
 
771ead9
 
 
 
 
 
 
 
 
 
6c99a56
 
0c2f72a
 
6c99a56
 
f3862e0
 
16969ba
f3862e0
 
 
771ead9
f3862e0
771ead9
f3862e0
 
 
 
6190ef7
f3862e0
 
 
 
 
771ead9
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
64
65
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
126
127
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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()