Приложение "Колба машинного обучения", показывающее внутреннюю ошибку сервера в Heroku - PullRequest
0 голосов
/ 09 июля 2019

Я развернул свое приложение на сервере Heroku, и первая страница загрузилась, но как только я рендерился для предсказания страницы, это выдает внутреннюю ошибку сервера.

Я проверил почти все решения на stackoverflow и все еще могуЯ не могу решить эту проблему, я думаю, что в моем коде есть какая-то ошибка в статическом адресе / файле, но я не могу ее решить.

Potato.py

from flask import Flask, redirect, url_for, request,render_template
import numpy as np
import label_image as m1
from PIL import Image
import time
import os
app = Flask(__name__,static_url_path='/static')

@app.route('/')
def log():
   return render_template('PotatoPrediction.html')

@app.route('/try',methods = ['GET', 'POST'])
def again():
   return render_template('PotatoPrediction.html')

@app.route('/predict',methods = ['GET', 'POST'])
def Prediction():
    data1 = request.files['image1']

    print(data1)
    image = "a" + str(time.time()) + ".jpg"
    img = Image.open(data1)
    path = 'static/' + image
    for filename in os.listdir('static/'):
        if filename.startswith('a'):  # not to remove other images
            os.remove('static/' + filename)
    img.save(path,'JPEG')
    b0,b1,b2 = m1.predict(image)
    b0 = b0*100
    b1 = b1*100
    b2 = b2*100
    data = 'Early_Blight_Percentage' +'     ' + str(b0) +'\n'+'Late_Blight_Percentage'+'      ' + str(b1) + '\n'+ 'Healthy_Leaves_Percentage'+'     ' + str(b2) +'\n'   
    return render_template('prediction.html',a0=b0,a1=b1,a2=b2,image=image)


if __name__ == '__main__':
   app.run(debug = True,host ='0.0.0.0')

Label_image.py

def load_graph(model_file):
  graph = tf.Graph()
  graph_def = tf.GraphDef()

  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())
  with graph.as_default():
    tf.import_graph_def(graph_def)

  return graph

def read_tensor_from_image_file(file_name, input_height=299, input_width=299,
                input_mean=0, input_std=255):
  input_name = "file_reader"
  output_name = "normalized"
  file_reader = tf.read_file(file_name, input_name)
  if file_name.endswith(".png"):
    image_reader = tf.image.decode_png(file_reader, channels = 3,
                                       name='png_reader')
  elif file_name.endswith(".gif"):
    image_reader = tf.squeeze(tf.image.decode_gif(file_reader,
                                                  name='gif_reader'))
  elif file_name.endswith(".bmp"):
    image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
  else:
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
                                        name='jpeg_reader')
  float_caster = tf.cast(image_reader, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0)
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)

  return result

def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    label.append(l.rstrip())
  return label

def predict(image):
  file_name = "static/" + image
  model_file = "model/my_model.pb"
  label_file = "model/labels.txt"
  input_height = 224
  input_width = 224
  input_mean = 128
  input_std = 128
  input_layer = ""
  #input_layer = "zero_padding2d_1_input"
  #output_layer = "dense_2/Softmax"

  graph = load_graph(model_file)
  t = read_tensor_from_image_file(file_name,
                                  input_height=input_height,
                                  input_width=input_width,
                                  input_mean=input_mean,
                                  input_std=input_std)

  input_name = "import/" + input_layer
  output_name = "import/" + output_layer
  input_operation = graph.get_operation_by_name(input_name)
  output_operation = graph.get_operation_by_name(output_name)

  with tf.Session(graph=graph) as sess:
    start = time.time()
    results = sess.run(output_operation.outputs[0],{input_operation.outputs[0]: t})
    end=time.time()
  results = np.squeeze(results)

  top_k = results.argsort()[-5:][::-1]
  labels = load_labels(label_file)

  return results[0],results[1],results[2]

Картофельный прогноз

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body style = "background-color:lightblue">

<h1 align="center">Potato Disease Detection</h1>
<form action = "/predict" method = "post" enctype="multipart/form-data"  >
    <div>
    <label style="margin-left:40%;font-size:25px">Browse Your Image:</label><br/>
    <input style="margin-left:40%;font-size:25px" type = "file" name = "image1" accept= ".jpg,.png,jpeg,"/>
    </div><br/>
    <input style="margin-left:40%;font-size:25px" type = "submit" value = "submit" />
</form>
</body>
</html> 

Прогноз

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body style = "background-color:lightblue">

<h1 align="center">Potato Plant Disease Detection </h1>
<div align="center">
<h4>Input Image</h4>
<img src="{{url_for('static', filename=image)}}" height="500px" width = "500px" />
<h4> Early Blight Percentage :- {{a0}} </h4>
<h4> Late Blight Percentage :- {{a1}} </h4>
<h4> Healthy_Leaves Percentage :- {{a2}} </h4>
<form action = "/try" method = "post">
<input style="margin-left:10%;font-size:25px" type = "submit" value = "Try Another Image" />
</form>
</div>
</body>

https://potato -image-classifier.herokuapp.com /

это ссылка на приложение, и как только вы отправляете образ, он выдает ошибку сервера, он отлично работает на localhost, пока я запускаю из терминала.

Мне нужно правильно его развернуть,Помогите мне, пожалуйста.

журналы для моего приложения

2019-07-09T11:28:23.492083+00:00 app[web.1]:     rv = self.dispatch_request()
2019-07-09T11:28:23.492085+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1818, in dispatch_request
2019-07-09T11:28:23.492087+00:00 app[web.1]:     return self.view_functions[rule.endpoint](**req.view_args)
2019-07-09T11:28:23.492090+00:00 app[web.1]:   File "/app/potato.py", line 32, in Prediction
2019-07-09T11:28:23.492092+00:00 app[web.1]:     b0,b1,b2 = m1.predict(image)
2019-07-09T11:28:23.492094+00:00 app[web.1]:   File "/app/label_image.py", line 66, in predict
2019-07-09T11:28:23.492095+00:00 app[web.1]:     graph = load_graph(model_file)
2019-07-09T11:28:23.492098+00:00 app[web.1]:   File "/app/label_image.py", line 17, in load_graph
2019-07-09T11:28:23.492099+00:00 app[web.1]:     graph_def.ParseFromString(f.read())
2019-07-09T11:28:23.492101+00:00 app[web.1]: google.protobuf.message.DecodeError: Error parsing message
2019-07-09T11:28:42.550576+00:00 heroku[router]: at=info method=GET path="/predict" host=potato-image-classifier.herokuapp.com request_id=681def10-d77d-4efb-9806-538a87a3be2e fwd="14.139.34.2" dyno=web.1 connect=1ms service=4ms status=400 bytes=347 protocol=https
2019-07-09T11:29:06.672292+00:00 app[web.1]: <FileStorage: '1 (41).jpg' ('image/jpeg')>
2019-07-09T11:29:07.748293+00:00 app[web.1]: E0709 11:29:07.747753 139833447112832 app.py:1780] Exception on /predict [POST]
2019-07-09T11:29:07.748306+00:00 app[web.1]: Traceback (most recent call last):
2019-07-09T11:29:07.748309+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 2311, in wsgi_app
2019-07-09T11:29:07.748312+00:00 app[web.1]:     response = self.full_dispatch_request()
2019-07-09T11:29:07.748319+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1834, in full_dispatch_request
2019-07-09T11:29:07.748321+00:00 app[web.1]:     rv = self.handle_user_exception(e)
2019-07-09T11:29:07.748323+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1737, in handle_user_exception
2019-07-09T11:29:07.748325+00:00 app[web.1]:     reraise(exc_type, exc_value, tb)
2019-07-09T11:29:07.748327+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 36, in reraise
2019-07-09T11:29:07.748330+00:00 app[web.1]:     raise value
2019-07-09T11:29:07.748332+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1832, in full_dispatch_request
2019-07-09T11:29:07.748334+00:00 app[web.1]:     rv = self.dispatch_request()
2019-07-09T11:29:07.748336+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1818, in dispatch_request
2019-07-09T11:29:07.748339+00:00 app[web.1]:     return self.view_functions[rule.endpoint](**req.view_args)
2019-07-09T11:29:07.748341+00:00 app[web.1]:   File "/app/potato.py", line 32, in Prediction
2019-07-09T11:29:07.748343+00:00 app[web.1]:     b0,b1,b2 = m1.predict(image)
2019-07-09T11:29:07.748345+00:00 app[web.1]:   File "/app/label_image.py", line 66, in predict
2019-07-09T11:29:07.748347+00:00 app[web.1]:     graph = load_graph(model_file)
2019-07-09T11:29:07.748350+00:00 app[web.1]:   File "/app/label_image.py", line 17, in load_graph
2019-07-09T11:29:07.748352+00:00 app[web.1]:     graph_def.ParseFromString(f.read())
2019-07-09T11:29:07.748360+00:00 app[web.1]: google.protobuf.message.DecodeError: Error parsing message
2019-07-09T11:29:07.750486+00:00 heroku[router]: at=info method=POST path="/predict" host=potato-image-classifier.herokuapp.com request_id=dd1018ec-340e-45f3-98de-75f2606289e3 fwd="14.139.34.2" dyno=web.1 connect=1ms service=5630ms status=500 bytes=455 protocol=https
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...