Spaces:
Sleeping
Sleeping
import streamlit as st | |
import requests | |
from urllib.parse import urlencode | |
from utils import * | |
import os | |
# Constants | |
CLIENT_ID = os.getenv("CLIENT_ID") | |
CLIENT_SECRET = os.getenv("CLIENT_SECRET") | |
REDIRECT_URI = "https://huggingface.co/spaces/Add1E/SpotifyHitPrediction" | |
AUTH_URL = "https://accounts.spotify.com/authorize" | |
TOKEN_URL = "https://accounts.spotify.com/api/token" | |
def get_track_audio_features(track_id, access_token): | |
endpoint = f"https://api.spotify.com/v1/audio-features/{track_id}" | |
headers = { | |
'Authorization': f'Bearer {access_token}', | |
} | |
response = requests.get(endpoint, headers=headers) | |
return response.json() | |
def get_track_information(track_id, access_token): | |
endpoint = f"https://api.spotify.com/v1/tracks/{track_id}" | |
headers = { | |
'Authorization': f'Bearer {access_token}', | |
} | |
response = requests.get(endpoint, headers=headers) | |
return response.json() | |
def extract_track_id_from_url(url): | |
# For a Spotify URL | |
if 'open.spotify.com' in url and '/track/' in url: | |
return url.split('track/')[1] | |
# For a Spotify URI | |
elif 'spotify:track:' in url: | |
return url.split(':')[-1] | |
else: | |
return None # Or handle invalid URL/URI appropriately | |
def app(): | |
# Step 1: User Authorization | |
if st.session_state.get('code') is None or ('access_token' not in st.session_state or st.session_state['access_token'] is None): | |
auth_params = { | |
'client_id': CLIENT_ID, | |
'response_type': 'code', | |
'redirect_uri': REDIRECT_URI, | |
'scope': 'user-read-private', # Modify as per your required scopes | |
} | |
st.write('Please log in to Spotify') | |
st.markdown(f"[Log In]({AUTH_URL}?{urlencode(auth_params)})", unsafe_allow_html=True) | |
else:# | |
# Step 2: Request Access Token | |
if 'access_token' not in st.session_state or (st.session_state['access_token'] is None): | |
auth_code = st.session_state['code'] | |
token_data = { | |
'grant_type': 'authorization_code', | |
'code': auth_code, | |
'redirect_uri': REDIRECT_URI, | |
'client_id': CLIENT_ID, | |
'client_secret': CLIENT_SECRET, | |
} | |
token_r = requests.post(TOKEN_URL, data=token_data) | |
token_response = token_r.json() | |
st.session_state['access_token'] = token_response.get('access_token') | |
if 'access_token' in st.session_state: | |
st.write("Enter a Spotify Track URL or URI to get its audio features.") | |
track_input = st.text_input("Spotify Track URL/URI", "") | |
traindata = [] | |
if st.button("Get Audio Features"): | |
track_id = extract_track_id_from_url(track_input) | |
if track_id: | |
track_info = get_track_information(track_id, st.session_state['access_token']) | |
if track_info: | |
st.write(f"Popularität: {track_info.get('popularity', 'Nicht verfügbar')}") | |
traindata.append("new") | |
traindata.append(track_info["name"]) | |
traindata.append(track_info["artists"][0]["name"]) | |
traindata.append("No_Genre_Found") | |
else: | |
st.write("Track-Informationen konnten nicht abgerufen werden.") | |
else: | |
st.write("Bitte geben Sie eine gültige Track-ID ein.") | |
if track_id: | |
audio_features = get_track_audio_features(track_id, st.session_state['access_token']) | |
features = [None] * 9 | |
features[0] = audio_features["tempo"] # Beats per minute | |
features[1] = audio_features["energy"] | |
features[2] = audio_features["danceability"] | |
features[3] = audio_features["loudness"] # Loudness in dB | |
features[4] = audio_features["liveness"] | |
features[5] = audio_features["valence"] | |
features[6] = audio_features["duration_ms"] / 1000 # Umrechnung von Millisekunden in Sekunden | |
features[7] = audio_features["acousticness"] | |
features[8] = audio_features["speechiness"] | |
feature_display = { | |
"Songname" : track_info["name"], | |
"Artist": track_info["artists"][0]["name"], | |
"tempo": features[0], | |
"energy" : features[1], | |
"danceability":features[2], | |
"loudness":features[3], | |
"liveness":features[4], | |
"valence":features[5], | |
"duration_in_s":features[6], | |
"acousticness":features[7], | |
"speechiness":features[8] | |
} | |
traindata.append(audio_features["tempo"]) | |
traindata.append(audio_features["energy"]) | |
traindata.append(audio_features["danceability"]) | |
traindata.append(audio_features["loudness"]) | |
traindata.append(audio_features["liveness"]) | |
traindata.append(audio_features["valence"]) | |
traindata.append(audio_features["duration_ms"]/ 1000) | |
traindata.append(audio_features["acousticness"]) | |
traindata.append(audio_features["speechiness"]) | |
traindata.append(track_info["popularity"]) | |
st.write(feature_display) | |
predictions = predict_popularity(features, traindata) | |
st.write(f"Random Forest Prediction: {predictions[0]}") | |
st.write(f"Regression Prediction: {predictions[1]}") | |
else: | |
st.error("Please enter a valid Spotify Track URL or URI.") | |
if 'code' not in st.session_state: | |
query_params = st.experimental_get_query_params() | |
st.session_state['code'] = query_params.get('code', [None])[0] | |
app() | |