Skip to content

Commit e753673

Browse files
authored
Merge pull request #98 from Haob2110011/main
Mood Based Music Recommender
2 parents 1347001 + cc8b4d6 commit e753673

File tree

4 files changed

+161
-0
lines changed

4 files changed

+161
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import spotipy
2+
from spotipy.oauth2 import SpotifyClientCredentials
3+
import random
4+
5+
# Authentication - Replace with your credentials
6+
CLIENT_ID = 'your_spotify_client_id'
7+
CLIENT_SECRET = 'your_spotify_client_secret'
8+
9+
# Connect to Spotify API
10+
auth_manager = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
11+
sp = spotipy.Spotify(auth_manager=auth_manager)
12+
13+
# Dictionary to map emotions to musical characteristics
14+
emotion_to_genre = {
15+
'happy': ['pop', 'dance', 'indie'],
16+
'sad': ['acoustic', 'blues', 'piano'],
17+
'angry': ['metal', 'rock', 'punk'],
18+
'relaxed': ['ambient', 'chill', 'classical'],
19+
'energetic': ['electronic', 'hip-hop', 'funk'],
20+
'anxious': ['ambient', 'classical', 'jazz'],
21+
'cheerful': ['pop', 'indie', 'reggae'],
22+
'stressed': ['jazz', 'chill', 'lo-fi'],
23+
'dreamy': ['dream-pop', 'ambient', 'shoegaze'],
24+
'excited': ['dance', 'electronic', 'pop'],
25+
'bored': ['alternative', 'indie', 'chill'],
26+
'nostalgic': ['classic rock', 'folk', 'retro'],
27+
'hopeful': ['pop', 'inspirational', 'uplifting'],
28+
'content': ['soft rock', 'acoustic', 'country'],
29+
'romantic': ['pop', 'r&b', 'soul'],
30+
}
31+
32+
# Function to recommend tracks based on emotion
33+
def recommend_tracks(emotion):
34+
genres = emotion_to_genre.get(emotion.lower(), ['pop']) # Default to 'pop' if emotion is not found
35+
selected_genre = random.choice(genres)
36+
37+
# Fetch recommendations from Spotify
38+
results = sp.recommendations(seed_genres=[selected_genre], limit=10) # Increase limit for more results
39+
tracks = results['tracks']
40+
41+
playlist = []
42+
for track in tracks:
43+
track_info = {
44+
'name': track['name'],
45+
'artist': track['artists'][0]['name'],
46+
'url': track['external_urls']['spotify']
47+
}
48+
playlist.append(track_info)
49+
50+
return playlist, genres
51+
52+
# Function to get maximum length of strings in a list of dictionaries
53+
def get_max_lengths(playlist):
54+
max_name_length = max(len(song['name']) for song in playlist) if playlist else 0
55+
max_artist_length = max(len(song['artist']) for song in playlist) if playlist else 0
56+
max_url_length = max(len(song['url']) for song in playlist) if playlist else 0
57+
return max_name_length, max_artist_length, max_url_length
58+
59+
# Main loop for user input
60+
while True:
61+
emotion = input("\nEnter your emotion (happy, sad, angry, relaxed, energetic, anxious, cheerful, stressed, dreamy, excited, bored, nostalgic, hopeful, content, romantic) or type 'exit' to quit: ").strip().lower()
62+
63+
if emotion == 'exit':
64+
print("Goodbye my Love!!!")
65+
break
66+
67+
# Get playlist based on the emotion
68+
playlist, genres = recommend_tracks(emotion)
69+
70+
# Get maximum lengths for formatting
71+
max_name_length, max_artist_length, max_url_length = get_max_lengths(playlist)
72+
73+
# Set a minimum width for columns to ensure proper alignment
74+
min_name_length = max(20, max_name_length)
75+
min_artist_length = max(15, max_artist_length)
76+
min_url_length = 35 # Fixed width for URL
77+
78+
# Display the recommended playlist
79+
if emotion not in emotion_to_genre:
80+
print("The emotion you entered is NOT in the list, so we will show you pop music instead.")
81+
82+
print(f"Here are some songs for your '{emotion}' mood:" if emotion in emotion_to_genre else "Here are some pop songs for you:")
83+
print(f"STT | Song Name{' ' * (min_name_length - 9)} | Artist{' ' * (min_artist_length - 6)} | URL")
84+
print("-" * (11 + max_name_length + max_artist_length + max_url_length))
85+
86+
for idx, song in enumerate(playlist, 1):
87+
print(f"{idx:<3} | {song['name']:<{min_name_length}} | {song['artist']:<{min_artist_length}} | {song['url']}")
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Music Recommendation Based on Emotion
2+
3+
A Python script that recommends music playlists based on user-inputted emotions using the Spotify API. The script fetches songs that match the user's mood and provides a playlist with links to each song.
4+
5+
## Features
6+
7+
- Recommend songs based on various emotions.
8+
- Integrates with Spotify's Web API to fetch song recommendations.
9+
10+
## Setup
11+
12+
### 1. Set Up Spotify API
13+
14+
To use this script, you will need to create a Spotify Developer account and register an app to obtain your Client ID and Client Secret. Follow the instructions [here](https://developer.spotify.com/documentation/general/guides/authorization/app-settings/) to get your credentials.
15+
16+
Here is an example:
17+
18+
![alt text](image.png)
19+
20+
### 2. Install Required Libraries
21+
22+
Make sure you have the following Python libraries installed:
23+
24+
```bash
25+
pip install spotipy
26+
pip install requests
27+
```
28+
29+
30+
### 3. Run the Script
31+
32+
**Notes:**
33+
- Replace **your_spotify_client_id** and **your_spotify_client_secret** in the script with your actual Spotify API credentials.
34+
- You can extend the emotion_to_genre dictionary with more emotions and genres.
35+
- You can modify the limit=10 in the Spotify recommendations query to change the number of recommended songs.
36+
37+
To run the script, use the following command:
38+
39+
```bash
40+
python Emosic-Spoti.py
41+
```
42+
43+
**Usage**
44+
45+
After running the script, enter an emotion from the list below to get a music playlist:
46+
47+
- happy
48+
- sad
49+
- angry
50+
- relaxed
51+
- energetic
52+
- anxious
53+
- cheerful
54+
- stressed
55+
- dreamy
56+
- excited
57+
- bored
58+
- nostalgic
59+
- hopeful
60+
- content
61+
- romantic
62+
63+
Type 'exit' to quit the program.
64+
65+
If the Emotion you enter is NOT in the list, so we will show **pop** music instead.
66+
67+
**How It Works**
68+
69+
- **Authentication**: The script uses the SpotifyClientCredentials class to handle authentication with the Spotify API.
70+
- **Emotion-to-Genre Mapping**: The script maps emotions to corresponding music genres using a predefined dictionary.
71+
- **Track Recommendations**: The script queries the Spotify API to fetch song recommendations based on the selected genre.
72+
- **User Input**: The user inputs their emotion, and the script fetches and displays a playlist of matching songs.
50.3 KB
Loading
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
requests==2.32.3
2+
spotipy==2.24.0

0 commit comments

Comments
 (0)