docstring added
Browse files- app.py +22 -28
- spotify_music_recommender.py +99 -99
app.py
CHANGED
@@ -9,6 +9,14 @@ if "song_init" not in st.session_state:
|
|
9 |
|
10 |
|
11 |
def song_page(name, year):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
song_uri = smr.find_song_uri(name, year)
|
13 |
formatted_song_uri = song_uri.split(':')[-1]
|
14 |
uri_link = f'https://open.spotify.com/embed/track/{formatted_song_uri}?utm_source=generator'
|
@@ -30,39 +38,29 @@ def spr_sidebar():
|
|
30 |
st.session_state.app_mode = 'Results'
|
31 |
elif menu == 'About':
|
32 |
st.session_state.app_mode = 'About'
|
33 |
-
# elif menu == 'How It Works':
|
34 |
-
# st.session_state.app_mode = 'How It Works'
|
35 |
-
|
36 |
|
37 |
def home_page():
|
38 |
|
39 |
-
# App layout
|
40 |
st.title("Spotify Music Recommender")
|
41 |
|
42 |
-
# Song input section
|
43 |
-
# st.subheader("")
|
44 |
col1, col2 = st.columns(2)
|
45 |
song_input = col1.text_input("Enter a song:")
|
46 |
year_input = col2.text_input("Enter the year:")
|
47 |
|
48 |
-
# Button section
|
49 |
-
# st.subheader("")
|
50 |
col3, col4 = st.columns(2)
|
51 |
find_song_button = col3.button("Find Song")
|
52 |
find_random_song_button = col4.button("Random Song")
|
53 |
|
54 |
-
# Critic input section
|
55 |
st.subheader("Song Review")
|
56 |
critic_input = st.text_input("")
|
57 |
|
58 |
-
# Prediction button
|
59 |
predict_button = st.button("Start Prediction")
|
60 |
|
61 |
if find_song_button:
|
62 |
song_page(song_input, year_input)
|
63 |
elif find_random_song_button:
|
64 |
find_random_song()
|
65 |
-
elif
|
66 |
st.session_state.song_init = True
|
67 |
find_random_song()
|
68 |
|
@@ -75,28 +73,28 @@ def home_page():
|
|
75 |
song_cluster_pipeline, data, number_cols = smr.get_model_values(
|
76 |
data_path, file_path, cluster_labels)
|
77 |
user_critic_text = critic_input
|
78 |
-
|
79 |
song_input, year_input, number_cols, user_critic_text)
|
80 |
-
|
81 |
-
|
82 |
-
st.session_state.song_uris = smr.
|
83 |
st.write("You can access recommended song at result page")
|
84 |
except:
|
85 |
st.write("An error occured please try again")
|
86 |
|
87 |
|
88 |
-
|
89 |
-
|
90 |
|
91 |
-
#
|
92 |
-
|
93 |
-
|
94 |
|
95 |
-
#
|
96 |
-
|
97 |
|
98 |
-
#
|
99 |
-
|
100 |
|
101 |
|
102 |
def find_random_song():
|
@@ -171,10 +169,6 @@ def main():
|
|
171 |
result_page()
|
172 |
if st.session_state.app_mode == 'About':
|
173 |
About_page()
|
174 |
-
# if st.session_state.app_mode == 'How It Works':
|
175 |
-
# examples_page()
|
176 |
-
|
177 |
|
178 |
-
# Run main()
|
179 |
if __name__ == '__main__':
|
180 |
main()
|
|
|
9 |
|
10 |
|
11 |
def song_page(name, year):
|
12 |
+
"""
|
13 |
+
Displays the Spotify song with the given name and year using an iframe.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
name (str): The name of the song.
|
17 |
+
year (str): The year of the song.
|
18 |
+
"""
|
19 |
+
|
20 |
song_uri = smr.find_song_uri(name, year)
|
21 |
formatted_song_uri = song_uri.split(':')[-1]
|
22 |
uri_link = f'https://open.spotify.com/embed/track/{formatted_song_uri}?utm_source=generator'
|
|
|
38 |
st.session_state.app_mode = 'Results'
|
39 |
elif menu == 'About':
|
40 |
st.session_state.app_mode = 'About'
|
|
|
|
|
|
|
41 |
|
42 |
def home_page():
|
43 |
|
|
|
44 |
st.title("Spotify Music Recommender")
|
45 |
|
|
|
|
|
46 |
col1, col2 = st.columns(2)
|
47 |
song_input = col1.text_input("Enter a song:")
|
48 |
year_input = col2.text_input("Enter the year:")
|
49 |
|
|
|
|
|
50 |
col3, col4 = st.columns(2)
|
51 |
find_song_button = col3.button("Find Song")
|
52 |
find_random_song_button = col4.button("Random Song")
|
53 |
|
|
|
54 |
st.subheader("Song Review")
|
55 |
critic_input = st.text_input("")
|
56 |
|
|
|
57 |
predict_button = st.button("Start Prediction")
|
58 |
|
59 |
if find_song_button:
|
60 |
song_page(song_input, year_input)
|
61 |
elif find_random_song_button:
|
62 |
find_random_song()
|
63 |
+
elif not st.session_state.song_init:
|
64 |
st.session_state.song_init = True
|
65 |
find_random_song()
|
66 |
|
|
|
73 |
song_cluster_pipeline, data, number_cols = smr.get_model_values(
|
74 |
data_path, file_path, cluster_labels)
|
75 |
user_critic_text = critic_input
|
76 |
+
raw_recommendation_array = smr.get_recommendation_array(
|
77 |
song_input, year_input, number_cols, user_critic_text)
|
78 |
+
result = smr.format_chatgpt_recommendations (
|
79 |
+
raw_recommendation_array, data, song_cluster_pipeline, 15)
|
80 |
+
st.session_state.song_uris = smr.get_recommendation_song_uri(result)
|
81 |
st.write("You can access recommended song at result page")
|
82 |
except:
|
83 |
st.write("An error occured please try again")
|
84 |
|
85 |
|
86 |
+
def text_field(label, columns=None, **input_params):
|
87 |
+
c1, c2 = st.columns(columns or [1, 4])
|
88 |
|
89 |
+
# Display field name with some alignment
|
90 |
+
c1.markdown("##")
|
91 |
+
c1.markdown(label)
|
92 |
|
93 |
+
# Sets a default key parameter to avoid duplicate key errors
|
94 |
+
input_params.setdefault("key", label)
|
95 |
|
96 |
+
# Forward text input parameters
|
97 |
+
return c2.text_input("", **input_params)
|
98 |
|
99 |
|
100 |
def find_random_song():
|
|
|
169 |
result_page()
|
170 |
if st.session_state.app_mode == 'About':
|
171 |
About_page()
|
|
|
|
|
|
|
172 |
|
|
|
173 |
if __name__ == '__main__':
|
174 |
main()
|
spotify_music_recommender.py
CHANGED
@@ -1,13 +1,3 @@
|
|
1 |
-
#!/usr/bin/env python
|
2 |
-
# coding: utf-8
|
3 |
-
|
4 |
-
# # **Import Libraries**
|
5 |
-
|
6 |
-
# In[22]:
|
7 |
-
|
8 |
-
|
9 |
-
# import os
|
10 |
-
# import difflib
|
11 |
import numpy as np
|
12 |
import pandas as pd
|
13 |
import openai
|
@@ -29,10 +19,17 @@ from collections import defaultdict
|
|
29 |
import warnings
|
30 |
warnings.filterwarnings("ignore")
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
data = pd.read_csv("data/data.csv")
|
37 |
|
38 |
song_cluster_pipeline = Pipeline([('scaler', StandardScaler()),
|
@@ -41,18 +38,37 @@ def get_pipeline_data_number_cols():
|
|
41 |
], verbose=False)
|
42 |
|
43 |
X = data.select_dtypes(np.number)
|
44 |
-
|
45 |
song_cluster_pipeline.fit(X)
|
46 |
song_cluster_labels = song_cluster_pipeline.predict(X)
|
47 |
data['cluster_label'] = song_cluster_labels
|
48 |
|
49 |
-
return song_cluster_pipeline, data,
|
50 |
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
|
55 |
def find_song(name, year):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
if os.path.isfile(".\secret_keys.py"):
|
57 |
import secret_keys
|
58 |
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
|
@@ -69,7 +85,6 @@ def find_song(name, year):
|
|
69 |
results = results['tracks']['items'][0]
|
70 |
track_id = results['id']
|
71 |
audio_features = sp.audio_features(track_id)[0]
|
72 |
-
|
73 |
song_data['name'] = [name]
|
74 |
song_data['year'] = [year]
|
75 |
song_data['explicit'] = [int(results['explicit'])]
|
@@ -83,6 +98,17 @@ def find_song(name, year):
|
|
83 |
|
84 |
|
85 |
def find_song_uri(name, year):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
# Create a Spotify client object.
|
87 |
if os.path.isfile(".\secret_keys.py"):
|
88 |
import secret_keys
|
@@ -91,26 +117,23 @@ def find_song_uri(name, year):
|
|
91 |
else:
|
92 |
client = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
|
93 |
client_id=os.environ.get("client_id"), client_secret=os.environ.get("client_secret")))
|
94 |
-
# Get the name of the song you want to get the ID for.
|
95 |
-
song_name = name
|
96 |
-
# Call the `search` method with the song name.
|
97 |
results = client.search(q='track: {} year: {}'.format(name, year), limit=1)
|
98 |
-
# Get the first result.
|
99 |
track = results['tracks']['items'][0]
|
100 |
-
# The Spotify ID of the song will be in the `id` property.
|
101 |
song_id = track['uri']
|
102 |
return song_id
|
103 |
|
104 |
|
105 |
-
def format_song(song_data, number_cols):
|
106 |
-
list_song_data = song_data[number_cols].values.tolist()[0]
|
107 |
-
list_song_data = '[' + ', '.join([str(num)
|
108 |
-
for num in list_song_data]) + ']'
|
109 |
-
return list_song_data
|
110 |
-
|
111 |
-
|
112 |
def get_response(text):
|
|
|
|
|
|
|
|
|
|
|
113 |
|
|
|
|
|
|
|
|
|
114 |
if os.path.isfile(".\secret_keys.py"):
|
115 |
import secret_keys
|
116 |
openai.api_key = secret_keys.openai_api_key
|
@@ -130,13 +153,10 @@ def get_response(text):
|
|
130 |
return response.choices[0].get("text")
|
131 |
|
132 |
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
init_text = "I want you to act as a song recommender. I will provide you songs data with following format f future_columns=[ <valence>, <published_year>, <acousticness>, <danceability>, <duration_ms>, <energy>, <explicit>,<instrumentalness>, <key>, <liveness>, <loudness>, <mode>, <popularity>, <speechiness>, <tempo>] \
|
138 |
-
values and user critic about the given song. And you will provide an array based on user critic.You must change at least 3 features. Do not write any explanations or other words, just return an array that include changes in future_columns\
|
139 |
-
and here is the describe values of future_columns \n\
|
140 |
valence year acousticness danceability duration_ms energy explicit instrumentalness key liveness loudness mode popularity speechiness tempo \n \
|
141 |
count 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 \n \
|
142 |
mean 0.528587211 1976.787241 0.502114764 0.537395535 230948.3107 0.482388835 0.084575132 0.167009581 5.199844128 0.205838655 -11.46799004 0.706902311 31.43179434 0.098393262 116.8615896 \n \
|
@@ -148,112 +168,92 @@ def get_text(user_critic, list_song_data):
|
|
148 |
max 1 2020 0.996 0.988 5403500 1 1 1 11 1 3.855 1 100 0.97 243.507"
|
149 |
|
150 |
# init_last = "\n\n start with only typing random future_columns values in given range as a array"
|
151 |
-
#
|
152 |
-
user_critic_last = "your output will be future_columns=[ <valence>, <published_year>, <acousticness>, <danceability>, <duration_ms>, <energy>, <explicit>,<instrumentalness>, <key>, <liveness>, <loudness>, <mode>, <popularity>, <speechiness>, <tempo>] format"
|
153 |
-
user_last = "\n\n start with the adjust following future_columns based on user_critic. "
|
154 |
# example_features = "future_columns=[0.68, 1976, 0.78, 0.62, 230948.3, 0.44, 0.22, 0.43, 5.2, 0.27, -9.67, 1, 31, 0.19, 118.86]"
|
155 |
-
# feature_col_starter = "future_columns="
|
156 |
-
real_features = "future_columns=" + list_song_data
|
157 |
-
|
158 |
-
# init_input = init_text + init_last
|
159 |
# test_input = init_text + user_last + user_critic + example_features + user_critic_last
|
|
|
|
|
|
|
|
|
160 |
real_input = init_text + user_last + \
|
161 |
-
user_critic +
|
162 |
|
163 |
return real_input
|
164 |
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
def format_gpt_output(rec_splitted):
|
170 |
-
formatted = rec_splitted[3:-1].split(",")
|
171 |
list_song_data = [float(i) for i in formatted]
|
172 |
return list_song_data
|
173 |
|
|
|
|
|
|
|
|
|
|
|
174 |
|
175 |
-
|
|
|
|
|
176 |
|
|
|
|
|
|
|
177 |
|
178 |
-
|
179 |
-
|
|
|
|
|
|
|
180 |
'instrumentalness', 'key', 'liveness', 'loudness', 'mode', 'popularity', 'speechiness', 'tempo']
|
181 |
|
182 |
metadata_cols = ['name', 'year', 'artists']
|
183 |
song_center = np.array(song_list)
|
184 |
-
|
185 |
scaler = song_cluster_pipeline.steps[0][1]
|
186 |
-
scaled_data = scaler.transform(spotify_data[
|
187 |
scaled_song_center = scaler.transform(song_center.reshape(1, -1))
|
188 |
-
|
189 |
distances = cdist(scaled_song_center, scaled_data, 'cosine')
|
190 |
index = list(np.argsort(distances)[:, :n_songs][0])
|
191 |
-
|
192 |
rec_songs = spotify_data.iloc[index]
|
193 |
# rec_songs = rec_songs[~rec_songs['name'].isin(song_dict['name'])]
|
194 |
return rec_songs[metadata_cols].to_dict(orient='records')
|
195 |
|
196 |
-
|
197 |
-
# In[28]:
|
198 |
-
|
199 |
-
|
200 |
-
def get_rec_song_uri(res):
|
201 |
song_spotipy_info = []
|
202 |
for song in res:
|
203 |
song_spotipy_info.append(find_song_uri(song["name"], song["year"]))
|
204 |
return song_spotipy_info
|
205 |
|
206 |
-
|
207 |
-
# In[30]:
|
208 |
-
|
209 |
-
|
210 |
-
def get_recommendation_array(song_name, song_year, number_cols, user_critic_text):
|
211 |
song_data = find_song(song_name, song_year)
|
212 |
-
list_song_data =
|
213 |
user_critic = "\n \"user_critic=" + user_critic_text
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
return rec_splitted
|
218 |
|
219 |
|
220 |
-
# In[34]:
|
221 |
-
|
222 |
def get_random_song():
|
223 |
data = pd.read_csv("data/data.csv")
|
224 |
sample = data.sample(n=1)
|
225 |
return sample.name, sample.year
|
226 |
|
227 |
-
|
228 |
-
def get_model_values(data_path, file_path, cluster_path):
|
229 |
-
data_path = data_path
|
230 |
-
file_path = file_path
|
231 |
-
cluster_path = cluster_path
|
232 |
-
# Load the pipeline from the pickle file
|
233 |
-
with open(file_path, 'rb') as file:
|
234 |
-
loaded_pipeline = pickle.load(file)
|
235 |
-
data = pd.read_csv(data_path)
|
236 |
-
labels = pd.read_csv(cluster_path)
|
237 |
-
data["cluster_label"] = labels["cluster_label"]
|
238 |
-
number_cols = ['valence', 'year', 'acousticness', 'danceability', 'duration_ms', 'energy', 'explicit',
|
239 |
-
'instrumentalness', 'key', 'liveness', 'loudness', 'mode', 'popularity', 'speechiness', 'tempo']
|
240 |
-
return loaded_pipeline, data, number_cols
|
241 |
-
|
242 |
-
|
243 |
def control():
|
244 |
-
# song_cluster_pipeline, data,
|
245 |
data_path = "data/data.csv"
|
246 |
file_path = "data/pipeline.pkl"
|
247 |
cluster_labels = "data/cluster_labels.csv"
|
248 |
-
song_cluster_pipeline, data,
|
249 |
data_path, file_path, cluster_labels)
|
250 |
|
251 |
user_critic_text = "it was dull and very loud"
|
252 |
song_name = "Poem of a Killer"
|
253 |
song_year = 2022
|
254 |
-
|
255 |
-
song_name, song_year,
|
256 |
-
|
257 |
-
|
258 |
-
print(
|
259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import numpy as np
|
2 |
import pandas as pd
|
3 |
import openai
|
|
|
19 |
import warnings
|
20 |
warnings.filterwarnings("ignore")
|
21 |
|
22 |
+
def feature_get_pipeline_data_column_names():
|
23 |
+
"""
|
24 |
+
Reads data from a CSV file, performs K-means clustering on numeric columns,
|
25 |
+
and assigns cluster labels to the data.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
- song_cluster_pipeline: Pipeline object containing the scaler and K-means model.
|
29 |
+
- data: DataFrame with the original data and cluster labels.
|
30 |
+
- feature_column_names: List of column names containing numeric values.
|
31 |
+
"""
|
32 |
+
|
33 |
data = pd.read_csv("data/data.csv")
|
34 |
|
35 |
song_cluster_pipeline = Pipeline([('scaler', StandardScaler()),
|
|
|
38 |
], verbose=False)
|
39 |
|
40 |
X = data.select_dtypes(np.number)
|
41 |
+
feature_column_names = list(X.columns)
|
42 |
song_cluster_pipeline.fit(X)
|
43 |
song_cluster_labels = song_cluster_pipeline.predict(X)
|
44 |
data['cluster_label'] = song_cluster_labels
|
45 |
|
46 |
+
return song_cluster_pipeline, data, feature_column_names
|
47 |
|
48 |
+
def get_model_values(data_path, file_path, cluster_path):
|
49 |
+
|
50 |
+
with open(file_path, 'rb') as file:
|
51 |
+
loaded_pipeline = pickle.load(file)
|
52 |
+
data = pd.read_csv(data_path)
|
53 |
+
labels = pd.read_csv(cluster_path)
|
54 |
+
data["cluster_label"] = labels["cluster_label"]
|
55 |
+
feature_column_names = ['valence', 'year', 'acousticness', 'danceability', 'duration_ms', 'energy', 'explicit',
|
56 |
+
'instrumentalness', 'key', 'liveness', 'loudness', 'mode', 'popularity', 'speechiness', 'tempo']
|
57 |
+
return loaded_pipeline, data, feature_column_names
|
58 |
|
59 |
|
60 |
def find_song(name, year):
|
61 |
+
"""
|
62 |
+
Finds a song on Spotify based on the song name and year.
|
63 |
+
|
64 |
+
Args:
|
65 |
+
- name: Name of the song.
|
66 |
+
- year: Year of the song.
|
67 |
+
|
68 |
+
Returns:
|
69 |
+
- DataFrame containing the song's data.
|
70 |
+
"""
|
71 |
+
|
72 |
if os.path.isfile(".\secret_keys.py"):
|
73 |
import secret_keys
|
74 |
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
|
|
|
85 |
results = results['tracks']['items'][0]
|
86 |
track_id = results['id']
|
87 |
audio_features = sp.audio_features(track_id)[0]
|
|
|
88 |
song_data['name'] = [name]
|
89 |
song_data['year'] = [year]
|
90 |
song_data['explicit'] = [int(results['explicit'])]
|
|
|
98 |
|
99 |
|
100 |
def find_song_uri(name, year):
|
101 |
+
"""
|
102 |
+
Finds the Spotify URI of a song based on the song name and year.
|
103 |
+
|
104 |
+
Args:
|
105 |
+
- name: Name of the song.
|
106 |
+
- year: Year of the song.
|
107 |
+
|
108 |
+
Returns:
|
109 |
+
- Spotify URI of the song.
|
110 |
+
"""
|
111 |
+
|
112 |
# Create a Spotify client object.
|
113 |
if os.path.isfile(".\secret_keys.py"):
|
114 |
import secret_keys
|
|
|
117 |
else:
|
118 |
client = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
|
119 |
client_id=os.environ.get("client_id"), client_secret=os.environ.get("client_secret")))
|
|
|
|
|
|
|
120 |
results = client.search(q='track: {} year: {}'.format(name, year), limit=1)
|
|
|
121 |
track = results['tracks']['items'][0]
|
|
|
122 |
song_id = track['uri']
|
123 |
return song_id
|
124 |
|
125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
def get_response(text):
|
127 |
+
"""
|
128 |
+
Retrieves a response using OpenAI's GPT-3 language model.
|
129 |
+
|
130 |
+
Args:
|
131 |
+
- input_text: The input text for the model.
|
132 |
|
133 |
+
Returns:
|
134 |
+
- Generated response as a string.
|
135 |
+
"""
|
136 |
+
|
137 |
if os.path.isfile(".\secret_keys.py"):
|
138 |
import secret_keys
|
139 |
openai.api_key = secret_keys.openai_api_key
|
|
|
153 |
return response.choices[0].get("text")
|
154 |
|
155 |
|
156 |
+
def get_finetune_text(user_critic, list_song_data):
|
157 |
+
init_text = "I want you to act as a song recommender. I will provide you songs data with following format future_columns=[ <valence>, <published_year>, <acousticness>, <danceability>, <duration_ms>, <energy>, <explicit>,<instrumentalness>, <key>, <liveness>, <loudness>, <mode>, <popularity>, <speechiness>, <tempo>] \
|
158 |
+
values and user critic about the given song. And you will change given array values based on user critic and return result array. Do not write any explanations or other words, just return an array that include changes in future_columns\
|
159 |
+
and here is the np.describe() values of future_columns \n\
|
|
|
|
|
|
|
160 |
valence year acousticness danceability duration_ms energy explicit instrumentalness key liveness loudness mode popularity speechiness tempo \n \
|
161 |
count 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 170653 \n \
|
162 |
mean 0.528587211 1976.787241 0.502114764 0.537395535 230948.3107 0.482388835 0.084575132 0.167009581 5.199844128 0.205838655 -11.46799004 0.706902311 31.43179434 0.098393262 116.8615896 \n \
|
|
|
168 |
max 1 2020 0.996 0.988 5403500 1 1 1 11 1 3.855 1 100 0.97 243.507"
|
169 |
|
170 |
# init_last = "\n\n start with only typing random future_columns values in given range as a array"
|
171 |
+
# user_critic_example = "\n \"user_critic=it was too old and loud but i like the energy\" "
|
|
|
|
|
172 |
# example_features = "future_columns=[0.68, 1976, 0.78, 0.62, 230948.3, 0.44, 0.22, 0.43, 5.2, 0.27, -9.67, 1, 31, 0.19, 118.86]"
|
|
|
|
|
|
|
|
|
173 |
# test_input = init_text + user_last + user_critic + example_features + user_critic_last
|
174 |
+
|
175 |
+
user_critic_last = "your output will be future_columns=[ <valence>, <published_year>, <acousticness>, <danceability>, <duration_ms>, <energy>, <explicit>,<instrumentalness>, <key>, <liveness>, <loudness>, <mode>, <popularity>, <speechiness>, <tempo>] format"
|
176 |
+
user_last = "\n\n start with the adjust following future_columns based on user_critic. "
|
177 |
+
features = "future_columns=" + list_song_data
|
178 |
real_input = init_text + user_last + \
|
179 |
+
user_critic + features + user_critic_last
|
180 |
|
181 |
return real_input
|
182 |
|
183 |
|
184 |
+
def format_gpt_output(raw_recommendation_array):
|
185 |
+
formatted = raw_recommendation_array[3:-1].split(",")
|
|
|
|
|
|
|
186 |
list_song_data = [float(i) for i in formatted]
|
187 |
return list_song_data
|
188 |
|
189 |
+
def format_song_string(song_data, feature_column_names):
|
190 |
+
list_song_data = song_data[feature_column_names].values.tolist()[0]
|
191 |
+
list_song_data = '[' + ', '.join([str(num)
|
192 |
+
for num in list_song_data]) + ']'
|
193 |
+
return list_song_data
|
194 |
|
195 |
+
def format_chatgpt_recommendations(song_list, spotify_data, song_cluster_pipeline, n_songs=15):
|
196 |
+
"""
|
197 |
+
Recommends a song using OpenAI's GPT-3 language model.
|
198 |
|
199 |
+
Args:
|
200 |
+
- song_name: The name of the song.
|
201 |
+
- song_year: The year of the song.
|
202 |
|
203 |
+
Returns:
|
204 |
+
- Recommended song as a list of string.
|
205 |
+
"""
|
206 |
+
|
207 |
+
feature_column_names = ['valence', 'year', 'acousticness', 'danceability', 'duration_ms', 'energy', 'explicit',
|
208 |
'instrumentalness', 'key', 'liveness', 'loudness', 'mode', 'popularity', 'speechiness', 'tempo']
|
209 |
|
210 |
metadata_cols = ['name', 'year', 'artists']
|
211 |
song_center = np.array(song_list)
|
|
|
212 |
scaler = song_cluster_pipeline.steps[0][1]
|
213 |
+
scaled_data = scaler.transform(spotify_data[feature_column_names])
|
214 |
scaled_song_center = scaler.transform(song_center.reshape(1, -1))
|
|
|
215 |
distances = cdist(scaled_song_center, scaled_data, 'cosine')
|
216 |
index = list(np.argsort(distances)[:, :n_songs][0])
|
|
|
217 |
rec_songs = spotify_data.iloc[index]
|
218 |
# rec_songs = rec_songs[~rec_songs['name'].isin(song_dict['name'])]
|
219 |
return rec_songs[metadata_cols].to_dict(orient='records')
|
220 |
|
221 |
+
def get_recommendation_song_uri(res):
|
|
|
|
|
|
|
|
|
222 |
song_spotipy_info = []
|
223 |
for song in res:
|
224 |
song_spotipy_info.append(find_song_uri(song["name"], song["year"]))
|
225 |
return song_spotipy_info
|
226 |
|
227 |
+
def get_recommendation_array(song_name, song_year, feature_column_names, user_critic_text):
|
|
|
|
|
|
|
|
|
228 |
song_data = find_song(song_name, song_year)
|
229 |
+
list_song_data = format_song_string(song_data, feature_column_names)
|
230 |
user_critic = "\n \"user_critic=" + user_critic_text
|
231 |
+
recommendation = get_response(get_finetune_text(user_critic, list_song_data))
|
232 |
+
raw_recommendation_array = format_gpt_output(recommendation)
|
233 |
+
return raw_recommendation_array
|
|
|
234 |
|
235 |
|
|
|
|
|
236 |
def get_random_song():
|
237 |
data = pd.read_csv("data/data.csv")
|
238 |
sample = data.sample(n=1)
|
239 |
return sample.name, sample.year
|
240 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
241 |
def control():
|
242 |
+
# song_cluster_pipeline, data, feature_column_names = feature_get_pipeline_data_column_names()
|
243 |
data_path = "data/data.csv"
|
244 |
file_path = "data/pipeline.pkl"
|
245 |
cluster_labels = "data/cluster_labels.csv"
|
246 |
+
song_cluster_pipeline, data, feature_column_names = get_model_values(
|
247 |
data_path, file_path, cluster_labels)
|
248 |
|
249 |
user_critic_text = "it was dull and very loud"
|
250 |
song_name = "Poem of a Killer"
|
251 |
song_year = 2022
|
252 |
+
raw_recommendation_array = get_recommendation_array(
|
253 |
+
song_name, song_year, feature_column_names, user_critic_text)
|
254 |
+
|
255 |
+
result = format_chatgpt_recommendations(raw_recommendation_array, data, song_cluster_pipeline)
|
256 |
+
print(result, get_recommendation_song_uri(result))
|
257 |
+
|
258 |
+
if __name__ == "__main__":
|
259 |
+
control()
|