Created
July 30, 2020 04:00
-
-
Save stanlee321/232a6f0914c25c247dbd0517aecc57df to your computer and use it in GitHub Desktop.
HOW TO SEND IMAGE TO A REST API, FLASK
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # DEMO CLASS | |
| class PlotTimeSeries: | |
| def __init__(self): | |
| pass | |
| def _find_weekend_indices(self, datetime_array, weekend=5): | |
| """ | |
| Returns all indices of Saturdays & Sundays in a datetime array | |
| datetime_array(pandas) = pandas datetime array | |
| weekend(int) = assume weekend starts at day=5=Saturday | |
| """ | |
| #empty list to tore indeces | |
| indices = [] | |
| for i in range(len(datetime_array)): | |
| # get day of the week with Monday=0, Saturday=5, Sunday=6 | |
| if datetime_array[i].weekday() >= weekend: | |
| indices.append(i) | |
| return indices | |
| def _highlight_datetimes(self, indices, ax, df, facecolor='green', alpha_span=0.2): | |
| """ | |
| Highlights all weekends in an axes object | |
| indices(list) = list of Saturdays and Sundays indeces corresponding to dataframe | |
| ax(matplot) = pyplot object | |
| df(pandas) = pandas dataframe | |
| """ | |
| i = 0 | |
| #iterate over indeces | |
| while i < len(indices)-1: | |
| #highlight from i to i+1 | |
| ax.axvspan(df.index[indices[i]], | |
| df.index[indices[i] + 1], | |
| facecolor=facecolor, | |
| edgecolor='none', | |
| alpha=alpha_span) | |
| i += 1 | |
| def plot(self, df, dfs_dict, title="Comments Sentiment Timeline"): | |
| fig, axes = plt.subplots(nrows=1, ncols=1, sharex=True,figsize=(13,5)) | |
| for k_name, v_df in dfs_dict.items(): | |
| if k_name == "positive": | |
| marker = "^" | |
| color = "green" | |
| label = "Positive Sentiment" | |
| if k_name == "nevative": | |
| marker = "v" | |
| color = "red" | |
| label = "Negative Sentiment" | |
| if k_name == "neutral": | |
| marker = "o" | |
| color = "blue" | |
| label = "Neutral sentiment" | |
| if k_name == "mixed": | |
| marker = "|" | |
| color = "black" | |
| label = "Mixed sentiment" | |
| #draw all columns of dataframe | |
| axes.plot(v_df.index, v_df, marker=marker, color = color, label=label, alpha=.8) | |
| #find weekend indeces | |
| weekend_indices = self._find_weekend_indices(df.index, weekend=5) | |
| #highlight weekends | |
| self._highlight_datetimes(weekend_indices, axes, df, "green") | |
| #set title and y label | |
| axes.set_title(title, fontsize=12) | |
| axes.set_ylabel("Sentiment Counts") | |
| axes.legend() | |
| plt.tight_layout() | |
| #add xaxis gridlines | |
| axes.xaxis.grid(b=True, which='major', color='black', linestyle='--', alpha=1) | |
| # here is the trick save your figure into a bytes object and you can afterwards expose it via flas | |
| bytes_image = io.BytesIO() | |
| plt.savefig(bytes_image, format='png') | |
| bytes_image.seek(0) | |
| return bytes_image | |
| # INSTANCEs | |
| plot_timeline = PlotTimeSeries() | |
| sampler_df = SampleDataframe() | |
| # FLASK DEMO ENDPOINT | |
| # | |
| # | |
| # | |
| # | |
| # | |
| # | |
| # | |
| # | |
| @app.route("/sentiment_plot", methods=['GET']) | |
| def plot_sentiment(): | |
| if request.method == 'GET': | |
| print( request.args) | |
| fbPageId = request.args.get('fbPageId') | |
| limit = int(request.args.get('limit')) | |
| print(fbPageId) | |
| df = read_comments(client, fbPageId=fbPageId, limit = limit ) | |
| df_dt, positive, negative, neutral, mixed = sampler_df.get_df_datetime(df, time_split='2020-02-01 00:00:00') | |
| # return dict | |
| sampled_df = sampler_df.sample( positive, negative, neutral, mixed, sample_frec=f'{24*60}min') | |
| bytes_obj = plot_timeline.plot(df_dt, sampled_df) | |
| return send_file(bytes_obj, | |
| attachment_filename='plot.png', | |
| mimetype='image/png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment