-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotify_utils.py
78 lines (65 loc) · 2.85 KB
/
spotify_utils.py
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
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import datetime
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
def create_spotify_client():
"""Create and return a Spotify client with proper authentication"""
if not all([os.getenv('SPOTIPY_CLIENT_ID'),
os.getenv('SPOTIPY_CLIENT_SECRET'),
os.getenv('SPOTIPY_REDIRECT_URI')]):
raise Exception("Missing Spotify credentials in .env file")
scope = "streaming user-read-playback-state user-modify-playback-state"
cache_path = ".spotify_cache"
auth_manager = SpotifyOAuth(
scope=scope,
cache_path=cache_path,
open_browser=False # Prevent automatic browser opening
)
return spotipy.Spotify(auth_manager=auth_manager)
def timestamp_to_ms(timestamp):
"""Convert timestamp string (MM:SS) to milliseconds"""
time_parts = timestamp.split(':')
minutes = int(time_parts[0])
seconds = int(time_parts[1])
return (minutes * 60 + seconds) * 1000
def search_track(sp, song, artist):
"""Search for a track on Spotify"""
print(f"Searching for track: {song} by {artist}") # Debug log
query = f"track:{song} artist:{artist}"
results = sp.search(q=query, type='track', limit=1)
if results['tracks']['items']:
print(f"Found track: {song}") # Debug log
return results['tracks']['items'][0]
print(f"No results found for: {song}") # Debug log
return None
def create_medley_queue(sp, mixtape_data):
"""Create a queue of tracks with their start and stop times"""
print("Starting medley queue creation...") # Debug log
medley_queue = []
for song in mixtape_data['songs']:
print(f"Processing song: {song['song']}") # Debug log
track = search_track(sp, song['song'], song['artist'])
if track:
# Convert timestamps to milliseconds
start_ms = timestamp_to_ms(song['start_timestamp'])
stop_ms = timestamp_to_ms(song['stop_timestamp'])
# Validate timestamps
track_duration_ms = track['duration_ms']
if start_ms >= track_duration_ms:
print(f"Warning: Start time {song['start_timestamp']} exceeds track duration for {song['song']}")
continue
if stop_ms > track_duration_ms:
print(f"Warning: Adjusting stop time to track duration for {song['song']}")
stop_ms = track_duration_ms
medley_queue.append({
'uri': track['uri'],
'start_ms': start_ms,
'stop_ms': stop_ms,
'song': song['song'],
'artist': song['artist']
})
print(f"Completed medley queue creation with {len(medley_queue)} tracks") # Debug log
return medley_queue