def profile(): """ Shows overview of user's Spotfy profile """ # Get profile data my_profile_data = helpers.get_my_profile(session["authorization_header"]) # Get playlists data my_playlists_data = helpers.get_my_playlists( session["authorization_header"]) # Get saved tracks data saved_tracks_data = helpers.get_saved_tracks( session["authorization_header"]) # Get followed artists data followed_artists_data = helpers.get_followed_artists( session["authorization_header"]) # Get recently played data recently_played_data = helpers.recently_played_tracks( session["authorization_header"]) # Get track popularity tracks = [] for track in recently_played_data["items"]: track_id = track["track"]["id"] tracks.append( helpers.get_track(session["authorization_header"], track_id)) return render_template("profile.html", user=my_profile_data, playlists=my_playlists_data, saved_tracks=saved_tracks_data, followed_artists=followed_artists_data, recently_played=recently_played_data["items"], tracks=tracks)
def get_format(track_info=None): """Set json logging format :param track_info: dict with external information on run :return: Json string with logging format """ new_format = '{"datetime": "%(asctime)s",' \ '"name": "%(name)s",' \ '"level": "%(levelname)s",' \ '"log": %(message)s,' new_format += '"track": %s}' % ( json.dumps(track_info if track_info else helpers.get_track())) return new_format
def __init__(self, _reponame, _repo_url, _repo_branch, _repo_path, _scratch_folder, _manifest, _dryrun=False): """Repo Manager init :param _reponame: Name of repo :param _repo_url: URL of repo :param _repo_branch: Repo branch :param _repo_path: Local location of repo :param _scratch_folder: Abs path of scratch folder :param _manifest: Manifest to monitor and parse :param _dryrun: False - Run function without any git interaction """ self.paths = { 'scratch_path': _scratch_folder, 'absolute_path': os.path.join(_scratch_folder, _repo_path) } self.paths['repo_path'] = os.path.join(self.paths['absolute_path'], _reponame) self.paths['manifest_repo'] = os.path.join(self.paths['repo_path'], consts.CONFIG_PATH_NAME, _manifest) self.manifest = _manifest self.url = _repo_url self.branch = _repo_branch self.track = helpers.get_track() self.project = "" self.reponame = "" self.prev_commit = "" self.dryrun = _dryrun repo_split = _repo_url.split('/') if len(repo_split) > 1: self.project = repo_split[-2] self.reponame = repo_split[-1].split('.')[0]
def track_analytics(track_id): """ Route including usage of graphs created with matplotlib # Main idea: # - Don't create static image files to prevent mass build-up of .jpg, .png files in directory # - Instead use BytesIO to hold binary stream of data in memory # - Follow by extracting bytes from object into plot file and embed in HTML directly """ track_features = helpers.get_features(session["authorization_header"], track_id) track_info = helpers.get_track(session["authorization_header"], track_id) required_data = [ "acousticness", "danceability", "energy", "instrumentalness", "liveness", "speechiness", "valence" ] feature_data = {} for feature, data in track_features.items(): if feature in required_data: feature_data[feature] = data # Sort data to match in polar axis bar chart labels = [] label_data = [] for key, value in feature_data.items(): labels.append(key) label_data.append(value) # Generate figure without using pyplot (to prevent main thread error) fig = Figure() # Define number of bars (on polar axis) N = len(required_data) # Define x coordinates of the bars theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False) # Create an array object satisfying the specified requirements height = np.array(label_data) # Define colors of bar chart colors = [ "#1DB954", "#39C269", "#56CB7F", "#72D394", "#8EDCAA", "#AAE5BF", "#C7EDD4" ] # Add subplot to figure object ax = fig.add_subplot(111, projection='polar') ax.set_facecolor("#757575") # Set figure title and design title = "Audio Features" ax.set_title(title, fontfamily='sans-serif', fontsize='xx-large', fontweight='bold', pad=15.0, color='#ffffff') # Edit radius labels ax.set_rlim(0.0, 1) ax.set_rlabel_position(+15) ax.tick_params(axis='both', colors='#ffffff', pad=22, labelsize='large') # Add bar chart ax.bar(x=theta, height=height, width=0.8, bottom=0.0, alpha=0.7, tick_label=labels, color=colors, edgecolor="black") # Ensure labels don't go out of Figure view fig.tight_layout() # Save to temporary buffer buf = BytesIO() fig.savefig(buf, format='png', facecolor='#757575') plot_url_features = base64.b64encode(buf.getbuffer()).decode() # b64encode(): Encodes the bytes-like object using Base64 and returns the encoded bytes # getvalue(): Returns bytes containing the entire contents of the buffer # decode(): Decodes the contents of the binary input file and write the resulting binary data to the output file # Image can be shown with following syntax: data:[<mime type>][;charset=<charset>][;base64],<encoded data> # eg. <img src="data:image/png;base64,{}">'.format(plot_url) # Visualize track analysis data track_analysis = helpers.get_analysis(session["authorization_header"], track_id) segments = [] loudness = [] for segment in track_analysis["segments"]: segments.append(segment["start"]) loudness.append(segment["loudness_start"]) # Make a new figure to display track loudness fig2 = Figure(figsize=(15, 4)) # Create plots ax1 = fig2.subplots() ax1.plot(segments, loudness, color="#1DB954", linewidth=1.1) ax1.set_facecolor("#757575") # Configure x- and y-limit for the graph ax1.set_xlim(left=0.0, right=track_features["duration_ms"] / 1000) ax1.set_ylim(bottom=-60.0, top=0.0) # Configure ticks and labels ax1.set_xticks( np.linspace(0.0, track_features["duration_ms"] / 1000, endpoint=False)) ax1.set_yticklabels([]) ax1.tick_params(direction="inout", labelrotation=45.0, pad=-0.5) ax1.set(xlabel="Time (s)", ylabel="Loudness", title="Track loudness") # Draw grid lines ax1.grid() # Ensure xlabel doesn't go out of Figure view fig2.tight_layout() # Save to temporary buffer buf2 = BytesIO() fig2.savefig(buf2, format='png') plot_url_loudness = base64.b64encode(buf2.getbuffer()).decode() return render_template("track-analytics.html", track_features=plot_url_features, track_features_data=feature_data, tempo=int(track_features["tempo"]), key=track_features["key"], track_loudness=plot_url_loudness, track_info=track_info)