AWS EC2でPython Webアプリケーションを公開する

AWS EC2を使用してPython Webアプリケーションを公開する方法について説明します。この記事は、PythonとFlaskを使用してWebアプリケーションを作成し、それをAWSで公開する方法について詳しく説明します。

前提条件

この記事を読むための前提条件は以下の通りです:
– Webアプリの実装方法やそれぞれのコードの詳細な解説は省略します。
– AWS初心者なので、アーキテクチャがベストプラクティスではないことをご了承ください。

アプリのディレクトリ構成と一部コードの紹介

実際のアプリ構成は以下のようになっています。

Flask
|_ app.py
|_ cnn_model.py
|_ photos-newmodel-light.hdf5
|_ templates
   |_ flask_api_index.html(メインのhtmlファイル)
   |_ result.html(結果を表示するページhtmlファイル)
|_ static
   |_ css
      |_main.css
   |_ images(htmlファイルに挿入する画像)
      |_xxxx.jpg

実際のコード (一部)

以下に app.pycnn_model.py の一部を示します。

# app.py
import numpy as np
from PIL import Image
import cnn_model
from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route('/result', methods=['POST'])
def result():
    body_list = ["筋肉型","標準型","痩せ型","肥満型"]
    try :
        if request.files['image']:
            img_file = request.files['image']
            temp_img = Image.open(request.files['image'])
            temp_img = temp_img.convert("RGB")
            temp_img = temp_img.resize((64,64))
            temp_img = np.asarray(temp_img)
            im_rows = 64
            im_cols = 64
            im_color = 3
            in_shape = (im_rows,im_cols,im_color)
            nb_classes = 4
            img_array = temp_img.reshape(-1,im_rows,im_cols,im_color)
            img_array = img_array / 255
            model = cnn_model.get_model(in_shape,nb_classes)
            model.load_weights("photos-newmodel-light.hdf5")
            predict = model.predict([img_array])[0]
            index = predict.argmax()
            body_shape = body_list[index]
            body_score = 90*predict[0]+70*predict[1]+40*predict[2]+40*predict[3]
            body_score = int(body_score)
            return render_template('./result.html', title='結果',body_score=body_score,body_shape=body_shape,img_file=img_file)
    except:
        return render_template('./flask_api_index.html')

if __name__ == '__main__':
    app.debug = True
    app.run(host='localhost', port=8888)
# cnn_model.py
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import RMSprop

def def_model(in_shape, nb_classes):
    model = Sequential()
    model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', input_shape=in_shape))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Conv2D(128, (3, 3), activation='relu'))
    model.add(Conv2D(128, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(1024, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes, activation='softmax'))
    return model
この記事は、PythonとFlaskを使用して作成したWebアプリケーションをAWSで公開する方法について詳しく説明します。自作のWebアプリケーションをAWSでWeb上に公開したい人にとっては特に参考になると思います。

AWSでWebアプリを公開する方法(Python+Flask) – Qiita

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です