-1

I need some help, the situation is I m able to return the new CSV file but unable to return the plot graph to another page, and I did separate the return under different scenarios. Does anyone can point out what should I do to my code? or perhaps give me some tips, Thanks in advance!

app.py

@app.route('/transform', methods=["POST"])
def transform_view():
    if request.method == 'POST':
        if request.files['data_file']:
            f = request.files['data_file']
            if not f:
                return "No file"
    
            
            stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
            csv_input = csv.reader(stream)
            stream.seek(0)
            result = stream.read()
            df = pd.read_csv(StringIO(result), usecols=[1])
            
            #extract month value
            df2 = pd.read_csv(StringIO(result))
            matrix2 = df2[df2.columns[0]].to_numpy()
            list1 = matrix2.tolist()
             
            # load the model from disk
            model = load_model('model.h5')
            dataset = df.values
            dataset = dataset.astype('float32')
            scaler = MinMaxScaler(feature_range=(0, 1))
            dataset = scaler.fit_transform(dataset)
            look_back = 1
            dataset_look = create_dataset(dataset, look_back)
            dataset_look = np.reshape(dataset_look, (dataset_look.shape[0], 1, dataset_look.shape[1]))
            predict = model.predict(dataset_look)
            transform = scaler.inverse_transform(predict)
    
            X_FUTURE = 12
            transform = np.array([])
            last = dataset[-1]
            for i in range(X_FUTURE):
                curr_prediction = model.predict(np.array([last]).reshape(1, look_back, 1))
                last = np.concatenate([last[1:], curr_prediction.reshape(-1)])
                transform = np.concatenate([transform, curr_prediction[0]])
          
            transform = scaler.inverse_transform([transform])[0]
    
            dicts = []
            curr_date = pd.to_datetime(list1[-1])
            for i in range(X_FUTURE):
                curr_date = curr_date +  relativedelta(months=+1)
                dicts.append({'Predictions': transform[i], "Month": curr_date})
    
    
            new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
    
                          
        
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"
            return response
        
            labels = [
                        'JAN', 'FEB', 'MAR', 'APR',
                        'MAY', 'JUN', 'JUL', 'AUG',
                        'SEP', 'OCT', 'NOV', 'DEC'
                       ]
    
            values = [
                            967.67, 1190.89, 1079.75, 1349.19,
                            2328.91, 2504.28, 2873.83, 4764.87,
                            4349.29, 6458.30, 9907, 16297
                        ]
    
            colors = [
                            "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                            "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                            "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
            return redirect(url_for('line'))
    
    @app.route('/line')
    def line():
        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Bitcoin Monthly Price in USD', max=17000, labels=line_labels, values=line_values)
davidism
  • 121,510
  • 29
  • 395
  • 339

1 Answers1

0

you have to save it first to specific folder and then in frontend you can specify the image like that you pass it in url

from matplotlib import pyplot as plt
     
plt.savefig('path/plot.png')

or else you can use JavaScript to render graph to frontend you can use chart.js etc.

Bhavya Parikh
  • 3,304
  • 2
  • 9
  • 19
  • Hi @Bhavya, Thanks for commenting, I did try to add `plt.savefig('path/plot.png')` and it actually does not work, the problem is it dint return `render_template` at all, and can you demo like how to plot graph using chart.js as you said ? – user15452564 Mar 27 '21 at 13:12
  • Hey you can refer https://stackoverflow.com/questions/50728328/python-how-to-show-matplotlib-in-flask from here! and for chart.js you can go through official document as well as from stack overflow it self you can find your answer just try diff. methods. – Bhavya Parikh Mar 27 '21 at 13:32
  • I think `chartjs` also not work because it has to `return render_template` also, my problem is the second `return` cannot work at all – user15452564 Mar 27 '21 at 13:41
  • I have edited another version for you to see my problem, I cant return my `return redirect(url_for('line'))`, Please help ~ – user15452564 Mar 28 '21 at 05:37
  • your code is not as with proper indentation required in python see that first if condition please update the code – Bhavya Parikh Mar 28 '21 at 07:20
  • Updated ~ please have a look – user15452564 Mar 28 '21 at 09:07
  • last return statement is correct with indentation?? – Bhavya Parikh Mar 28 '21 at 11:27
  • yaya , I have try remove the entire predicted code and just leave the plot graph code, and its able to return the graph as normally – user15452564 Mar 28 '21 at 12:02
  • thats great!! now you can debug that prediction code or else use redirect also there if you want to. – Bhavya Parikh Mar 28 '21 at 12:05
  • but when I come to combine the prediction code and plot graph code together, It literally cannot return these 2 combined codes together. For the plot graph, actually I wanted to put the `predicted value` as Y-axis and `month` as X-axis. However, I have to solve the return problem which only I can adjust the x-axis and y-axis. The previous I mentioned when I remove the predicted code then the plot graph works, is I want to clarify that there is no problem with the plot graph code, The problem is when the `predicted code` and `plot graph` come together, Its only can return the `predicted code `. – user15452564 Mar 28 '21 at 13:10