[PYTHON] I made a face diagnosis AI for a female professional golfer ③

1.First of all

Last time I even created a learning model.

This time, we will create an actual web application using the learning model and deploy it.

The completed image looks like this スクリーンショット 2020-08-04 21.01.56.png

2. Created using Flask

main.py


#Import module
import cv2
import os
from flask import Flask, request, redirect, url_for, render_template, flash
from werkzeug.utils import secure_filename
from keras.models import Sequential, load_model
from keras.preprocessing import image
from PIL import Image
import tensorflow as tf
import numpy as np
from datetime import datetime
import face_recognition

#Player name
classes = ['Hinako Shibuno', 'Small celebration Sakura', 'Erika Hara']
num_classes = len(classes)
image_size = 64

#File to save the uploaded image
UPLOAD_FOLDER = "uploads/"
#Specify the extension that allows uploading
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

#Set up an instance of the Flask class
app = Flask(__name__)

#Define a function to check the extension of uploaded files
def allowed_file(filename):
    #First condition: in the variable filename'.'Does it contain the characters?
    #Second condition: variable filename.The character string after is ALLOWED_Which of the EXTENSIONS is applicable
    #In rsplit, the order of delimiter is "1" from the end of the character string. lower converts strings to lowercase
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


#Detect face(haarcascade)
def detect_face(img_path):
    image = face_recognition.load_image_file(img_path)
    faces = face_recognition.face_locations(image)
    if len(faces)>0:
        face_max = [(abs(faces[i][0]-faces[i][2])) * (abs(faces[i][1]-faces[i][3])) for i in range(len(faces))]
        top, right, bottom, left = faces[face_max.index(max(face_max))]#There is no problem because only one person is shown
        faceImage = image[top:bottom, left:right]
        final = Image.fromarray(faceImage)

        final = np.asarray(final.resize((image_size,image_size)))
        final = Image.fromarray(final)

        basename = datetime.now().strftime("%Y%m%d-%H%M%S")
        filepath = UPLOAD_FOLDER + basename+".png "
        final.save(filepath)

        return final
    else:
        return "Please enter a face image"

#Load the trained model
model = load_model('./golfer.h5', compile=False)

graph = tf.get_default_graph()

# app.route()Associate the URL specified in the function with./ http://127.0.0.1:5000/Specify the following URL
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    global graph
    # as_default()Specify the target graph with
    with graph.as_default():
        #If the HTTP method is POST
        if request.method == 'POST':
            #Does the POST request contain file data?
            if 'file' not in request.files:
                flash('File does not exist')
                #redirect is a function that redirects to the argument URL
                return redirect(request.url)
            file = request.files['file']
            if file.filename == '':
                flash('File does not exist')
                return redirect(request.url)
            
            #If the file exists and is in an allowed format
            if file and allowed_file(file.filename):
                #If there is a dangerous character string in the file name, disable it.
                filename = secure_filename(file.filename)
                #Save to uploads folder
                file.save(os.path.join(UPLOAD_FOLDER, filename))
                #Create a file path
                filepath = os.path.join(UPLOAD_FOLDER, filename)
                
                # #Read the received image and convert it to np format
                img = image.load_img(filepath, grayscale=False, target_size=(image_size,image_size))
                #Detect the face part
                img = detect_face(filepath)

                if type(img)!=str:
                    img = image.img_to_array(img)
                    data = np.array([img])
                    #Pass the transformed data to the model for prediction
                    result = model.predict(data)[0]
                    predicted = result.argmax()
                    pred_answer = "This female professional" + str(classes[predicted]) + "is"

                    return render_template("index.html",answer=pred_answer)
                else:
                    return render_template("index.html",answer=img)


        return render_template("index.html",answer="")

#Solve the problem that CSS is not reflected during web application development in Flask
@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)

def dated_url_for(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
        if filename:
            file_path = os.path.join(app.root_path,
                                 endpoint, filename)
            values['q'] = int(os.stat(file_path).st_mtime)
    return url_for(endpoint, **values)


if __name__ == "__main__":
    port = int(os.environ.get('PORT', 8080))
    app.run(host ='0.0.0.0',port = port)

3. index.html and stylesheet

index.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Female professional golfer judgment</title>
    <!-- <link rel="stylesheet" href="./static/stylesheet.css"> -->
    <link rel= "stylesheet" type= "text/css" 
            href= "{{ url_for('static',filename='stylesheet.css') }}">
</head>
<body>
    <header>   
        <a class="header-logo" href="#">Female professional golfer judgment</a>
    </header>

    <div class="main">    
        <h2>Identify the face in the image</h2>
        <p>Please send the image</p>
        <form method="POST" enctype="multipart/form-data">
            <input class="file_choose" type="file" name="file">
            <input class="btn" value="submit!" type="submit">
        </form>
        <div class="answer">{{answer}}</div>
    </div>

    <footer>
    </footer>
</body>
</html>

stylesheet.css


header {
    background-color: rgb(100, 81, 255);
    height: 100px;
    margin: -8px;
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
}

.header-logo {
    color: #fff;
    font-size: 30px;
    margin: auto;
}

.header_img {
    height: 25px;
    margin: 15px 25px;
}

.main {
    height: 370px;
}

h2 {
    color: #444444;
    margin: 90px 0px;
    text-align: center;
}

p {
    color: #444444;
    margin: 70px 0px 30px 0px;
    text-align: center;
}

.answer {
    margin: 70px 0px 30px 0px;
    text-align: center;
    font-size: 30px;
    color: blue;
    font-weight: bold;
}

form {
    text-align: center;
}

h2 {
    color: #444444;
    text-align: center;
}

footer {
    background-color: #F7F7F7;
    height: 110px;
    margin: -8px;
    position: relative;
}

.footer_img {
    height: 25px;
    margin: 15px 25px;
}

small {
    margin: 15px 25px;
    position: absolute;
    left: 0;
    bottom: 0;
}

4. File structure

The structure of the file is as follows スクリーンショット 2020-08-04 21.38.29.png

Index.html in the templates folder stylesheet.css in static folder

Please refer to this article for the remaining files [Complete version] Procedure for deploying API created with Flask to Heroku (Note)

5. Deploy to heroku

5-1. Register as a member on Heroku

Heroku Register here

5-2. Log in to Heroku

$ heroku login

5-3. Settings

Create New App ⇨ Enter your App name to register your country in United States. Go to the app page, go to Setteings and click Add build pack to add Python.

5-4. Execute the following from the terminal

git init

__ * Only the first time. If you do it twice, you will not be able to deploy successfully. __

heroku git:remote -a (app name)
git add .
git commit -m “(Write a message about what has changed)”
git push heroku master

__ Deployment is complete __

6. Check the web app

Check with the code below

heroku open

This completes the posting of the image application three times.

Recommended Posts

I made a face diagnosis AI for a female professional golfer ③
I tried to make a face diagnosis AI for a female professional golfer ①
I tried to make a face diagnosis AI for a female professional golfer ②
I made a dash docset for Holoviews
I made a library for actuarial science
I made a python dictionary file for Neocomplete
I made a spare2 cheaper algorithm for uWSGI
I made a useful tool for Digital Ocean
I made a downloader for word distributed expression
I made a peeping prevention product for telework.
I made a user management tool for Let's Chat
I made a window for Log output with Tkinter
I made a cleaning tool for Google Container Registry
[Valentine special project] I made a LINE compatibility diagnosis!
[Python] I made a classifier for irises [Machine learning]
[VSCode] I made a user snippet for Python print f-string
I made a Numer0n battle game in Java (I also made AI)
I made a resource monitor for Raspberry Pi with a spreadsheet
I made a python text
Made a command for FizzBuzz
I made a discord bot
Python> I made a test code for my own external file
I made a client / server CLI tool for WebSocket (like Netcat for WebSocket)
I made a lot of files for RDP connection with Python
I made a development environment for Django 3.0 with Docker, Docker-compose, Poetry
I made a Dir en gray face classifier using TensorFlow --(1) Introduction
I made a scaffolding tool for the Python web framework Bottle
I made a Dir en gray face classifier using TensorFlow-④ Face extraction
I made a Python wrapper library for docomo image recognition API.
I made a C ++ learning site
I touched PyAutoIt for a moment
I made a Line-bot using Python!
I made a CUI-based translation script (2)
I made a wikipedia gacha bot
I made a fortune with Python.
I made a daemon with Python
I made a Docker container to use JUMAN ++, KNP, python (for pyKNP).
[Updated Ver1.3.1] I made a data preprocessing library DataLiner for machine learning.
I made a Dir en gray face classifier using TensorFlow --⑩ Face classification test
I made a Dir en gray face classifier using TensorFlow --⑥ Learning program
I made a Dir en gray face classifier using TensorFlow --⑬ Playing (final)
I made a poop AI drill. Please do your summer vacation homework.
I made a Dir en gray face classifier using TensorFlow --- ⑧ Learning execution
I made a Dir en gray face classifier using TensorFlow --⑫ Web release
I made a Dir en gray face classifier using TensorFlow --- ⑦ Learning model
I made a Dir en gray face classifier using TensorFlow --② Environment construction
I made a payroll program in Python!
I touched "Orator" so I made a note
I made a character counter with Python
I made a conversation partner like Siri
I made a script to display emoji
I made a Hex map with Python
I made a life game with Numpy
I made a stamp generator with GAN
I made a browser automatic stamping tool.
After studying Python3, I made a Slackbot
I made a roguelike game with Python
Building a Python development environment for AI development
I made a simple blackjack with Python
I made a configuration file with Python
I made a WEB application with Django