机器学习烧瓶应用程序在Heroku中显示内部服务器错误

时间:2019-07-09 11:38:21

标签: python machine-learning heroku flask server

我在Heroku服务器中部署了我的应用程序,并加载了第一页,但是一旦我渲染以预测页面,就会出现内部服务器错误。

我已经检查了关于stackoverflow的几乎所有解决方案,但仍然无法解决,我认为代码中的静态地址/文件中存在一些错误,但无法解决。

Potato.py

function ToDo(){
  const [ input, setInput ] = React.useState('')
  const [ toDo, setToDo ] = React.useState([])
  const [ score, setScore ] = React.useState(0)
  const [ speed, setSpeed ] = React.useState(0)
  const [ urgency, setUrgency ] = React.useState(0)

  return(
    <div>
      <h2>List of things to do</h2>
      <input
          value={ input }
          onChange={ (e) => setInput( e.target.value ) }/>
      <button 
        onClick={ () => {
          setToDo( toDo.concat(input))
          setInput('')
          }}>Add
      </button>
      <ul>
        { toDo.map(( task, idTask ) => {
          return (
            <li 
              key={idTask}
              score={ speed + urgency }>
              {task}<br/>
              <select onChange={(e) => { setSpeed(Number(e.target.value)) }}>
                <option value={1}>slow</option>
                <option value={2}>medium</option>
                <option value={3}>fast</option>
              </select><br/>
              <select onChange={(e) => { setUrgency(Number(e.target.value)) }}>
                <option value={1}>non-urgent</option>
                <option value={3}>urgent</option>
              </select>
              <span 
                onClick={ 
                  (index) => {
                    const newTodos = [...toDo]
                    newTodos.splice(index, 1);
                    setToDo( newTodos)
                  }}>
                [-------]
              </span>
            </li>
            )
          })
         }
      </ul>
      <button onClick={ 
          () => { 
            const sortMe = [...toDo].sort((a, b) => b - a)
            setToDo( sortMe )
          }}>Sort!</button>
    </div>
    )
  }

ReactDOM.render(<ToDo/>, document.getElementById('app'));

Label_image.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')

马铃薯预测

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> 

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

这是到应用程序的链接,只要您提交图像就给服务器报错,只要我从终端运行,它就可以在localhost上正常工作。

我需要正确部署它。请帮助我。

我的应用的日志

<!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>

0 个答案:

没有答案