Hướng dẫn does spotify use python? - spotify có sử dụng python không?

Hướng dẫn does spotify use python? - spotify có sử dụng python không?

Ngày 20 tháng 3 năm 2013

Hướng dẫn does spotify use python? - spotify có sử dụng python không?

Câu hỏi thường gặp nhất mà chúng tôi đã nghe tại & nbsp; Pycon & nbsp; Cuối tuần này, là làm thế nào để chúng tôi sử dụng Python tại Spotify. Hy vọng bài viết này trả lời câu hỏi!

Tại Spotify, hai địa điểm chính chúng tôi sử dụng & nbsp; Python & nbsp; là dịch vụ phụ trợ và phân tích dữ liệu. Python có thói quen xuất hiện ở những nơi ngẫu nhiên khác, vì hầu hết các nhà phát triển của chúng tôi đều có chương trình hạnh phúc trong đó.

Spotify sườn & nbsp; backend & nbsp; bao gồm nhiều dịch vụ phụ thuộc lẫn nhau, được kết nối bằng giao thức nhắn tin riêng trên & nbsp; Zeromq. Khoảng 80% các dịch vụ này được viết bằng Python.

Các dịch vụ phi Python thường được viết bằng Java, mặc dù chúng tôi có một số ít sử dụng C hoặc C ++.

Tốc độ là một trọng tâm lớn cho Spotify. Python phù hợp với suy nghĩ này, vì nó giúp chúng ta những chiến thắng lớn trong tốc độ phát triển. Chúng tôi cũng sử dụng nhiều khung Async Python để giúp các dịch vụ bị ràng buộc IO. Các dịch vụ trước đó đã được viết bằng cách sử dụng & nbsp; bị xoắn, và trong vài năm qua, chúng tôi đã ưa thích & nbsp; gevent.

Một số dịch vụ được tính toán ràng buộc và chúng tôi đã thử một loạt các chiến lược để xử lý việc này trong Python. Điều này đã bao gồm kiểm tra hiệu suất, hồ sơ, & nbsp; Cython và các thư viện gốc.

Phân tích dữ liệu

Các nhóm Spotify sử dụng nhiều phân tích, cả trong việc ra quyết định và trong chính sản phẩm. Để đơn giản hóa các tương tác với Hadoop, chúng tôi sử dụng gói & nbsp; luigi & nbsp;

Luigi cho phép bạn nhanh chóng xây dựng các đường ống phức tạp của các công việc hàng loạt từ máy của bạn. Nó xử lý gói các thư viện cần thiết và mang lại bất kỳ nhật ký lỗi nào cho máy cục bộ của bạn. Điều này có nghĩa là bạn có thể nhanh chóng tạo ra các công việc dữ liệu phức tạp.

Chúng tôi sử dụng Luigi, cùng với một loạt các thuật toán học máy, để cung cấp năng lượng cho đài phát thanh của chúng tôi và khám phá các tính năng, cũng như các đề xuất cho những người bạn có thể muốn theo dõi. Công việc đơn giản hơn sức mạnh những thứ như danh sách hàng đầu của chúng tôi.

Khoảng 90% công việc giảm bản đồ của chúng tôi được viết bằng Python. Khi nó đi ra ngoài, chúng tôi đã thấy hơn 6000 quá trình Python chạy trên hàng trăm nút trong cụm Hadoop của chúng tôi.

Sử dụng khác

Các đội Spotify thường sử dụng & nbsp; GraphWalker & nbsp; để thực hiện thử nghiệm dựa trên mô hình của cả người dùng đối mặt với máy khách cũng như một số API. Để đơn giản hóa việc tích hợp với các dịch vụ Python của chúng tôi, chúng tôi đã chuyển & nbsp; GraphWalker Runner & nbsp; to Python.

Python cũng được sử dụng cho các dịch vụ tạo mẫu, tập lệnh nhanh, quy trình xây dựng và nhiều hơn nữa. Thậm chí còn có một ứng dụng Django & nbsp; hoặc hai!

Cộng đồng

Một phần của những gì làm cho Python trở nên đặc biệt là cộng đồng xung quanh nó. Spotify có liên quan đến cộng đồng theo một số cách.

Chúng tôi tài trợ cho các hội nghị như & nbsp; pycon & nbsp; và & nbsp; euro python, cung cấp hỗ trợ cho các nhóm địa phương như

Chúng tôi luôn quan tâm đến việc làm nhiều hơn cho cộng đồng, vì vậy xin vui lòng liên lạc nếu có điều gì đó chúng tôi có thể giúp đỡ.

Nhóm của chúng tôi đã có một đống niềm vui tại Pycon và Pydata gần đây. Đó là lần đầu tiên của tôi, và tôi đã có một cuộc gặp gỡ thời gian tuyệt vời rất nhiều người và học hỏi từ cả các cuộc nói chuyện và đường đua hành lang!

Nếu bạn thích làm việc với Python tại Spotify, chúng tôi sẽ thuê & NBSP; Hoặc chỉ cần ghé qua một trong các văn phòng của chúng tôi và nói xin chào!

Tags: Dịch vụ phụ trợ, Python, Công nghệ

Muốn có một danh sách nhạc của âm nhạc tuyệt vời không bao giờ kết thúc?

Điều này trở nên rõ ràng hơn với tôi khi tôi xem 500 album vĩ đại nhất mọi thời đại mới nhất từ ​​tạp chí Rolling Stone, và nhận ra rằng tôi chỉ nghe một tỷ lệ nhỏ trong số các album "vĩ đại" được cho là suốt. The Rolling Stone xác định "sự vĩ đại" bằng cách tổng hợp kết quả khảo sát của 300 nhạc sĩ, nhà báo, nhà sản xuất và giám đốc điều hành âm nhạc (bao gồm Beyonce, Taylor Swift và Billie Eilish), mỗi người đã gửi 50 album hàng đầu của họ. Nếu bạn lo lắng, danh sách này có sự thiên vị cho âm nhạc gần đây với các nhạc sĩ đương đại được thăm dò, đừng. Những năm 2010 là địa điểm thứ hai được đại diện một thập kỷ chỉ sau những năm 1950.500 Greatest Albums of All Time from the Rolling Stone Magazine, and realized I'd only listened to a tiny percentage of the supposedly "great" albums all the way through. The Rolling Stone determined "greatness" by aggregating the survey results of some 300 musicians, journalists, producers and music executives (including Beyonce, Taylor Swift, and Billie Eilish) who each submitted their top 50 albums. If you're worried the list has a bias for recent music given the contemporary musicians polled, don't. The 2010's were the second-least represented decade behind only the 1950's.

Danh sách khét tiếng bây giờ là phân cực vô tận và tất nhiên, không hoàn hảo (làm thế nào bạn có thể thực sự so sánh The Beatles và Kendrick Lamar trong cùng một danh sách?). Nhưng nếu đủ ngành công nghiệp âm nhạc, Titans đã bỏ phiếu cho một album để nó lập danh sách, thì có lẽ nó đáng nghe, phải không? Vậy tại sao không nghe tất cả 500 album trong suốt chặng đường, bắt đầu kết thúc?polarizing and, of course, imperfect (how can you really compare the Beatles and Kendrick Lamar in the same list?). But if enough music industry titans voted for an album for it to make the list, it's probably worth listening to, right? So why not listen to all 500 albums all the way through, start to finish?

Vấn đề

Nhưng nó không đơn giản để nghe 500 album và 7.000 bài hát bao gồm chúng. Thật quá tẻ nhạt khi thêm tất cả 500 album từng người vào thư viện Spotify của bạn (hoặc thư viện dịch vụ phát trực tuyến khác). Có danh sách phát công khai trên Spotify có tất cả các album trong danh sách, nhưng theo dõi nơi bạn đang ở trong một danh sách phát dường như không thể. Tôi không muốn bị cám dỗ bỏ qua và cuối cùng nhìn ra bất kỳ. Trên thực tế, tôi thực sự muốn bị buộc phải nghe mọi album suốt cả những cách mà tôi không yêu ngay lập tức. Tôi chỉ muốn một hàng các album tuyệt vời nhất mà tôi chỉ có thể tiến bộ bằng cách nghe từng bài hát trên mỗi album. Nói tóm lại, tôi muốn một danh sách nhạc vô tận.forced to listen to every album all the way througheven the ones I'm not in love with right away. I just want a queue of the greatest albums that I can only progress through by listening to each song on each album. In short, I want an endless playlist.

Solution (using Python and the Spotify Web API)

So with Python and the Spotify Web API at my disposal, I decided to make my own Spotify playlist off the Rolling Stone's Greatest Albums list that automatically updates when I listen to a song from it, deleting the ones I listened to and adding new ones automatically. You can think of it as a giant conveyor belt of songs that you can only see a small part of, and that only turns when you listen to it. Every hour, it takes the songs I listened to (if any), deletes them, and adds the next songs up from the next album. I also randomized the albums (but kept the songs within each album in order) so I never know what's coming next and have no expectations. Best of all, if I listen to other music for an hour, I can come back to my endless playlist and know exactly where I left off: the first song. Here's how I did it, and how you can too (disclaimer: you must have Spotify Premium to do this).

Connecting to the Spotify API

First you have to make a registered app with Spotify in order to use the Spotify Web API. I prefer Python so I use the Spotipy Python library to access the API. Once you've registered your app and added a redirect URI, you can start playing with the API! Here's some sample code to authorize your credentialsjust replace the client credentials below with the ones generated by your own app. A new window will open asking if you want to give the app access to your Spotify account. After you click "Accept", copy and paste the resulting url where it prompts for it. Try it out in a Jupyter Notebook or your preferred IDE.

import spotipy import pandas as pd import numpy as np import requests from spotipy import oauth2 import re SPOTIPY_CLIENT_ID ='YOUR CLIENT ID'SPOTIPY_CLIENT_SECRET ='YOUR CLIENT SECRET'SCOPE =('user-read-recently-played,user-library-read,user-read-currently-playing,playlist-read-private,playlist-modify-private,playlist-modify-public,user-read-email,user-modify-playback-state,user-read-private,user-read-playback-state')SPOTIPY_REDIRECT_URI ='YOUR REDIRECT URI'sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE ) #click "Accept" in your browser when the auth window pops up code = sp_oauth.get_auth_response(open_browser=True)token = sp_oauth.get_access_token(code)refresh_token = token['refresh_token']sp = spotipy.Spotify(auth=token['access_token'])username = sp.current_user()['id']

Making your endless playlist

Once you're authorized and the API is working, you can create your playlist using Spotify's user_playlist_create() method. I called mine "myEndlessPlaylist1" but feel free to be more creative. You'll also want to save the playlist ID of your newly created playlist for future use (as I did with "pl_id").

#creating your playlistpl_name ='myEndlessPlaylist1' result = sp.user_playlist_create(username, name=pl_name)pl_id = result['id']

Now we need to get a list of the top 500 albums, randomize the order, and initialize the playlist. I found this playlist on Spotify that seemed to have all the albums from the list. The code below collects all songs in that playlist (each of which is a dictionary object with data like name, artist, track ID, and other fields) into a list, and then loops through that list to make a DataFrame with fields like track, artist, album, track_id and album_id. We'll use that resulting DataFrame ("album_df") to populate the endless playlist.

#ID for the public spotify playlist we're getting all the albums from top_album_pl ='70n5zfYco8wG777Ua2LlNv' #top_albums is list we'll use to make the top albums playlisttop_albums =[]offset =0while True: response = sp.playlist_items(top_album_pl, offset=offset) iflen(response['items'])== 0:break top_albums +=response['items'] offset = offset +len(response['items']) #Here we make a DataFrame of all the top albums by looping through that list of response of dictionariesalbum_df =[]for album in top_albums: track = album['track']['name'] artist = album['track']['artists'][0]['name'] album_name = album['track']['album']['name'] track_id = album['track']['id'] album_id = album['track']['album']['id'] album_df.append([track,artist,album_name, track_id,album_id])album_df = pd.DataFrame(album_df, columns =['track','artist','album','track_id','album_id'])

Randomizing and cleaning your album list

Once you have your DataFrame of all the albums, it's time to randomize the order. I just made an "all albums" DataFrame, gave a random number from 0-1 to each album and then merged it back with the full top albums DataFrame. Then I sorted by that random number ("rand_key" in the code below) and added an index column "idx" which will make it simpler to add tracks from this DataFrame to my endless playlist. There are a few compilations and incomplete albums (due to unavailability of some songs on Spotify), that lead to some one-track albums. You can delete those if you want or comment out that code to keep them. I also cleaned out characters like backslashes and quotes from the data so it will play nice.

#random seed so others can get the same album order as menp.random.seed(10) #make a DataFrame of all albums and add a random number between 0-1 "rand_key" for each albumall_albums = album_df.drop_duplicates('album_id').album_id all_albums = pd.DataFrame(all_albums).reset_index(drop=True)all_albums['rand_key'] = np.random.rand(len(all_albums)) #merge the albums DataFrame back with the full top albums DataFramealbum_df = pd.merge(album_df, all_albums, how='inner', on='album_id') #sort by the rand_key (and by index so the songs within albums stay in order)album_df['idx']= album_df.index album_df = album_df.sort_values(['rand_key','idx']).reset_index(drop=True) #run the code below to exclude one-track albumsalbum_df_piv = pd.pivot_table(album_df, index='album_id',values='track_id',aggfunc='count')album_df_piv.columns =['num_tracks']album_df = pd.merge(album_df, album_df_piv, how='left',left_on='album_id',right_index=True)album_df = album_df[album_df.num_tracks>1].reset_index(drop=True) #do some data cleaning (getting rid of quotes, backslashes) so it will play nice df.loc[(df['track'].str.contains('"')),'track']= df.track.str.replace('"','') df.loc[(df['artist'].str.contains('"')),'artist']= df.artist.str.replace('"','') df.loc[(df['album'].str.contains('"')),'album']= df.album.str.replace('"','') df.loc[(df['track'].str.contains(r"\\")),'track']= df.track.str.replace('\\','') album_df['idx']= album_df.index #copy this album df to your clipboard to paste into google sheets or elsewhere. album_df.to_clipboard(index=False)

Now with this randomized "album_df" DataFrame, you can finally initialize your playlist! Choose whatever size playlist you want, but the smaller it is the simpler it is to manageplus it creates more suspense if you can only see the next 1 or 2 albums in your queue. Since I'll be updating mine every hour, I chose 30 songs, and simply added the first 30 songs from the "album_df" DataFrame to my playlist with the playlist_add_items() method shown below.

#initialize playlist of length 30pl_length =30last_tracks_added = album_df.loc[0:pl_length-1]tracks_to_add = last_tracks_added.track_id.tolist()sp.playlist_add_items(pl_id,tracks_to_add )

You can copy the randomized DataFrame of all the albums to your clipboard and paste it into a Google Sheet to make it easier to work with. As you can see, my first album up is "Crazysexycool" by TLC.

Automating your playlist updates

Now it's time to automate updating your playlist! To do this I'm going to to grab my recently played songs with the user_recently_played() method, and delete any songs I recently played that are also currently in my endless playlist. I'll also check the "context" of my recently played songs to make sure they were played from my endless playlist (if I play a song in my endless playlist but from a different place, I don't necessarily want to delete it). I'll use the "refresh token" from access credentials dictionary above so I don't have to re-authorize every time I want to update the playlist (which I'll be doing every hour). For this code to work, you'll also need your DataFrame of all albums ("album_df") and a DataFrame of the last tracks you added ("last_tracks_added"). You'll add songs from the "album_df" starting with the index after the max index from the "last_tracks_added" DataFrame . Finally, to make it truly "endless", I'll start adding songs from the beginning again once I reach the end.

import spotipy import pandas as pd import numpy as np from spotipy import oauth2 import re SPOTIPY_CLIENT_ID ='YOUR CLIENT ID'SPOTIPY_CLIENT_SECRET ='YOUR CLIENT SECRET'SCOPE =('user-read-recently-played,user-library-read,user-read-currently-playing,playlist-read-private,playlist-modify-private,playlist-modify-public,user-read-email,user-modify-playback-state,streaming,app-remote-control,user-read-private,user-read-playback-state')SPOTIPY_REDIRECT_URI ='YOUR REDIRECT URI'SPOTIFY_USER_ID = 'YOUR SPOTIFY USER ID'sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE ) refresh_token ='YOUR REFRESH TOKEN'token_info = sp_oauth.refresh_access_token(refresh_token)sp = spotipy.Spotify(auth=token_info['access_token'])username = sp.current_user()['id']pl_id ='YOUR ENDLESS PLAYLIST ID' #add these lines if using SeekWell to automate your code (and map those Parameters to correct Google Sheet)# album_df = {{allAlbums}}# last_tracks_added = {{lastTracksAdded}} #make lists of playlist track id's and names to check against your recently played tracksthis_pl = sp.playlist_items(pl_id)['items']this_pl_ids =[track['track']['id'] for track in this_pl] #we'll use this list of track+artist names to find tracks that got added to our playlist with a different track_id (which sometimes happens)this_pl_names =[re.sub('[^0-9a-zA-Z]+', '',track['track']['name']+track['track']['artists'][0]['name'])for track in this_pl] #make a "to_delete" list of the index and URI of songs you in your playlist that you just listened toto_delete =[]recents = sp.current_user_recently_played(50)['items']for track in recents: context = track['context']if context and'playlist'in context['uri']: this_pl_id = context['uri'].split('playlist:')[1] name_artist = re.sub('[^0-9a-zA-Z]+', '',track['track']['name']+track['track']['artists'][0]['name'])if track['track']['id']in this_pl_ids and this_pl_id == pl_id : idx = this_pl_ids.index(track['track']['id']) uri = track['track']['uri'] to_delete.append([idx,uri])#including a second if statement in case that track id isn't in the playlist but that track+artist is. elif this_pl_id == pl_id and name_artist in this_pl_names: idx = this_pl_names.index(name_artist) uri ='spotify:track:'+ this_pl_ids[idx] to_delete.append([idx,uri]) #if there's no songs to delete then there's no updates to makeiflen(to_delete)> 0: #use that list to create a list of track dictionaries (which have track uri and position in the playlist) tracks =[{'uri': track[1],'positions': [track[0]]}for track in to_delete] #use that list of track dictionaries and delete them from your playlist sp.user_playlist_remove_specific_occurrences_of_tracks(username,pl_id,tracks) #make a 'tracks_to_add' DataFrame that is the same length as the "to_delete" list to_add =len(to_delete) last_index = last_tracks_added['idx'].astype(int).max() tracks_to_add = album_df.loc[last_index+1:last_index+to_add] #to make it truly "endless" start adding the first tracks again once you reach the endif(last_index+to_add)>=len(album_df): tracks_to_add = pd.concat([tracks_to_add, album_df.loc[0:(last_index+to_add)%len(album_df)]],axis=0) #add those songs to your playlist sp.playlist_add_items(pl_id,tracks_to_add.track_id.tolist()) #add this code if using SeekWell to automate your Python so you can send the "tracks_to_add" DataFrame somewhere #tracks_to_add#seekwell = {'df': tracks_to_add}

Tuyệt quá! Bây giờ chúng tôi có mã thông qua các bài hát được chơi gần đây của bạn, xóa bất kỳ bài hát nào từ danh sách phát vô tận của bạn (và nó thực sự được phát từ nó), và sau đó thêm cùng một số bài hát mới vào danh sách phát vô tận của bạn. Phương pháp này buộc bạn phải nghe mọi bài hát trong suốt (mà tôi thực sự thích) vì vậy nó hiển thị trong trò chơi gần đây của bạn. Nếu bạn muốn có thể bỏ qua các bài hát và vẫn bị xóa, bạn có thể thay đổi mã để lấy chỉ số cao nhất từ ​​DataFrame "Album_DF" đầy đủ của bạn cũng có trong các bài hát được phát và xóa gần đây khỏi danh sách phát của bạn với các chỉ mục thấp hơn thế.

Nếu bạn thích sử dụng Shuffle khi nghe nhạc khác của mình, bạn phải nhớ tắt chế độ Shuffle khi bạn nghe danh sách phát "vô tận" của mình.

Lên lịch mã của bạn với Seekwell

Bây giờ chúng ta chỉ cần chạy mã này mỗi giờ và lưu trữ dữ liệu "last_tracks_added" ở đâu đó. Tôi hơi thiên vị kể từ khi tôi làm việc ở đó, nhưng công cụ ưa thích của tôi để tự động hóa mã Python là tìm kiếm. Nó cho phép bạn chạy bất kỳ mã Python nào và tự động hóa nó theo lịch trình (ví dụ: hàng ngày, hàng giờ, cứ sau năm phút). Nó cũng cung cấp cho bạn quyền truy cập bản địa vào các khung dữ liệu từ Google Sheets hoặc cơ sở dữ liệu của bạn, trong trường hợp này rất hữu ích để tôi có thể nhập các khung dữ liệu "album_df" và "Last_Tracks_added" để biết các bản nhạc nào sẽ thêm tiếp theo. Bạn có thể đăng ký dùng thử miễn phí hai tuần tại đây và kiểm tra các tài liệu để sử dụng Python tại đây. Bạn cũng có thể sử dụng một công cụ khác để lên lịch mã Python của mình hoặc chỉ chạy mã cập nhật theo cách thủ công khi bạn có cơ hội. Một cảnh báo là phương thức user_recenty_play () của Spotify đã chỉ lưu trữ tối đa 50 bài hát, vì vậy nếu bạn nghe hơn 50 bài hát giữa việc cập nhật danh sách phát của bạn, một số sẽ thực sự sẽ bị xóa.SeekWell. It lets you run any Python code and automate it on a schedule (e.g. daily, hourly, every five minutes). It also gives you native access to DataFrames from Google Sheets or your database, which in this case is helpful so I can import my "album_df" and "last_tracks_added" DataFrames to know which tracks to add next. You can sign up for your two week free trial here and check out the docs for using Python here. You can also use a different tool for scheduling your Python code or just run the update code manually when you get the chance. One caveat is that Spotify's user_recently_played() method only stores up to 50 songs so if you listen to more than 50 songs in between updating your playlist, some won't actually get deleted.

Nếu bạn sử dụng Seekwell, hãy thêm mã này vào cuối tập lệnh Python của bạn và bạn có thể gửi DataFrame đó bất cứ nơi nào bạn muốn. Trong trường hợp này, tôi đang gửi nó đến Google Sheets để tôi có thể đọc lại vào giờ tiếp theo để biết tôi vừa thêm bản nhạc nào.

Seekwell = {'df': Track_to_add}={'df': tracks_to_add}

Tôi cũng đang đọc trong các khung dữ liệu "album_df" và "Last_Tracks_added" từ Google Sheets thông qua các tham số của Seekwell, giống như phương thức nhập không mã hóa. Để tự làm điều này, hãy tạo một tên bí danh cho các khung dữ liệu bạn muốn nhập theo dấu ngoặc đôi và trong đó nó nói "tham số" ở bên phải, thay đổi loại thành "tờ" và nhập tên của trang Google của bạn.Parameters, which is like a no-code import method. To do this yourself, create an alias name for the DataFrames you want to import in double curly brackets, and where it says "Parameters" on the right, change the Type to "Sheets" and enter the name of your Google Sheet.

Bây giờ chỉ cần chọn lịch trình của bạn. Tôi thường xuyên nghe danh sách phát vô tận của mình trong khi tôi làm việc để cập nhật hàng giờ có ý nghĩa nhất đối với tôi. Nhưng nếu bạn chỉ thỉnh thoảng nghe hoặc danh sách phát của bạn lớn hơn, bạn cũng có thể chọn cập nhật hàng ngày hoặc thậm chí hàng tuần.

Vui thích! Hãy nhớ lưu các bài hát bạn thích vào thư viện của bạn ngay trước khi chúng bị xóa. Sử dụng hạt giống ngẫu nhiên giống như tôi (10) và hãy cùng nhau lắng nghe. Hãy tiếp cận nếu bạn có bất kỳ vấn đề nào và theo dõi hành trình lắng nghe của tôi ở đây.here.

Tất cả các mã được sử dụng cho dự án này có thể được tìm thấy trên github của tôi ở đây.here.

Bởi Brian Kane @Seekwell.SeekWell.