Spaces:
Sleeping
Sleeping
| import pandas as pd | |
| import numpy as np | |
| import keras | |
| from keras.models import load_model | |
| from keras.preprocessing.sequence import pad_sequences | |
| import spotipy | |
| from spotipy.oauth2 import SpotifyClientCredentials | |
| import gradio as gr | |
| import pickle | |
| model = load_model('emotion_model.h5') | |
| with open('tokenizer.pkl', 'rb') as handle: | |
| tokenizer = pickle.load(handle) | |
| with open('label_encoder.pkl', 'rb') as handle: | |
| label_encoder = pickle.load(handle) | |
| max_length = 100 | |
| # Spotify credentials | |
| client_id = '6ae166a3ffd34a7da59b1da9bf626f35' | |
| client_secret = '0fbb8f152cdb455eb56fe05fdd21f7d3' | |
| sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)) | |
| # Function to recommend songs based on emotion and language | |
| def recommend_songs(emotion, language): | |
| emotion_to_playlist = { | |
| 'joy': {'english': 'Happy Pop Hits', 'tamil': 'VIBE Panlaama', 'hindi': 'Bollywood Dance Music', | |
| 'malayalam': 'Malayalam Chill Mix', 'telugu': 'DSP Dance Hits'}, | |
| 'sadness': {'english': 'Life Sucks', 'tamil': 'Sad Melodies Tamil', 'hindi': 'Sad Hindi Melodies', | |
| 'malayalam': 'Feel Good Malayalam', 'telugu': 'Sad Melodies Telugu'}, | |
| 'anger': {'english': 'Rage Beats', 'tamil': 'Fight Mood Tamil', 'hindi': 'Bollywood Workout', | |
| 'malayalam': 'Hip Hop Malayalam', 'telugu': 'Kiraak Telugu'}, | |
| 'love': {'english': 'Love Pop', 'tamil': 'Kaadhal Theeye', 'hindi': 'Bollywood Mush', | |
| 'malayalam': 'Romantic Malayalam', 'telugu': 'Purely Prema'}, | |
| 'fear': {'english': 'Chill Vibes', 'tamil': 'Iniya Iravu', 'hindi': 'Bollywood & Chill', | |
| 'malayalam': 'Malayalam Chill Mix', 'telugu': 'Mellow Telugu'}, | |
| 'surprise': {'english': 'Feel Good Indie', 'tamil': 'VIBE Panlaama', 'hindi': 'Happy Vibes', | |
| 'malayalam': 'Happy Vibes Malayalam', 'telugu': 'Feel Good Telugu'} | |
| } | |
| # Get the playlist name | |
| playlist_name = emotion_to_playlist.get(emotion, {}).get(language, 'mood booster') | |
| print(f"Searching for playlist: {playlist_name}") # Debugging | |
| try: | |
| results = sp.search(q=playlist_name, type='playlist', limit=1) | |
| print(f"Search Results: {results}") # Debugging | |
| if 'playlists' in results and results['playlists']['items']: | |
| playlist_item = results['playlists']['items'][0] | |
| if playlist_item: | |
| playlist_id = playlist_item['id'] | |
| else: | |
| print("Playlist item is None!") | |
| return ["No valid playlists found."] | |
| else: | |
| print("No playlists found in search results!") | |
| return ["No playlist recommendations available."] | |
| except Exception as e: | |
| print(f"Spotify API error: {e}") | |
| return ["Error connecting to Spotify API."] | |
| # Fetch and return songs | |
| try: | |
| tracks = sp.playlist_tracks(playlist_id) | |
| song_recommendations = [ | |
| f"{track['track']['name']} by {track['track']['artists'][0]['name']} - [Listen on Spotify]({track['track']['external_urls']['spotify']})" | |
| for track in tracks['items'] if track['track'] | |
| ] | |
| return song_recommendations[:15] | |
| except Exception as e: | |
| print(f"Error fetching tracks: {e}") | |
| return ["Error fetching song recommendations."] | |
| # Function to predict emotion and recommend songs | |
| def predict_emotion_and_recommend_songs(text, language): | |
| input_sequence = tokenizer.texts_to_sequences([text]) | |
| padded_input_sequence = pad_sequences(input_sequence, maxlen=max_length) | |
| prediction = model.predict(padded_input_sequence) | |
| predicted_label = np.argmax(prediction) | |
| emotion = label_encoder.inverse_transform([predicted_label])[0] | |
| songs = recommend_songs(emotion, language) | |
| return emotion, songs | |
| # Gradio interface function | |
| def gradio_interface(text, language): | |
| emotion, songs = predict_emotion_and_recommend_songs(text, language) | |
| song_list = "\n\n".join(songs) | |
| return f"**Emotion:** {emotion.capitalize()}\n\n**Recommended Songs ({language.capitalize()}):**\n\n{song_list}" | |
| # Gradio app setup | |
| textbox = gr.Textbox(label="Enter a sentence") | |
| dropdown = gr.Dropdown(choices=["english", "tamil", "hindi", "malayalam", "telugu"], label="Choose a language") | |
| interface = gr.Interface(fn=gradio_interface, | |
| inputs=[textbox, dropdown], | |
| outputs="markdown", | |
| title="EmoGroove- An Emotion-Based Song Recommender", | |
| description="Enter a sentence to predict its emotion and get song recommendations based on that emotion and your preferred language.", | |
| allow_flagging="never" | |
| ) | |
| # Launch the app | |
| interface.launch(share=True) | |