RasmusLH commited on
Commit
a2d0e0e
1 Parent(s): 792dd11

Upload app.py

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