Google App Engine: не удалось загрузить ресурсы с помощью keras / tenorflow / flask - PullRequest
1 голос
/ 14 апреля 2020

В настоящее время я занимаюсь разработкой веб-приложения для машинного обучения с использованием tenorflow / keras и flask. Для развертывания я использую Google App Engine (GAE).

Локально я могу запустить свое приложение, получить некоторые данные через пользовательский интерфейс и отобразить прогноз, используя мои загруженные модели (их четыре, все файлы .h5)

Я могу развернуть его в GAE без ошибок, но когда я вхожу в браузер по ссылке, я получаю сообщение об ошибке «502 bad gateway», а когда я проверяю браузер (Chrome), я вижу три сообщения об ошибке «Не удалось загрузить ресурс».

Я новичок в веб-разработке, поэтому я не до конца понимаю, в чем и где проблема. Нужно ли объявлять мои модели в файле .yaml или загружать их специально?

Мой файл .yaml:

env: flex
runtime: python
runtime_config:
    python_version: 3

Мой файл main.py:

import pandas as pd
import tensorflow as tf
from keras.models import load_model
from keras.backend import set_session
from utils import instagram_scraper
from utils import image_preprocessing
from utils import label_encoding
from utils import overall_class_label
from sklearn.preprocessing import LabelEncoder

global sess
global graph
sess = tf.compat.v1.Session()
graph = tf.compat.v1.get_default_graph()
tf.compat.v1.keras.backend.set_session(sess) 
num_attributes = 4
model = [[] for i in range(num_attributes)]
model[0] = load_model('./model/savemodels/glamorous_model.h5')
model[1] = load_model('./model/savemodels/rugged_model.h5')
model[2] = load_model('./model/savemodels/fun_model.h5')
model[3] = load_model('./model/savemodels/healthy_model.h5')

app = Flask(__name__)


def data_collection(brandname):
    url = 'https://www.instagram.com/'+brandname+'/?hl=en'
    scraper = instagram_scraper.InstagramScraper()
    official_images = scraper.profile_page_posts(url)
    return official_images


def data_preprocessing(official_images):
    preprocessed_data = image_preprocessing.preprocessing(official_images)
    return preprocessed_data


def make_prediction(preprocessed_data):
    X_test = preprocessed_data

    with graph.tf.compat.v1.as_default():
        tf.compat.v1.keras.backend.set_session(sess)
        y_pred = [[] for i in range(num_attributes)]
        for i in range(num_attributes):
            y_pred[i] = model[i].predict(X_test)
        y_pred_label = overall_class_label.give_ovr_class_label_output(y_pred)

    # convert from encoded label to label name
    # encoded label
    y_pred_lst = y_pred_label.tolist()
    # map back to original label name
    code2label = {0: 'glamorous', 1: 'rugged', 2: 'fun', 3: 'healthy'}
    y_pred_lbnm = map(code2label.get, y_pred_lst)
    y_pred_lbnm = list(y_pred_lbnm)
    prediction = pd.Series(y_pred_lbnm).value_counts()
    return prediction


@app.route("/", methods=["POST", "GET"])
def index():
    if request.method == "POST":
        brandname = request.form["brandname"]
        return redirect(url_for("predict", brandname=brandname))
    else:
        return render_template("index.html")


@app.route("/predict/<brandname>", methods=["POST", "GET"])
def predict(brandname):
    official_images = data_collection(brandname)
    preprocessed_data = data_preprocessing(official_images)
    prediction = make_prediction(preprocessed_data)
    return render_template("predict.html", prediction=prediction)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, debug=True)

Структура моего приложения:

parent
 --model
   --savemodels
     fun_model.h5
     glamorous_model.h5
     healthy_model.h5
     rugged_model.h5
 --static
     style.css
 --templates
     index.html
     predict.html
 --utils
     image_preprocessing.py
     instagram_scraper.py
     label_encoding.py
     overall_class_label.py
 app.yaml
 main.py
 requirements.txt

Любая помощь очень ценится, спасибо! Всего наилучшего, снежная

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...