File size: 6,233 Bytes
7998f7f
54b5359
 
 
 
 
 
 
 
 
 
 
 
8cde942
54b5359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f07f84f
 
 
979b0ef
8cde942
979b0ef
 
 
 
 
 
 
 
4f4d177
ae9b212
 
 
 
 
 
 
 
 
 
 
 
 
 
8cde942
54b5359
 
 
5597931
54b5359
 
5597931
 
 
 
 
 
 
 
 
 
 
 
54b5359
 
 
5597931
54b5359
 
5597931
54b5359
 
5597931
54b5359
 
 
ec68be5
 
54b5359
 
 
 
 
 
 
 
 
 
5597931
 
 
 
 
 
 
 
 
 
54b5359
5597931
54b5359
 
 
 
 
5597931
54b5359
 
02f2f62
 
54b5359
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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():
    if st.session_state.get('code') is not None:
        if st.button("Go Back"):
            st.session_state['code'] = None
    # Step 1: User Authorization
    if st.session_state.get('code') 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()