我正在开发一个 Flask 应用程序来部署我的 NLP 模型,稍后该模型将链接到前端和后端。这是我的flask_app.py代码:
from flask import Flask, render_template, request, jsonify
import joblib
import pandas as pd
from sentence_transformers import SentenceTransformer
app = Flask(__name__)
# Load the model from .joblib file
with open("API/NearestNeighbors_clf.joblib", "rb") as file:
loaded_model = joblib.load(file)
# load the database from .csv file
df = pd.read_csv("DL/database_Leo.csv")
# define embedding model based on all-MiniLM-L6-v2
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
model.max_seq_length = 512 # Change the length to 512
@app.route("/")
def index():
return render_template("index.html")
@app.route("/predict", methods=["POST"])
def predict():
# extract input data from the request
star_rating = float(request.form["star_rating"])
price = float(request.form["price"])
user_input_str = str(request.form["user_input_str"])
# create embeddings for user input
user_input_emb = model.encode(user_input_str).reshape(1,-1)
# make prediction based on user input
distances, indices = loaded_model.kneighbors(user_input_emb)
# flatten indices array to use as index in dataframe
indices = indices.flatten()
# get ID's to return
recs = df.iloc[indices]["reference"]
return jsonify({"recommendations" : recs})
if __name__ == "__main__":
app.run(debug=True)
我分别测试了导入和模型,一切都工作得很好,但是当我运行整个文件时,它会抛出以下错误:
Traceback (most recent call last):
File "C:\Users\phyla\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3460, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-2-79851fa29ea7>", line 1, in <module>
runfile('C:\\Users\\phyla\\Documents\\Github\\ss23-drop-in-to-berlin\\API\\flask_app.py', wdir='C:\\Users\\phyla\\Documents\\Github\\ss23-drop-in-to-berlin\\API')
File "C:\Program Files\JetBrains\PyCharm 2023.1.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2023.1.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\phyla\Documents\Github\ss23-drop-in-to-berlin\API\flask_app.py", line 4, in <module>
from sentence_transformers import SentenceTransformer
File "C:\Program Files\JetBrains\PyCharm 2023.1.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'sentence_transformers'
´´´
I'm not sure if it has to do with the way that I installed sentence_transformers, but it does show up in my conda environment (which is active) and as I said everything works until I try to run it as flask app.
Thanks for your time!
我自己设法解决了这个问题。我认为这可能对其他人有帮助,所以我将答案留在这里:
通过终端命令运行 Flask 应用程序:
flask --app flask_app.py run
是我丢失的钥匙。