Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Streamlit application
|
2 |
+
|
3 |
+
# Import necessary libraries
|
4 |
+
import streamlit as st
|
5 |
+
import pandas as pd
|
6 |
+
from openai import OpenAI
|
7 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
8 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
9 |
+
import os
|
10 |
+
from dotenv import load_dotenv
|
11 |
+
|
12 |
+
# Import data
|
13 |
+
music_data = pd.read_csv("Spotify_Youtube.csv")
|
14 |
+
|
15 |
+
# Specify api key for OpenAIs API
|
16 |
+
|
17 |
+
load_dotenv()
|
18 |
+
|
19 |
+
OPENAI_API_KEY=os.environ.get("OPENAI_API_KEY")
|
20 |
+
|
21 |
+
client = OpenAI()
|
22 |
+
|
23 |
+
# Function that calls OpenAIs API
|
24 |
+
def parse_user_input(user_input):
|
25 |
+
response = client.chat.completions.create(
|
26 |
+
model="gpt-3.5-turbo",
|
27 |
+
messages=[
|
28 |
+
{
|
29 |
+
"role": "system",
|
30 |
+
"content": """You will be provided with an input: '{user_input}', and your task is to determine the following:
|
31 |
+
- Valence: a number that is equal to the mood. Positive moods are closer to 1 and negative moods are closer to 0.
|
32 |
+
- Number of songs: the number of songs the user requests.
|
33 |
+
- Tempo: the tempo of the songs.
|
34 |
+
- Danceability: the danceability of the songs.
|
35 |
+
|
36 |
+
Provide this information in the following format with each value separated by a space:
|
37 |
+
'valence number_of_songs tempo danceability'
|
38 |
+
Example: '0.5 20 120 0.8'
|
39 |
+
"""
|
40 |
+
},
|
41 |
+
{
|
42 |
+
"role": "user",
|
43 |
+
"content": user_input
|
44 |
+
},
|
45 |
+
{
|
46 |
+
"role": "assistant",
|
47 |
+
"content": "0.5 20, 120, 0.8"
|
48 |
+
}
|
49 |
+
],
|
50 |
+
temperature=0.5,
|
51 |
+
max_tokens=64,
|
52 |
+
top_p=1
|
53 |
+
)
|
54 |
+
return response.choices[0].message.content
|
55 |
+
|
56 |
+
|
57 |
+
# Function create new dataframe from music dataframe based on valence, number of tracks, tempo an danceability
|
58 |
+
def get_tracks_by_artist_and_danceability(music_data, valence, num_tracks, tempo, danceability):
|
59 |
+
filtered_tracks = music_data[
|
60 |
+
(music_data['Valence'].between(valence - 0.1, valence + 0.1)) &
|
61 |
+
(music_data['Tempo'].between(tempo - 30, tempo + 30)) &
|
62 |
+
(music_data['Danceability'].between(danceability - 0.2, danceability + 0.2))
|
63 |
+
]
|
64 |
+
return filtered_tracks.head(num_tracks)[['Track', 'Artist']]
|
65 |
+
|
66 |
+
# Function the recommends tracks by using tfidVectoricer and cosine_similarities
|
67 |
+
def recommend_tracks(track_names, track_ids, top_k=20):
|
68 |
+
vectorizer = TfidfVectorizer()
|
69 |
+
tfidf_matrix = vectorizer.fit_transform(track_names)
|
70 |
+
similarities = cosine_similarity(tfidf_matrix)
|
71 |
+
avg_similarity = similarities.mean(axis=0)
|
72 |
+
top_indices = avg_similarity.argsort()[-top_k:][::-1]
|
73 |
+
return track_ids.iloc[top_indices]
|
74 |
+
|
75 |
+
# Streamlit Application
|
76 |
+
|
77 |
+
logo = "music_logo.png"
|
78 |
+
|
79 |
+
# Sidebar
|
80 |
+
with st.sidebar:
|
81 |
+
st.image(logo, width=100)
|
82 |
+
st.header("Navigation")
|
83 |
+
tab_selection = st.sidebar.radio("Go to", ["Music Generator", "Browse Music", "About Us"])
|
84 |
+
|
85 |
+
# Music generator page
|
86 |
+
if tab_selection == "Music Generator":
|
87 |
+
st.header("Mood Playlist Generator", divider='rainbow')
|
88 |
+
st.write("Enter your music preferences in a detailed format and recieve a personalized playlist based on your mood:")
|
89 |
+
user_prompt = st.text_input("Example: 'I want 20 happy songs with a lot of tempo that i can dance to!'")
|
90 |
+
|
91 |
+
if st.button("Generate Playlist"):
|
92 |
+
try:
|
93 |
+
with st.spinner("Processing your request..."):
|
94 |
+
parsed_input = parse_user_input(user_prompt)
|
95 |
+
#st.write(f"Parsed input: {parsed_input}")
|
96 |
+
|
97 |
+
# Extract valence and number of songs from the parsed input
|
98 |
+
valence, num_tracks, tempo, danceability = parsed_input.split()
|
99 |
+
valence = float(valence)
|
100 |
+
num_tracks = int(num_tracks)
|
101 |
+
tempo = int(tempo)
|
102 |
+
danceability = (float(danceability))
|
103 |
+
|
104 |
+
#st.write(f"Number of tracks: {num_tracks}, Valence: {valence}, Tempo: {tempo}, Danceability: {danceability}")
|
105 |
+
|
106 |
+
tracks = get_tracks_by_artist_and_danceability(music_data, valence, num_tracks, tempo, danceability)
|
107 |
+
#st.write(f"Found {len(tracks)} tracks.")
|
108 |
+
|
109 |
+
if tracks.empty:
|
110 |
+
st.write("No tracks found. Please try a different query.")
|
111 |
+
else:
|
112 |
+
track_names = tracks['Track'].tolist()
|
113 |
+
track_ids = tracks[['Track', 'Artist']]
|
114 |
+
#st.write("Track names:", track_names)
|
115 |
+
|
116 |
+
recommended_tracks = recommend_tracks(track_names, track_ids, top_k=int(num_tracks))
|
117 |
+
st.write("Here are your recommended playlist:")
|
118 |
+
st.table(recommended_tracks)
|
119 |
+
st.button("Add playlist to Spotify")
|
120 |
+
except ValueError:
|
121 |
+
st.write("Error: Unable to parse the input. Please make sure the format is correct.")
|
122 |
+
|
123 |
+
# Browse music page
|
124 |
+
elif tab_selection == "Browse Music":
|
125 |
+
st.header("Browse Music", divider='rainbow')
|
126 |
+
st.write("Explore the music data used for generating your playlists.")
|
127 |
+
df = pd.read_csv("Spotify_Youtube.csv")
|
128 |
+
st.dataframe(df)
|
129 |
+
|
130 |
+
# About us page
|
131 |
+
elif tab_selection == "About Us":
|
132 |
+
st.header("About Us", divider='rainbow')
|
133 |
+
st.write("""
|
134 |
+
This App is developed by 4 ambitious university students, whose goals are to create playlists and music experiences which you can emotionally connect with.
|
135 |
+
""")
|
136 |
+
st.image("group_photo.jpg", caption="Our Team", use_column_width=True)
|
137 |
+
|
138 |
+
# Add custom CSS
|
139 |
+
st.markdown(
|
140 |
+
"""
|
141 |
+
<style>
|
142 |
+
.css-18e3th9 {
|
143 |
+
padding-top: 2rem;
|
144 |
+
}
|
145 |
+
.css-1d391kg {
|
146 |
+
padding-top: 1.5rem;
|
147 |
+
}
|
148 |
+
.css-1d2jrlv {
|
149 |
+
padding-bottom: 1rem;
|
150 |
+
}
|
151 |
+
.css-1v3fvcr {
|
152 |
+
padding-top: 1rem;
|
153 |
+
padding-bottom: 1rem;
|
154 |
+
}
|
155 |
+
</style>
|
156 |
+
""",
|
157 |
+
unsafe_allow_html=True
|
158 |
+
)
|