emission_detect_model/run.py

53 lines
1.9 KiB
Python
Raw Normal View History

2023-06-26 13:49:10 +08:00
# -*-coding:utf-8-*-
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import json
from flask import Flask, request, make_response
from logzero import logger
2023-06-28 12:34:57 +08:00
import pandas as pd
2023-06-26 13:49:10 +08:00
current_path = os.path.dirname(os.path.abspath(__file__)) # for local
# current_path = "/app" # for docker
logger.info(f"{current_path}")
2023-06-28 12:34:57 +08:00
from models.lgb_predict import load_config, load_history_data, load_lgb_model, predict_df
2023-06-26 13:49:10 +08:00
lgb_model = load_lgb_model(model_path=f"{current_path}/model_files/hour_best_model.txt")
object_cols = load_config(f"{current_path}/config/object_cols.json")
history_data = load_history_data(data_path=f"{current_path}/data/data_sample.csv")
emission_factors = load_config(f"{current_path}/config/emission_factor.json")
2023-06-28 12:34:57 +08:00
col_dict =load_config(f"{current_path}/config/columns_dict.json")
2023-06-26 13:49:10 +08:00
app = Flask(__name__)
@app.route('/emission/', methods=["POST"])
def run_case_check():
resp_info = dict()
if request.method == "POST":
data = request.json.get('data')
2023-06-28 12:34:57 +08:00
columns = request.json.get('key')
new_cols = [col_dict.get(x) if x in col_dict else x for x in columns]
print(new_cols)
df = pd.DataFrame.from_records(data, columns=new_cols)
logger.info(f"request key: {columns}")
logger.info(f"传入{len(data)}条数据")
2023-06-26 13:49:10 +08:00
if data is not None and len(data) != 0:
2023-06-26 14:56:24 +08:00
try:
2023-06-28 12:34:57 +08:00
rst = predict_df(history_data, df, lgb_model, object_cols, emission_factors)
2023-06-26 14:56:24 +08:00
resp_info["code"] = 200
resp_info["data"] = rst
except Exception as e:
resp_info["code"] = 406
resp_info["data"] = str(e)
2023-06-26 13:49:10 +08:00
else:
2023-06-26 14:56:24 +08:00
resp_info["msg"] = "Input is None, please check!"
2023-06-26 13:49:10 +08:00
resp_info["code"] = 406
resp = make_response(json.dumps(resp_info))
resp.status_code = 200
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8788, debug=False)