def album_content(album_uri): results = spotify.album(album_uri) songs = [] for song in results['tracks']['items']: track = Track(name=song['name'], uri=song['uri']) songs.append(track.to_dict()) return {'playlists': songs}
def playlist_track(playlist_uri): username = spotify_username() tracks_in_playlist = [] results = spotify.user_playlist(username, playlist_uri, fields="tracks,next") for tracks in results['tracks']['items']: single_track = tracks['track'] track = Track(single_track['name'], single_track['uri'], single_track['album']['images'][1]['url']) tracks_in_playlist.append(track.to_dict()) return {'playlists': tracks_in_playlist}
def show_tracks(tracks): results = [] for i, track in enumerate(tracks['items']): results.append( Track(track['name'], track['artists'][0]['name'], track['id'], track['album']['images'][0]['url'], None, track['duration_ms'])) return results
def get_track(self, name): try: track = self.conference.tracks[name] except KeyError: track = Track(name) self.conference.tracks[name] = track return track
def get_top_tracks(auth_header,artists): """ Return list containing 10 track ids per artist. """ top_tracks = [] for artist_id in artists: request = "{}/artists/{}/top-tracks?country=IN".format(SPOTIFY_API_URL, artist_id) track_data = get_spotify_data(request, auth_header) tracks = track_data['tracks'] for track in tracks: track_uri = track['uri'] track_id = track['id'] track_name = track['name'] track_exist = db.session.query(Track).filter(Track.uri == track_uri).all() if not track_exist: new_track = Track(uri=track_uri, id=track_id, name=track_name) db.session.add(new_track) user = session.get('user') new_user_track_exist = db.session.query(UserTrack).filter(UserTrack.user_id == user,UserTrack.track_uri == track_uri).all() if not new_user_track_exist: new_user_track = UserTrack(user_id=user, track_uri=track_uri) db.session.add(new_user_track) if track['id'] not in top_tracks: top_tracks.append(track['id']) db.session.commit() return top_tracks
def create_track(acoutsicness, danceability, duration_ms, energy, track_id, instrumentalness, key, liveness, loudness, mode, name, speechiness, tempo, valence, mood, artist, album_art): track = Track(acoutsicness=acoutsicness, danceability=danceability, duration_ms=duration_ms, energy=energy, track_id=track_id, instrumentalness=instrumentalness, key=key, liveness=liveness, loudness=loudness, mode=mode, name=name, speechiness=speechiness, tempo=tempo, valence=valence, mood=mood, artist=artist, album_art=album_art) db.session.add(track) db.session.commit() return track
def add_track_to_db(sp_track, audio_features): """Create Track object, add to database""" sp_track_id = sp_track['id'] duration_ms = sp_track['duration_ms'] album = sp_track['album']['name'] is_explicit = sp_track['explicit'] title = sp_track['name'] artist = ', '.join(artist['name'] for artist in sp_track['artists']) tempo = int(round(audio_features['tempo'])) danceability = audio_features['danceability'] energy = audio_features['energy'] valence = audio_features['valence'] track = Track( sp_track_id=sp_track_id, title=title, artist=artist, album=album, duration_ms=duration_ms, tempo=tempo, danceability=danceability, energy=energy, is_explicit=is_explicit, valence=valence, ) db.session.add(track) db.session.commit() print "Added to DB:", track return track
def get_playlist_tracks(self, playlist: Playlist, enriched=False) -> Generator[Track, None, None]: continue_ = True current_offset = 0 while continue_: r = self._spotipy.playlist_tracks(playlist_id=playlist.identifier, offset=current_offset) for item in r["items"]: track = Track( duration=item["track"]["duration_ms"], explicit=item["track"]["explicit"], identifier=item["track"]["id"], name=item["track"]["name"], popularity=item["track"]["popularity"], ) if enriched: track = self.enrich_track(track) yield track continue_ = (r["offset"] + r["limit"]) < r["total"] current_offset = r["offset"]
def currently_playing(): authenticate() result = requests.get(url='https://api.spotify.com/v1/me/player/currently-playing', headers={'Authorization': "Bearer " + token}) result_json = result.json() track = result_json["item"] return Track(track['name'], track['artists'][0]['name'], track['id'], track['album']['images'][0]['url'], result_json['progress_ms'], track['duration_ms'])
def show_tracks_in_playlist(playlist): results = [] for i, item in enumerate(playlist['items']): track = item["track"] results.append( Track(track['name'], track['artists'][0]['name'], track['id'], track['album']['images'][0]['url'], None, track['duration_ms'])) return results
def get(self): user = users.get_current_user() user_track = {} pub_track = {} pub_track_count = 0 if user: user_track = Track.all().filter('user',user).order('begin_time') else: pub_track = Track.all().filter('private', False).order('begin_time') pub_track_count = pub_track.count() template_values = { 'user_track': user_track, 'pub_track' : pub_track, 'pub_track_count' : pub_track_count } path = os.path.join(os.path.dirname(__file__),'templates/list.html') self.response.out.write(template.render(path,template_values))
def add_track(obj): with session_scope() as session: session.add( Track(name=obj['name'], spotify_id=obj['spotify_id'], explicit=obj['explicit'], runtime=obj['duration_ms'], popularity=obj['popularity'], preview_url=obj['preview_url']))
def get_top_tracks(self, artist_id: str) -> Generator[Track, None, None]: r = self._spotipy.artist_top_tracks(artist_id) for track_obj in r["tracks"]: yield Track( duration=track_obj["duration_ms"], explicit=track_obj["explicit"], identifier=track_obj["id"], name=track_obj["name"], popularity=track_obj["popularity"], )
def create_track_return_as_dict(uid, title, artist, album, release_date, playtime, genre, preview, popularity, album_art): """Create a new track""" track = Track(uid=uid, title=title, artist=artist, album=album, release_date=release_date, playtime=playtime, genre=genre, preview=preview, popularity=popularity, album_art=album_art) db.session.add(track) db.session.commit() return track.as_dict()
def create_track(track_id, track_name, artist_name): """Create and return a new Track""" track = Track(track_id=track_id, track_name=track_name, artist_name=artist_name) db.session.add(track) db.session.commit() return track
def _get_saved_tracks(self, progress=None): """Get the Tracks from the "Saved" songs. Args: progress (Progress): Progress associated with this call. Returns: tuple: The Tracks. """ q = {"limit": 50} url = "me/tracks" page = self.get_api_v1(url, q) return tuple(Track(saved["track"]) for saved in self.extract_page(page, progress))
def Track(locale, data): if not data: return {} mdl = TrackModel() mdl.trackingId = data.get('trackingId', 'None') mdl.uniqueId = data.get('uniqueId', 'None') mdl.version = data.get('version', 'None') mdl.events = data.get('events', 'None') mdl.put() return {}
def get_currently_playing(self): """Get the currently playing Track. Returns: Track: The currently playing Track or NoneTrack. """ playing = self.get_api_v1("me/player/currently-playing") if playing: track = playing['item'] if track: playing.update(track) return Track(playing) else: return NoneTrack else: return NoneTrack
def get_track(self, track_id: str) -> Track: r = self._spotipy.track(track_id) artists = [] for artist_obj in r["artists"]: artists.append(self.get_artist(artist_obj["id"])) return self.enrich_track( Track( artists=artists, duration=r["duration_ms"], explicit=r["explicit"], identifier=r["id"], name=r["name"], popularity=r["popularity"], ))
def get_tracks_from_album(self, album, progress=None): """Get Tracks from a certain Album. Args: album (Album): The Album to get Tracks from. Returns: tuple: The Tracks. """ q = {"limit": 50} url = "albums/{}/tracks".format(album['id']) page = self.get_api_v1(url, q) tracks = [] for track in self.extract_page(page, progress): track['album'] = album tracks.append(Track(track)) return tuple(tracks)
def parseTrack(self): flags = self.readByte() trackname = self.getPaddedString(40) nstrings = self.readSignedInt() track = Track(trackname, nstrings) for j in range(7): tuning = self.readSignedInt() track.tuning.append(tuning) track.port = self.readSignedInt() track.channel = self.readSignedInt() - 1 track.effectChannel = self.readSignedInt() - 1 track.frets = self.readSignedInt() track.capo = self.readSignedInt() track.color = self.readColor() return track
def get_top_tracks_from_artist(self, artist, market=None): """Get top tracks from a certain Artist. This also returns a pseudo-track to play the Artist context. Args: artist (Artist): The Artist to get Tracks from. market (str): The market. Default is None which means use the account. Returns: tuple: The Tracks. """ q = {"country": market or self.get_market()} url = "artists/{}/top-tracks".format(artist['id']) result = self.get_api_v1(url, q) if result: return tuple(Track(t) for t in result["tracks"]) else: return []
def get_top_tracks(auth_header, artists): """ Return list containing 10 track ids per artist. Add tracks to Track model as well as to UserTrack model to associate them with the user. """ top_tracks = [] for artist_id in artists: request = f'{SPOTIFY_API_URL}/artists/{artist_id}/top-tracks?country=US' track_data = requests.get(request, headers=auth_header).json() # track_data = get_spotify_data(request, auth_header) tracks = track_data['tracks'] for track in tracks: track_uri = track['uri'] track_id = track['id'] track_name = track['name'] track_exist = db.session.query(Track).filter( Track.uri == track_uri).all() if not track_exist: new_track = Track(uri=track_uri, id=track_id, name=track_name) db.session.add(new_track) user = session.get('user') new_user_track_exist = db.session.query(UserTrack).filter( UserTrack.user_id == user, UserTrack.track_uri == track_uri).all() if not new_user_track_exist: new_user_track = UserTrack(user_id=user, track_uri=track_uri) db.session.add(new_user_track) if track['id'] not in top_tracks: top_tracks.append(track['id']) db.session.commit() return top_tracks
def get_tracks_from_playlist(self, playlist, progress=None): """Get Tracks from a certain Playlist. Args: playlist (Playlist): The Playlist to get Tracks from. progress (Progress): Progress associated with this call. Returns: tuple: The Tracks. """ # Special case for the "Saved" Playlist if playlist['uri'] == common.SAVED_TRACKS_CONTEXT_URI: return self._get_saved_tracks(progress) else: q = {"limit": 50} url = "users/{}/playlists/{}/tracks".format(playlist['owner']['id'], playlist['id']) page = self.get_api_v1(url, q) result = [Track(track["track"]) for track in self.extract_page(page, progress)] return tuple(result)
def get_all_tracks_from_artist(self, artist, progress=None): """Return all tracks from an Artist. This includes the top tracks and albums from the artist. Args: artist (Artist): The Artist. progress (Progress): Progress associated with this call. Returns: iter: The Tracks. """ albums = self.get_albums_from_artist(artist) if albums: n = len(albums) tracks = [] for i, a in enumerate(albums): for t in self.get_tracks_from_album(a): tracks.append(Track(t)) if progress: progress.set_percent(float(i)/n) tracks = (t for t in tracks if artist['name'] in str(t)) return tuple(tracks)
def add_track(): """ Add a track to the user's chosen playlist and creates track-playlist relationship. """ artist = request.form.get("artist") title = request.form.get("title") rss = request.form.get("rss") img = request.form.get("img") playlist_title = request.form.get("playlist") track = Track(artist=artist, title=title, audio=rss, img=img) db.session.add(track) db.session.commit() new_track = Track.query.filter_by(audio=rss).first() track_id = new_track.track_id playlist = Playlist.query.filter_by(title=playlist_title).first() playlist_id = playlist.playlist_id track_playlist = TrackPlaylist(track_id=track_id, playlist_id=playlist_id) db.session.add(track_playlist) db.session.commit() return redirect("/user")
def load_all(self, fname='strt_session.root'): full_fname = os.path.abspath(fname) if not os.path.exists(full_fname): print 'File %s does not exists.' % full_fname return runs = [] with root_open(full_fname) as root_file: directories = next(root_file.walk())[1] for dir in directories: run_id = generate_run_id(runs) run = Run(run_id, name=dir) event_tree = root_file.Get(dir).Get('Events') track_tree = None try: track_tree = root_file.Get(dir).Get('Tracks') except DoesNotExist: pass for event in event_tree: e = Event(ev_id=event.id, data_file_path='') for i in range(event.xhits.size()): h = Hit(event.xhits[i], event.yhits[i]) e.hits.append(h) run.events.append(e) current_event = run.events[0] for track in track_tree: ev_id = track.event_id if ev_id != current_event.id: current_event = filter_by_id(run.events, ev_id) t = Track(ev_id, track.id) for i in track.hit_indices: t.hit_indices.append(i) t.color_from_int(track.color) t.rho = track.rho t.theta = track.theta t.set_line((track.x0, track.x1), (track.y0, track.y1)) t.R2 = track.R2 t.is_good = track.is_good t.calculate_parameters(current_event) current_event.tracks.append(t) runs.append(run) print '%d runs were loaded' % len(runs) return runs
def post(self): user = users.get_current_user() if user: data = self.request.get("data") if not data: self.response.out.write('No data received!') return if data[0:5] == '<?xml': logging.info('upload file type: gpx') obj = XML2Dict() rs = obj.fromstring(data) section_count = len(rs.gpx.trk) logging.info(100000+section_count) #self.response.out.write(rs) for trk in rs.gpx.trk: point_count = len(trk.trkseg.trkpt) #logging.info(2000+point_count) begin_dt = trk.trkseg.trkpt[0]['time'].value tmp = begin_dt[0:-1].split('T') begin_time = tmp[0]+tmp[1] end_dt = trk.trkseg.trkpt[-1]['time'].value tmp = end_dt[0:-1].split('T') end_time = tmp[0]+tmp[1] tt = Track.all().filter('user', user).filter('begin_time',datetime.datetime.strptime(begin_time,'%Y-%m-%d%H:%M:%S')).filter('end_time',datetime.datetime.strptime(end_time,'%Y-%m-%d%H:%M:%S')) if tt and tt.count()>0: continue t = Track() t.upload_time += datetime.timedelta(hours=+8) t.begin_time = datetime.datetime.strptime(begin_time,'%Y-%m-%d%H:%M:%S') t.end_time = datetime.datetime.strptime(end_time,'%Y-%m-%d%H:%M:%S') t.description = '' t.put() key = t.key() i = 0 step = int(math.ceil(point_count/618.0)) logging.info('point_count:'+str(point_count)) logging.info('step:'+str(step)) for trkpt in trk.trkseg.trkpt: i += 1 if i!= point_count and (i+step-1)%step != 0: continue dt = trkpt['time'].value tmp = dt[0:-1].split('T') time = tmp[0]+tmp[1] ele = trkpt['ele'].value lon = trkpt['lon'].value lat = trkpt['lat'].value pdop = trkpt['pdop'].value tp = TrackPoint() tp.trackid = key tp.time = datetime.datetime.strptime(time,'%Y-%m-%d%H:%M:%S') tp.point = db.GeoPt(lat, lon) if ele=='NaN': ele = 0 tp.elevation = float(ele) tp.speed = 0.0 tp.pdop = float(pdop) tp.put() else: logging.info('upload file type: csv') sections = data.split('-') for section in sections[1:]: lines = section.splitlines() first = lines[1].split(',') begin_time = first[0]+first[1] last = lines[-1].split(',') end_time = last[0]+last[1] tt = Track.all().filter('user', user).filter('begin_time',datetime.datetime.strptime(begin_time,'%Y%m%d%H%M%S')).filter('end_time',datetime.datetime.strptime(end_time,'%Y%m%d%H%M%S')) if tt and tt.count()>0: continue t = Track() t.upload_time += datetime.timedelta(hours=+8) t.begin_time = datetime.datetime.strptime(begin_time,'%Y%m%d%H%M%S') t.end_time = datetime.datetime.strptime(end_time,'%Y%m%d%H%M%S') t.description = '' t.put() key = t.key() i = 0 step = int(math.ceil((len(lines)-1)/400.0)) logging.info('point_count:'+str(len(lines))) logging.info('step:'+str(step)) tp_list = [] for line in lines[1:]: i += 1 if (i+1)!= len(lines) and (i+step-1)%step != 0: continue #logging.info(line) fields = line.split(',') tp = TrackPoint() tp.trackid = key tp.time = datetime.datetime.strptime(fields[0]+fields[1],'%Y%m%d%H%M%S') tp.point = db.GeoPt(fields[2], fields[3]) if fields[4]=='NaN': ele = 0 else: ele = fields[4] tp.elevation = float(ele) speed = fields[7] if speed == 'NaN': speed = 0.0 else: speed = float(fields[7]) tp.speed = speed tp.pdop = float(fields[9]) tp_list.append(tp) db.put(tp_list) self.response.out.write('1') else: self.response.out.write('Not Login')
def __init__(self): self.Track = Track.Track('Groningen GP')
def test_add_remove_hits(self): self.aux() ev_id = 21 ev = generate_event(None, ev_id) test_hit_coords = [ (58.5, 44.3), (39.2, 63.8), (11.4, 78.1), (58.6, 24.8), (26.9, 59.9), (13.6, 75.4), (8.6, 52.9), (55.6, 28.3), (0.6, 71.1), (9.2, 22.8), (62.9, 57.6), (38.1, 64.7), (51.5, 4.0), (32.1, 65.3), (8.7, 35.6), (42.7, 17.1), (34.2, 41.6), (55.6, 4.7), (12.1, 40.7), (23.4, 65.3), (39.0, 27.9), (5.3, 44.6), (27.0, 60.6), (60.5, 29.0), (49.8, 55.5), (29.9, 11.4), (60.6, 53.8), (57.5, 58.0), (23.7, 3.7), (32.1, 15.6), (33.1, 3.5), (17.0, 12.5), (59.7, 49.3), (19.7, 53.5), (35.3, 44.5), (2.1, 43.4), (37.6, 56.8), (46.0, 23.6), (6.7, 25.9), (46.0, 53.9), (46.6, 18.6), (58.7, 41.2), (34.8, 75.0), (46.4, 1.7), (5.5, 37.6), (62.0, 45.4), (20.8, 68.8), (43.2, 45.0), (48.7, 15.5), (31.9, 47.8) ] for x, y in test_hit_coords: ev.add_hit(Hit(x, y)) track0 = Track(track_id=0, track_type="selected") track1 = Track(track_id=1, track_type="recognized") track0.add_hits_indices(range(0, 15)) track0.add_hits_indices(range(3, 10)) track0.add_hits_indices(range(11, 17)) track1.add_hits_indices(range(19, 35)) track1.add_hits_indices(range(21, 26)) track1.remove_hits_indices(range(23, 29)) ev.add_track(track0) ev.add_track(track1) self.add_event(ev) # use sets here since add/remove hits mixes up the existing indices track0_hit_inds = set(self.m.get_event(ev_id).get_track(0).hit_indices) expected_track0_hit_inds = set(range(0, 17)) self.assertEqual(len(track0_hit_inds ^ expected_track0_hit_inds), 0) track1_hit_inds = set(self.m.get_event(ev_id).get_track(1).hit_indices) expected_track1_hit_inds = set(range(19, 23) + range(29, 35)) self.assertEqual(len(track1_hit_inds ^ expected_track1_hit_inds), 0)
def enrich_track(self, track: Track) -> Track: r = self._spotipy.track(track.identifier) artists = [] for artist_obj in r["artists"]: artists.append(self.get_artist(artist_obj["id"])) track.artists = artists r = self._spotipy.audio_features([track.identifier]) track.key = r[0]["key"] track.mode = r[0]["mode"] track.time_signature = r[0]["time_signature"] track.acousticness = r[0]["acousticness"] track.danceability = r[0]["danceability"] track.energy = r[0]["energy"] track.instrumentalness = r[0]["instrumentalness"] track.liveness = r[0]["liveness"] track.loudness = r[0]["loudness"] track.speechiness = r[0]["speechiness"] track.valence = r[0]["valence"] track.tempo = r[0]["tempo"] return track
def get_track(id): track = sp.track(id) return Track(track['name'], track['artists'][0]['name'], track['id'], track['album']['images'][0]['url'], None, track['duration_ms'])