Amit Kumar
fit data using kmeans
e7b83d9
raw
history blame contribute delete
No virus
2.99 kB
import os
import spotipy
import gradio as gr
import pandas as pd
from get_scaler import get_scaler
from dotenv import load_dotenv
from recommendations import recommend_songs
from spotipy.oauth2 import SpotifyClientCredentials
# Load environment variables from .env file
load_dotenv()
# Access the Spotify API credentials
client_id = os.getenv('SPOTIFY_CLIENT_ID')
client_secret = os.getenv('SPOTIFY_CLIENT_SECRET')
# Authenticate with the Spotify API
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=client_id, client_secret=client_secret))
# data = pd.read_csv("kmeans_clustered_spotify_dataset.csv")
data = get_scaler()[0]
def fetch_song_cover(song_name):
# Search for the song
results = sp.search(q=song_name, limit=1, type='track')
if results['tracks']['items']:
song = results['tracks']['items'][0]
cover_url = song['album']['images'][0]['url']
user_song_name = song['name']
user_song = song['name']
return cover_url, song['name'], song['artists'][0]['name']
else:
return None, "Song not found", "Artist not found"
def get_recommendations(song_name):
suggestions = recommend_songs(song_list=[{'name': song_name}], spotify_data=data)
song_covers = []
for suggestion in suggestions:
print(suggestion)
cover = fetch_song_cover(suggestion["name"])
song_covers.append(cover[0])
return song_covers
# Gradio Interface
def gradio_interface(song_name):
cover_url, song_name, artist_name = fetch_song_cover(song_name)
if cover_url:
return cover_url, f"Song: {song_name}", f"Artist: {artist_name}", gr.update(visible=True), gr.update(visible=True)
else:
return None, "Song not found", "Artist not found"
# Creating Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# Music Recommendation System using Spotify Dataset")
with gr.Row():
with gr.Column():
song_input = gr.Textbox(label="Enter Song Name")
search_button = gr.Button("Find Song")
with gr.Column():
cover_output = gr.Image(label="Cover Image")
song_name_output = gr.Textbox(label="Song Name")
artist_name_output = gr.Textbox(label="Artist Name")
recommendations_labels = gr.Row(visible=False)
recommendations_songs = gr.Column(visible=False)
with recommendations_labels:
gr.Markdown("# You may also like")
with recommendations_songs:
song_covers = gr.Gallery(label="Image Gallery")
search_button.click(fn=gradio_interface,
inputs=song_input,
outputs=[cover_output, song_name_output, artist_name_output, recommendations_labels, recommendations_songs]).then(
fn=get_recommendations,
inputs=song_input,
outputs=song_covers
)
# Launching the Gradio app
demo.launch(debug=True)