-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspotify_recommender.py
More file actions
105 lines (88 loc) · 3.72 KB
/
Copy pathspotify_recommender.py
File metadata and controls
105 lines (88 loc) · 3.72 KB
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
import os
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from dotenv import load_dotenv
load_dotenv()
CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID')
CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET')
if not CLIENT_ID or not CLIENT_SECRET:
print("Error: Spotify API credentials not loaded. Make sure SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET are set in your .env file.")
exit()
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET))
EMOTION_TO_SEARCH_MAP = {
"happy": {
"keywords": ["happy pop", "upbeat dance", "joyful songs"],
"genres": ["pop", "dance", "funk"]
},
"sad": {
"keywords": ["sad acoustic", "melancholy piano", "heartbreak songs"],
"genres": ["acoustic", "ambient", "ballad"]
},
"angry": {
"keywords": ["angry rock", "intense metal", "rage rap"],
"genres": ["rock", "metal", "hip-hop"]
},
"neutral": {
"keywords": ["chill lo-fi", "relaxing instrumental", "calm background music"],
"genres": ["lo-fi", "ambient", "chill"]
},
"surprise": {
"keywords": ["exciting electronic", "unpredictable indie", "bouncy pop"],
"genres": ["electronic", "indie-pop", "alternative"]
},
"fear": {
"keywords": ["dark ambient", "suspenseful instrumental", "eerie soundscapes"],
"genres": ["ambient", "dark-ambient"]
},
"disgust": {
"keywords": ["heavy metal", "punk rock", "industrial music"],
"genres": ["heavy-metal", "punk"]
}
}
def get_music_recommendations(emotion, limit=5):
emotion = emotion.lower()
search_terms = EMOTION_TO_SEARCH_MAP.get(emotion, EMOTION_TO_SEARCH_MAP["neutral"])
keywords = search_terms.get("keywords")
genres_for_search = search_terms.get("genres")
query = keywords[0] if keywords else genres_for_search[0]
if not query:
print(f"Warning: No valid search query for emotion '{emotion}'.")
return []
try:
results = sp.search(q=query, type='track', limit=limit)
tracks = []
for track in results['tracks']['items']:
tracks.append({
'name': track['name'],
'artist': track['artists'][0]['name'],
'url': track['external_urls']['spotify'],
'embed_url': f"https://open.spotify.com/embed/track/{track['id']}"
})
return tracks
except spotipy.SpotifyException as e:
print(f"Spotify API Error during search: {e}")
return []
except Exception as e:
print(f"An unexpected error occurred during search: {e}")
return []
if __name__ == "__main__":
print("--- Spotify Music Recommender Test (Search-Based) ---")
emotions_to_test = ["happy", "sad", "angry", "neutral", "surprise"]
for emotion in emotions_to_test:
print(f"\nRecommending for '{emotion}' emotion:")
recommendations = get_music_recommendations(emotion, limit=3)
if recommendations:
for i, track in enumerate(recommendations):
print(f" {i+1}. {track['name']} by {track['artist']}")
print(f" URL: {track['url']}")
print(f" Embed URL: {track['embed_url']}")
else:
print(f" No recommendations found for '{emotion}'.")
print("\nRecommending for 'confused' emotion (should fallback to neutral):")
recommendations = get_music_recommendations("confused", limit=2)
if recommendations:
for i, track in enumerate(recommendations):
print(f" {i+1}. {track['name']} by {track['artist']}")
else:
print(" No recommendations found for 'confused'.")