Визуализируйте диаграмму внутри для l oop in flask front end - PullRequest
0 голосов
/ 08 марта 2020

Следующая функция визуализации визуализирует предоставленные ей пары функций. Пары объектов являются динамическими c, поэтому они сохраняются внутри для l oop. Это отлично работает на выходе терминала. Однако, может ли кто-нибудь помочь мне, как применить то же самое в flask ??

# Visualization of data
def visualization(dataframe,pair_list):
    try:
        for i in range(len(pair_list)):
                    x = pair_list[i][0]
                    y = pair_list[i][1]
                    plotdata = sns.pairplot(dataframe, x_vars = [x], y_vars = [y])
                    title = str(x) +' VS ' + str(y)
                    plotdata.fig.suptitle(title, y = 1)
                    plt.show()
    except:
        dataframe.plot()
def calling_visualization():
    visualization(dataframe_name, [(feature1, feature2), (feature3, feature4)])
    return 'visualization is done'

Я проверил другие ответы, которые, как я думал, могут помочь мне в переполнении стека, но ничего не помогло мне. Нужен совет специалистов по коду.

1 Ответ

1 голос
/ 08 марта 2020

Просто обновите fapp.py и index.html из последнего сообщения.

fapp.py:

import os
import shutil

from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
from flask import Flask, session
from fastai.vision import *

from io import StringIO
import base64
import io
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
import seaborn as sns

basedir = os.path.abspath(os.path.dirname(__file__))

UPLOAD_FOLDER = os.path.join('static', 'csv')

app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['csv','xls'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/')
def upload_form():
    return render_template('index.html')

@app.after_request
def add_header(response):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
    response.headers['Cache-Control'] = 'public, max-age=0'
    return response    

def build_plot(dataframe):
    # dataframe = pd.read_csv('/home/kriti/Desktop/Iris.csv')
    pair_list = [['PetalLengthCm', 'PetalWidthCm'], ['PetalWidthCm', 'Species']]
    img = io.BytesIO()

    fig, axs = plt.subplots(ncols=2, figsize=(12,5))
# 
    plotdata = []
    for i in range(2):
        x = pair_list[i][0]
        y = pair_list[i][1]
        print(x,y)
        plotdata = sns.scatterplot(data=dataframe, x=x, y=y, hue='Species', ax=axs[i])
        plt.tight_layout()
        # plotdata.legend()

    fig.savefig(img, format='png')
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue()).decode()
    return plot_url

    # return '<img src="data:image/png;base64,{}">'.format(plot_url)

@app.route('/', methods=['POST'])
def upload_file():

    # shutil.rmtree(UPLOAD_FOLDER)
    # os.mkdir(UPLOAD_FOLDER)

    d = request.form.to_dict()
    button_name = 'None'
    if (len(d)!=0):
        button_name = list(d.items())[-1][0]

    file = request.files['file']
    print("file:",file)
    if file.filename == '':
        flash('No file selected for uploading','red')
        # return redirect(request.url)
        return render_template('index.html', uploaded_csv=False)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        shutil.rmtree(UPLOAD_FOLDER)
        os.mkdir(UPLOAD_FOLDER)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('File successfully uploaded!', 'green')
        print(UPLOAD_FOLDER)
        print("==>",os.path.join(UPLOAD_FOLDER, sorted(os.listdir(app.config['UPLOAD_FOLDER']))[0]))
        csv_file = pd.read_csv(os.path.join(UPLOAD_FOLDER, sorted(os.listdir(app.config['UPLOAD_FOLDER']))[0]))
        csv_shape = csv_file.shape

        disp_div = 'block'
        plot_sns = build_plot(csv_file)

        # session['csv_file'] = csv_file
        return render_template('index.html', csv_shape=csv_shape, plot_graph=plot_sns, uploaded_csv = True)
        # return redirect('/')
    else:
        flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif', 'red')
        # return redirect(request.url)
        return render_template('index.html',uploaded_csv=False)


if __name__ == '__main__':
    app.run(debug=False, port=5006)

## For deploying the app use `app.run(debug=False, host="0.0.0.0", port=80)`

index. html:

<link rel="stylesheet" type="text/css" href="/static/css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="static/js/index.js"></script>
<script>
  $(document).ready(function(){
    $("#target").on('submit',function(){
        // alert("It works");
    });
  });
</script>
<!doctype html>

<html>
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>
<body>

    <form id="target" method="post"  enctype="multipart/form-data">
      <div name ="up" class="upload-btn-wrapper">
        <button name="upload" class="btn">Upload CSV File</button>
        <input type="file" id="file" value="go" name="file" onchange="$('#target').submit();"/>
      </div>
    </form>

    <p>
       {% with messages = get_flashed_messages(with_categories=true) %}
         {% if messages %}
          <div class=flashes>
          {% for category_color, message in messages %}
            <p class="error_text" style="color:{{ category_color }};width:500px;">{{ message }}</p>
          {% endfor %}
          </div>
         {% endif %}
       {% endwith %}
    </p>

    ===>{{ csv_shape }}

    {% if uploaded_csv %}
    <img src="data:image/png;base64, {{ plot_graph }}">

    {% endif %}
</body>
</html>

Перед загрузкой: enter image description here

После загрузки файла Iris.csv: enter image description here

Вы можете настроить код и написать собственную логику c, чтобы показать разные графики.

...