File size: 4,151 Bytes
f4c8685
e8c4129
f4c8685
 
 
 
7c4e98c
f4c8685
 
 
6868ece
f4c8685
0d5194e
f4c8685
 
e8c4129
 
f4c8685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c4e98c
 
0670634
 
 
 
 
 
3020ad1
 
506e32d
 
 
5c5363c
0670634
3020ad1
0670634
 
e8c4129
 
 
 
 
 
 
 
 
6868ece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0670634
 
 
 
 
c66809e
0670634
 
 
 
 
 
 
 
 
 
e8c4129
0670634
 
 
 
 
 
c66809e
0670634
 
 
c66809e
 
 
 
801318e
c66809e
0670634
e8c4129
0670634
f4c8685
 
 
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
import json
from urllib import request
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import HTMLResponse, RedirectResponse
from starlette.requests import Request
import gradio as gr
import uvicorn
from fastapi.responses import HTMLResponse
from fastapi.responses import RedirectResponse
import pandas as pd

import spotipy
from spotipy import oauth2

import heatmap

PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'c087fa97cebb4f67b6f08ba841ed8378'
SPOTIPY_CLIENT_SECRET = 'ae27d6916d114ac4bb948bb6c58a72d9'
SPOTIPY_REDIRECT_URI = 'https://hf-hackathon-2023-01-spotify.hf.space'
SCOPE = 'user-library-read'

sp_oauth = oauth2.SpotifyOAuth(SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, SPOTIPY_REDIRECT_URI, scope=SCOPE)

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="w.o.w")

@app.get('/', response_class=HTMLResponse)
async def homepage(request: Request):
    token = request.session.get('token')
    if token:
        return RedirectResponse("/gradio")

    url = str(request.url)
    code = sp_oauth.parse_response_code(url)
    if code != url:
        token_info = sp_oauth.get_access_token(code)
        request.session['token'] = token_info['access_token']
        return RedirectResponse("/gradio")

    auth_url = sp_oauth.get_authorize_url()
    return "<a href='" + auth_url + "'>Login to Spotify</a>"



from vega_datasets import data

iris = data.iris()


def scatter_plot_fn(request: gr.Request):
    token = request.request.session.get('token')
    if token:
        sp = spotipy.Spotify(token)
        results = sp.current_user()
        print(results)
    return gr.ScatterPlot(
        value=iris,
    )

def heatmap_plot_fn(request: gr.Request):
    token = request.request.session.get('token')
    if token:
        sp = spotipy.Spotify(token)
        data = heatmap.build_heatmap(heatmap.fetch_recent_songs(sp))
        fig, _ = heatmap.plot(data)
        return fig


def get_features(spotify):
    features = []
    for index in range(0, 10):
        results = spotify.current_user_saved_tracks(offset=index*50, limit=50)
        track_ids = [item['track']['id'] for item in results['items']]
        features.extend(spotify.audio_features(track_ids))

    df = pd.DataFrame(data=features)
    names = [
        'danceability', 
        'energy',
        'loudness',
        'speechiness',
        'acousticness',
        'instrumentalness',
        'liveness',
        'valence',
        'tempo',
    ]
    features_means = df[names].mean()
    # print (features_means.to_json())
    return features_means


##########
def get_started():
    # redirects to spotify and comes back
    # then generates plots
    return

with gr.Blocks() as demo:
    gr.Markdown(" ## Spotify Analyzer 🥳🎉")
    gr.Markdown("This app analyzes how cool your music taste is. We dare you to take this challenge!")
    with gr.Row():
        get_started_btn = gr.Button("Get Started")
    with gr.Row():
        with gr.Column():
            with gr.Row():
                with gr.Column():
                    hm_plot = gr.Plot().style(container=True)
                with gr.Column():
                    plot = gr.ScatterPlot(show_label=False).style(container=True)
            with gr.Row():
                with gr.Column():
                    plot = gr.ScatterPlot(show_label=False).style(container=True)
                with gr.Column():
                    plot = gr.ScatterPlot(show_label=False).style(container=True)
    with gr.Row():
        gr.Markdown(" ### We have recommendations for you!")
    with gr.Row():
        gr.Dataframe(
            headers=["Song", "Album", "Artist"],
            datatype=["str", "str", "str"],
            label="Reccomended Songs",
            value=[["something", "something", "something"], ["something", "something", "something"]]  # TODO: replace with actual reccomendations once get_started() is implemeted.
        )
    demo.load(fn=scatter_plot_fn, outputs=plot)
    demo.load(fn=heatmap_plot_fn, output=hm_plot)


gradio_app = gr.mount_gradio_app(app, demo, "/gradio")
uvicorn.run(app, host="0.0.0.0", port=7860)