无法运行Flask服务器。

huangapple go评论55阅读模式
英文:

Can't run a Flask server

问题

我正试图按照这个在线教程创建一个Flask/Tensorflow/React应用程序,但是我在尝试运行Flask服务器时遇到了一些问题。

Flask版本: 2.2.3

Python版本: 3.10.0

我已经在网上搜索了一些解决方案,但是没有尝试过的方法有效。以下是我尝试运行应用程序的方式:

无法运行Flask服务器。

不确定这是否有助于找到解决方案,但如果有的话,这是我的app.py文件:

import os
import numpy as np
from flask import Flask, request
from flask_cors import CORS
from keras.models import load_model
from PIL import Image, ImageOps

app = Flask(__name__)
CORS(app)

@app.route('/upload', methods=['POST'])
def upload():
    np.set_printoptions(suppress=True)

    model = load_model("keras_Model.h5", compile=False)
    class_names = open("labels.txt", "r").readlines()

    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
    image = Image.open("<IMAGE_PATH>").convert("RGB")

    size = (224, 224)
    image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)

    image_array = np.asarray(image)
    normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1

    data[0] = normalized_image_array

    prediction = model.predict(data)
    index = np.argmax(prediction)
    class_name = class_names[index]
    confidence_score = prediction[0][index]

    print("Class:", class_name[2:], end="")
    print("Confidence Score:", confidence_score)

有谁知道我在这里做错了什么,有没有明显的问题导致了这个问题?如果有其他有用的信息我可以添加,请告诉我,谢谢。

编辑:

我已经在我的代码末尾添加了执行部分:

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=5000)

现在,运行'python -m flask run'尝试运行应用程序,所以原始问题得到了回答。不过,现在似乎有一个后续问题,它不断返回这个错误。我使用'pip3 install tensorflow'安装了tensorflow,并且安装成功,但然后它总是返回模块未找到的错误。Tensorflow在pip freeze的包列表中似乎没有出现,我现在正在寻找原因。

编辑2:我的问题被标记为已经在这里回答了,尽管我很难理解为什么,因为那个帖子根本没有提到'flask run'或尝试运行Flask应用程序时可能出现问题的原因,以及在应用程序无法运行时该怎么办,而这就是这个问题的关键点。那个帖子只是讨论了运行Flask应用程序的“正确”方式,而不是如何运行一个根本无法运行的应用程序。

英文:

I'm trying to follow this online tutorial for a Flask/Tensorflow/React application, but I'm having some trouble at the end now trying to run the Flask server.

Flask version: 2.2.3

Python version: 3.10.0

I've search online for solutions, but nothing I've tried has worked. Here's the ways I've tried to run the application:

无法运行Flask服务器。

Not sure if this could be helpful in coming to a solution, but incase it is, here's my app.py file:

import os

import numpy as np
from flask import Flask, request
from flask_cors import CORS
from keras.models import load_model
from PIL import Image, ImageOps

app = Flask(__name__) # new
CORS(app) # new

@app.route(&#39;/upload&#39;, methods=[&#39;POST&#39;])
def upload():
    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)

    # Load the model
    model = load_model(&quot;keras_Model.h5&quot;, compile=False)

    # Load the labels
    class_names = open(&quot;labels.txt&quot;, &quot;r&quot;).readlines()

    # Create the array of the right shape to feed into the keras model
    # The &#39;length&#39; or number of images you can put into the array is
    # determined by the first position in the shape tuple, in this case 1
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

    # Replace this with the path to your image
    image = Image.open(&quot;&lt;IMAGE_PATH&gt;&quot;).convert(&quot;RGB&quot;)

    # resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)

    # turn the image into a numpy array
    image_array = np.asarray(image)

    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1

    # Load the image into the array
    data[0] = normalized_image_array

    # Predicts the model
    prediction = model.predict(data)
    index = np.argmax(prediction)
    class_name = class_names[index]
    confidence_score = prediction[0][index]

    # Print prediction and confidence score
    print(&quot;Class:&quot;, class_name[2:], end=&quot;&quot;)
    print(&quot;Confidence Score:&quot;, confidence_score)

Does anyone know what I'm doing wrong here, is there maybe something obvious I'm missing that's causing the problem? If there's any other info I can add that may be helpful, please let me know, thanks.

Edit:

I've added the execution section at the end of my code:

if __name__ == &#39;__main__&#39;:
    app.run(host=&quot;127.0.0.1&quot;, port=5000)

And now 'python -m flask run' does attempt to run the app, so the original post question is answered. There does seem to be a subsequent problem now though, it constantly returns this error. I installed tensorflow using 'pip3 install tensorflow' and it does install successfully, but then it always returns with the module not found error. Tensorflow doesn't appear in pip freeze package list, am now looking to see how/why this is.

Edit2: My question was flagged as already answered here, though I'm struggling to see how, as that post has absolutely no mention at all on why 'flask run' or any way of trying to run a flask app might not work, or what to do when it doesn't, which is what this question is. That post is simply discussing the 'correct' way to run a flask app, not how to run one at all when it's not running.

答案1

得分: 0

如果您不想使用 flask 命令,您需要添加代码来运行开发服务器。

if __name__ == "__main__":
    app.run()
英文:

If you don't want to use the flask command, you need to add code to run the development server instead.

if __name__ == &quot;__main__&quot;:
    app.run()

huangapple
  • 本文由 发表于 2023年2月20日 00:07:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定