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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import spotipy
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from spotipy.oauth2 import SpotifyClientCredentials
|
| 5 |
+
import librosa
|
| 6 |
+
import librosa.display
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import numpy as np
|
| 9 |
+
import plotly.express as px
|
| 10 |
+
import plotly.graph_objects as go
|
| 11 |
+
import requests
|
| 12 |
+
import io
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Spotify API credentials
|
| 16 |
+
client_id = '1138a66b81e2490593ab49b4573a0c5f'
|
| 17 |
+
client_secret = 'c7d18d1f37c44bd891128790a2f1b982'
|
| 18 |
+
|
| 19 |
+
# Initialize the Spotipy client
|
| 20 |
+
client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
|
| 21 |
+
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
| 22 |
+
|
| 23 |
+
# Streamlit app
|
| 24 |
+
st.set_page_config(page_title='Spotify Track Analysis', layout="wide")
|
| 25 |
+
|
| 26 |
+
# Streamlit app
|
| 27 |
+
st.title('Spotify Track Analysis')
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Create columns for layout
|
| 32 |
+
col1, col2, col3 = st.columns([1, 3, 1])
|
| 33 |
+
|
| 34 |
+
# Initialize the selected_track variable
|
| 35 |
+
selected_track = None
|
| 36 |
+
|
| 37 |
+
selected_track_details = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Section for track selection
|
| 42 |
+
with col2:
|
| 43 |
+
st.header('Track Selection')
|
| 44 |
+
|
| 45 |
+
# Input field for track search
|
| 46 |
+
search_query = st.text_input('Search for a track')
|
| 47 |
+
|
| 48 |
+
if search_query:
|
| 49 |
+
# Search for tracks based on user input
|
| 50 |
+
results = sp.search(q=search_query, type='track', limit=10)
|
| 51 |
+
|
| 52 |
+
if results and results['tracks']['items']:
|
| 53 |
+
st.subheader('Search Results')
|
| 54 |
+
selected_track = st.selectbox('Select a track', [f"{track['name']} by {track['artists'][0]['name']}" for track in results['tracks']['items']])
|
| 55 |
+
|
| 56 |
+
if selected_track:
|
| 57 |
+
selected_track_details = results['tracks']['items'][[f"{track['name']} by {track['artists'][0]['name']}" for track in results['tracks']['items']].index(selected_track)]
|
| 58 |
+
track_name = selected_track_details['name']
|
| 59 |
+
artist_name = selected_track_details['artists'][0]['name']
|
| 60 |
+
album_name = selected_track_details['album']['name']
|
| 61 |
+
cover_url = selected_track_details['album']['images'][0]['url']
|
| 62 |
+
track_id = selected_track_details['id']
|
| 63 |
+
|
| 64 |
+
# Display the selected track details
|
| 65 |
+
st.subheader('Selected Track Details')
|
| 66 |
+
st.write(f"Track: {track_name}")
|
| 67 |
+
st.write(f"Artist: {artist_name}")
|
| 68 |
+
st.write(f"Album: {album_name}")
|
| 69 |
+
st.image(cover_url,width = 200)
|
| 70 |
+
|
| 71 |
+
# Section for track analysis
|
| 72 |
+
# Section for track analysis
|
| 73 |
+
with col2:
|
| 74 |
+
st.header('Track Analysis')
|
| 75 |
+
|
| 76 |
+
if selected_track:
|
| 77 |
+
selected_track_details = results['tracks']['items'][[f"{track['name']} by {track['artists'][0]['name']}" for track in results['tracks']['items']].index(selected_track)]
|
| 78 |
+
track_uri = f'spotify:track:{selected_track_details["id"]}'
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Load the full audio data for the selected track
|
| 83 |
+
audio_url = sp.track(track_uri)['preview_url']
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
st.info("You can preview the first 30 seconds of the song here. Please note that the full song cannot be played due to copyright issues.")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Display an audio player for the preview URL
|
| 91 |
+
st.audio(audio_url, format="audio/mp3")
|
| 92 |
+
|
| 93 |
+
if audio_url:
|
| 94 |
+
response = requests.get(audio_url)
|
| 95 |
+
y, sr = librosa.load(io.BytesIO(response.content))
|
| 96 |
+
|
| 97 |
+
# Visualize highs and lows using a spectrogram
|
| 98 |
+
st.subheader('Highs and Lows')
|
| 99 |
+
D = np.abs(librosa.stft(y))
|
| 100 |
+
fig = px.imshow(librosa.amplitude_to_db(D, ref=np.max), aspect='auto')
|
| 101 |
+
|
| 102 |
+
# Adjust the size of the graph and display it using st.plotly_chart
|
| 103 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 104 |
+
st.info("The 'Highs and Lows' graph shows the distribution of high and low frequencies over time. Brighter areas indicate higher energy in the frequency bands.")
|
| 105 |
+
|
| 106 |
+
# Visualize beat intensity
|
| 107 |
+
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
|
| 108 |
+
times = librosa.times_like(onset_env)
|
| 109 |
+
onset_frames = librosa.onset.onset_detect(onset_envelope=onset_env)
|
| 110 |
+
st.subheader('Beat Intensity')
|
| 111 |
+
fig = go.Figure()
|
| 112 |
+
fig.add_trace(go.Scatter(x=times, y=onset_env, mode='lines', name='Onset strength'))
|
| 113 |
+
fig.add_vline(x=times[onset_frames], line_color='red', line_dash='dash', name='Onsets')
|
| 114 |
+
fig.update_layout(xaxis_title='Time (s)', yaxis_title='Onset Strength')
|
| 115 |
+
|
| 116 |
+
# Adjust the size of the graph and display it using st.plotly_chart
|
| 117 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 118 |
+
st.info("The 'Beat Intensity' graph represents the rhythm and intensity changes in the music. Red vertical lines indicate the onsets of beats in the track.")
|
| 119 |
+
|
| 120 |
+
# Visualize energy changes
|
| 121 |
+
rms = librosa.feature.rms(y=y)
|
| 122 |
+
times = librosa.times_like(rms)
|
| 123 |
+
st.subheader('Energy Changes')
|
| 124 |
+
fig = go.Figure()
|
| 125 |
+
fig.add_trace(go.Scatter(x=times, y=rms[0], mode='lines', name='RMS Energy'))
|
| 126 |
+
fig.update_layout(xaxis_title='Time (s)', yaxis_title='RMS Energy')
|
| 127 |
+
|
| 128 |
+
# Adjust the size of the graph and display it using st.plotly_chart
|
| 129 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 130 |
+
st.info("The 'Energy Changes' graph displays the root mean square energy (RMSE) of the audio. It shows how the energy in the music changes over time.")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# Visualize tempo variations
|
| 134 |
+
onset_frames = librosa.onset.onset_detect(onset_envelope=onset_env)
|
| 135 |
+
st.subheader('Tempo Variations')
|
| 136 |
+
tempo_changes = 60 / np.diff(times[onset_frames])
|
| 137 |
+
fig = go.Figure()
|
| 138 |
+
fig.add_trace(go.Scatter(x=times[onset_frames][:-1], y=tempo_changes, mode='lines', name='Tempo (BPM)'))
|
| 139 |
+
fig.update_layout(xaxis_title='Time (s)', yaxis_title='Tempo (BPM)')
|
| 140 |
+
|
| 141 |
+
# Adjust the size of the graph and display it using st.plotly_chart
|
| 142 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 143 |
+
st.info("The 'Tempo Variations' graph reveals the changes in tempo (BPM) over time. It provides insights into tempo fluctuations in the track.")
|
| 144 |
+
else:
|
| 145 |
+
st.warning("Audio analysis not available for the selected track.")
|
| 146 |
+
|
| 147 |
+
# Streamlit app
|
| 148 |
+
st.title('Music Recommendation Based on Audio Features')
|
| 149 |
+
|
| 150 |
+
# Create sliders for adjusting audio features
|
| 151 |
+
st.header('Adjust Audio Features')
|
| 152 |
+
|
| 153 |
+
acousticness = st.slider('Acousticness', 0.0, 1.0, 0.5, 0.01)
|
| 154 |
+
st.info("Acousticness measures the amount of acoustic sound in the track. Decreasing it may lead to more electronic or non-acoustic recommendations, while increasing it may result in more acoustic recommendations.")
|
| 155 |
+
danceability = st.slider('Danceability', 0.0, 1.0, 0.5, 0.01)
|
| 156 |
+
st.info("Danceability quantifies how suitable the track is for dancing. Higher values represent tracks that are more danceable.")
|
| 157 |
+
energy = st.slider('Energy', 0.0, 1.0, 0.5, 0.01)
|
| 158 |
+
st.info("Energy measures the intensity and activity in the music. Higher values indicate more energetic tracks, while lower values represent calmer tracks.")
|
| 159 |
+
instrumentalness = st.slider('Instrumentalness', 0.0, 1.0, 0.5, 0.01)
|
| 160 |
+
st.info("Instrumentalness assesses the presence of vocals in the track. Lower values suggest the presence of vocals, while higher values indicate instrumental tracks.")
|
| 161 |
+
liveness = st.slider('Liveness', 0.0, 1.0, 0.5, 0.01)
|
| 162 |
+
st.info("Liveness indicates the likelihood of a live audience in the track. Higher values suggest a live performance, while lower values imply a studio recording.")
|
| 163 |
+
speechiness = st.slider('Speechiness', 0.0, 1.0, 0.5, 0.01)
|
| 164 |
+
st.info("Speechiness quantifies the presence of spoken words in the track. Higher values indicate more speech-like audio, while lower values are more musical and instrumental.")
|
| 165 |
+
valence = st.slider('Valence', 0.0, 1.0, 0.5, 0.01)
|
| 166 |
+
st.info("Valence measures the overall positivity of the track. Higher values represent happier and more positive tracks, while lower values indicate sadder or more negative tracks.")
|
| 167 |
+
|
| 168 |
+
# Button to generate recommendations
|
| 169 |
+
if st.button('Get Recommendations'):
|
| 170 |
+
# Build the target_audio_features dictionary
|
| 171 |
+
target_audio_features = {
|
| 172 |
+
'acousticness': acousticness,
|
| 173 |
+
'danceability': danceability,
|
| 174 |
+
'energy': energy,
|
| 175 |
+
'instrumentalness': instrumentalness,
|
| 176 |
+
'liveness': liveness,
|
| 177 |
+
'speechiness': speechiness,
|
| 178 |
+
'valence': valence
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
# Fetch track recommendations based on the selected audio features
|
| 182 |
+
recommended_tracks = sp.recommendations(seed_tracks=[track_id], limit=5, target_audio_features=target_audio_features)
|
| 183 |
+
|
| 184 |
+
st.subheader('Recommended Tracks:')
|
| 185 |
+
|
| 186 |
+
if selected_track:
|
| 187 |
+
# Fetch track recommendations based on the selected audio features
|
| 188 |
+
recommended_tracks = sp.recommendations(seed_tracks=[track_id], limit=5, target_audio_features=target_audio_features)
|
| 189 |
+
|
| 190 |
+
# Create columns for the recommended tracks, e.g., 2 tracks per column
|
| 191 |
+
num_columns = 2
|
| 192 |
+
num_recommended_tracks = len(recommended_tracks['tracks'])
|
| 193 |
+
num_rows = (num_recommended_tracks + num_columns - 1) // num_columns
|
| 194 |
+
|
| 195 |
+
for row in range(num_rows):
|
| 196 |
+
cols = st.columns(num_columns)
|
| 197 |
+
for col in range(num_columns):
|
| 198 |
+
idx = row * num_columns + col
|
| 199 |
+
if idx < num_recommended_tracks:
|
| 200 |
+
rec_track = recommended_tracks['tracks'][idx]
|
| 201 |
+
with cols[col]:
|
| 202 |
+
st.write(f"Track: {rec_track['name']}")
|
| 203 |
+
st.write(f"Artist: {rec_track['artists'][0]['name']}")
|
| 204 |
+
st.write(f"Album: {rec_track['album']['name']}")
|
| 205 |
+
album_art_url = rec_track['album']['images'][0]['url']
|
| 206 |
+
st.image(album_art_url,width=250)
|
| 207 |
+
|
| 208 |
+
# Get the 'preview_url' for the recommended track
|
| 209 |
+
recommended_audio_url = rec_track['preview_url']
|
| 210 |
+
|
| 211 |
+
# Display an audio player for the recommended track's preview URL
|
| 212 |
+
st.audio(recommended_audio_url, format="audio/mp3")
|