Thursday, February 13, 2020

Flask & Model Connection

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.xception import (
    Xception, preprocess_input, decode_predictions)
from tensorflow.keras.models import load_model
UPLOAD_FOLDER = '.'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
# Refactor above steps into reusable function
def predict(image_path):
    # Load the Xception model
    # https://keras.io/applications/#xception
    model = load_model('xception.h5')
    # Default Image Size for Xception
    image_size = (299, 299)
    """Use Xception to label image"""
    img = image.load_img(image_path, target_size=image_size)
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    
    predictions = model.predict(x)
    #plt.imshow(img)
    
    result = decode_predictions(predictions, top=3)[0]
    print('Predicted:', result)
    return result
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def classify(filename):
    result = predict(filename)
    #os.remove(filename)
    strTable = '<table>'
    for r in result:
        strTable += '<tr>'
        strTable += '<td>' + str(r[1]) + '</td>'
        strTable += '<td>' + str(r[2]) + '</td>'
        strTable += '</tr>'
    strTable += '</table>'
    strHTML = f'Successfully uploaded {filename} <BR><BR> Prediction results:<BR> {strTable}'
    os.remove(filename)
    return strHTML
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #return redirect(url_for('classify',filename=filename))
            return classify(filename)
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
if __name__ == "__main__":
    
    app.run(debug=True)

No comments:

Post a Comment

All about CSS

From book HTML & CSS - Design and Build Websites - Jon Duckett CSS works by associating rules with HTML elements. These rules govern how...