Shivam Prasad commited on
Commit
123e163
·
verified ·
1 Parent(s): a301546

Update music_recommender.py

Browse files
Files changed (1) hide show
  1. music_recommender.py +83 -52
music_recommender.py CHANGED
@@ -2,67 +2,98 @@ import spotipy
2
  from spotipy.oauth2 import SpotifyClientCredentials
3
  import random
4
  import os
 
5
 
6
- # Enhanced emotion-to-genre mapping
7
- def get_music_recommendations(emotion):
8
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Define emotion to genre mapping (now with Hindi/English focus)
11
- mood_to_genre = {
12
- "Happy": "bollywood pop",
13
- "Sad": "indian indie",
14
- "Angry": "indian rock",
15
- "Relaxed": "indian classical",
16
- "Fear": "indian ambient",
17
- "Disgust": "indian metal",
18
- "Surprise": "indian electronic",
19
- "Neutral": "indian folk"
20
- }
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  client_id = os.getenv("SPOTIFY_CLIENT_ID")
23
  client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
24
-
25
  if client_id and client_secret:
26
- sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
27
- client_id=client_id,
28
- client_secret=client_secret
29
- ))
30
-
31
- genre = mood_to_genre.get(emotion, "bollywood")
32
-
33
- # Search for Hindi/English tracks in the genre
34
- query = f"genre:{genre} (tag:hindi OR tag:english)"
35
- results = sp.search(q=query, type="track", limit=10, market="IN") # 'IN' for India market
36
-
37
- songs = []
38
- for track in results['tracks']['items']:
39
- # Additional check for Hindi/English in track name or artist
40
- if any(keyword in track['name'].lower() or
41
- any(keyword in artist['name'].lower() for artist in track['artists'])
42
- for keyword in ["hindi", "english", "bollywood"]):
43
- songs.append({
44
- "name": track['name'],
45
- "artist": track['artists'][0]['name'],
46
- "url": track['external_urls']['spotify'],
47
- "image_url": track['album']['images'][0]['url'] if track['album']['images'] else ""
48
- })
49
-
50
- # If no results, fallback to Bollywood
51
- if not songs:
52
- results = sp.search(q="genre:bollywood", type="track", limit=10, market="IN")
53
- for track in results['tracks']['items']:
54
- songs.append({
55
- "name": track['name'],
56
- "artist": track['artists'][0]['name'],
57
- "url": track['external_urls']['spotify'],
58
- "image_url": track['album']['images'][0]['url'] if track['album']['images'] else ""
59
- })
60
  else:
61
- # Fallback to Hindi/English mock data
62
- songs = get_hindi_english_mock_recommendations(emotion)
63
-
64
- return songs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
 
 
66
 
67
  def get_hindi_english_mock_recommendations(emotion):
68
  """Mock recommendations focused on Hindi/English songs"""
 
2
  from spotipy.oauth2 import SpotifyClientCredentials
3
  import random
4
  import os
5
+ import logging
6
 
7
+ # Setup logging
8
+ logging.basicConfig(level=logging.INFO)
9
 
10
+ # Emotion-to-genre mapping
11
+ MOOD_TO_GENRE = {
12
+ "Happy": "pop",
13
+ "Sad": "acoustic",
14
+ "Angry": "rock",
15
+ "Relaxed": "chill",
16
+ "Fear": "ambient",
17
+ "Disgust": "metal",
18
+ "Surprise": "electronic",
19
+ "Neutral": "indie"
20
+ }
21
 
22
+ # Hindi music indicators
23
+ HINDI_KEYWORDS = [
24
+ # Popular Hindi singers
25
+ "Arijit", "Shreya", "Neha", "Kumar", "Jubin", "Sonu", "KK", "Rahat", "Mohit", "Atif", "Udit",
26
+ "Lata", "Kishore", "Asha", "Sunidhi", "Alka", "Shaan", "Pritam", "Armaan", "Badshah",
 
 
 
 
 
 
27
 
28
+ # Common Hindi song words
29
+ "Zindagi", "Dil", "Tera", "Mera", "Pyaar", "Ishq", "Mohabbat", "Yaad", "Saath", "Tum", "Hum",
30
+ "Jaan", "Pal", "Raat", "Sapna", "Chand", "Tujh", "Aankhon", "Leja", "Bekhayali",
31
+
32
+ # Bollywood related
33
+ "Bollywood", "Hindi", "Desi", "India", "Mumbai", "Aashiqui", "Kalank", "Kabir", "Dostana",
34
+
35
+ # Regional cross-over terms
36
+ "Punjabi", "Lofi", "Romantic", "Mashup", "Bolna", "Baarish", "Love Story"
37
+ ]
38
+
39
+ def is_hindi_or_english(text):
40
+ """Heuristic to detect Hindi or English songs based on metadata"""
41
+ if not text:
42
+ return False
43
+ text_lower = text.lower()
44
+ return (
45
+ all(ord(char) < 128 for char in text) # mostly English
46
+ or any(keyword.lower() in text_lower for keyword in HINDI_KEYWORDS)
47
+ )
48
+
49
+ def get_spotify_client():
50
+ """Initialize Spotify client if credentials are available"""
51
  client_id = os.getenv("SPOTIFY_CLIENT_ID")
52
  client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
53
+
54
  if client_id and client_secret:
55
+ try:
56
+ return spotipy.Spotify(auth_manager=SpotifyClientCredentials(
57
+ client_id=client_id,
58
+ client_secret=client_secret
59
+ ))
60
+ except Exception as e:
61
+ logging.warning(f"Spotify auth failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  else:
63
+ logging.warning("Spotify credentials not found in environment.")
64
+ return None
65
+
66
+ def get_music_recommendations(emotion):
67
+ """Get songs based on emotion, filtered by language preference"""
68
+ genre = MOOD_TO_GENRE.get(emotion, "pop")
69
+ sp = get_spotify_client()
70
+
71
+ if sp:
72
+ try:
73
+ offset = random.randint(0, 950)
74
+ results = sp.search(q=f"genre:{genre}", type="track", limit=50, offset=offset)
75
+
76
+ songs = []
77
+ for track in results.get('tracks', {}).get('items', []):
78
+ title = track['name']
79
+ artist = track['artists'][0]['name']
80
+ if is_hindi_or_english(title) or is_hindi_or_english(artist):
81
+ songs.append({
82
+ "name": title,
83
+ "artist": artist,
84
+ "url": track['external_urls']['spotify'],
85
+ "image_url": track['album']['images'][0]['url'] if track['album']['images'] else ""
86
+ })
87
+
88
+ if songs:
89
+ return songs[:10]
90
+ else:
91
+ logging.info("No Hindi or English songs found in Spotify results. Falling back to mock data.")
92
+ except Exception as e:
93
+ logging.error(f"Spotify API error: {e}")
94
 
95
+ # Fallback to mock recommendations
96
+ return get_mock_recommendations(genre)
97
 
98
  def get_hindi_english_mock_recommendations(emotion):
99
  """Mock recommendations focused on Hindi/English songs"""