コード例 #1
0
ファイル: app.py プロジェクト: Khuongb1609777/auto_ml_flask
def load_model():
    try:
        model_id = request.args.get("modelId")
        classModel = request.args.get("classModel")
        if (classModel == "SystemModelVn"):
            r = API.get_class("DatasetSurveyBalance")
            arr = str(r.data, "utf-8")
            r_json = json.loads(arr)
            data = r_json["results"]
            dataFrame = pd.DataFrame(data)
            dataFrame = dataFrame.iloc[:, 3:]
            dataFrame.drop('obesity', inplace=True, axis=1)
        new_record = request.args.get("record")
        new_record = new_record.split(",")
        df_new_record = pd.DataFrame([new_record])
        df_new_record.columns = dataFrame.columns
        for i in range(len(df_new_record)):
            for feature in list(df_new_record.columns):
                if df_new_record[feature][i] == "":
                    df_new_record[feature][i] = list(
                        dataFrame[feature].value_counts().index)[list(
                            dataFrame[feature].value_counts()).index(
                                min(dataFrame[feature].value_counts()))]
        if model_id == None:
            return "[error] modelId not found check (keys) modelId and values"
        else:
            r = API.get_model(classModel, model_id)
            modelUrl = r["modelFile"]["url"]
            Nu_SVC_classifier = joblib.load(urlopen(modelUrl))
            data_transform = {
                "0": "Thiếu cân (Insufficient weight)",
                "1": "Bình thường (Normal weight)",
                "2": "Thừa cân loại 1 (Overweight level 1)",
                "3": "Thừa cân loại 2 (Overweight level 2)",
                "4": "Béo phì loại 1 (Obesity type I)",
                "5": "Béo phì loại 2 (Obesity type II)",
                "6": "Béo phì loại 3 (Obesity type III)",
            }
            KQ = np.array(Nu_SVC_classifier.predict(df_new_record))
            dataReturn = {
                "dataPredict": [],
            }
            for rs in KQ:
                dataReturn["dataPredict"].append(data_transform[str(rs)])
            return dataReturn
    except:
        print("[error] check key (inputColumns) and value")
        return "[error] check key (inputColumns) and value (check type inputColumns)"
        pass
コード例 #2
0
ファイル: app.py プロジェクト: Khuongb1609777/auto_ml_flask
def create_api_model():
    # try:
    if request.headers["CONTENT_TYPE"] == "application/json":
        try:
            data_request = request.json
            modelId = data_request["modelId"]
            if modelId == None:
                return "[error] modelId not found check (keys) modelId and values "
            else:
                data_test_json = data_request["data"]
                data_test_dataFrame = pd.DataFrame(data_test_json)
                r = API.get_model("Model", modelId)
                modelUrl = r["modelFile"]["url"]
                Nu_SVC_classifier = joblib.load(urlopen(modelUrl))
                KQ = np.array(Nu_SVC_classifier.predict(data_test_dataFrame))
                data_transform = {
                    "0": "Thiếu cân (Insufficient weight)",
                    "1": "Bình thường (Normal weight)",
                    "2": "Thừa cân loại 1 (Overweight level 1)",
                    "3": "Thừa cân loại 2 (Overweight level 2)",
                    "4": "Béo phì loại 1 (Obesity type I)",
                    "5": "git Béo phì loại 2 (Obesity type II)",
                    "6": "Béo phì loại 3 (Obesity type III)",
                }
                dataReturn = {
                    "result": [],
                }
                for rs in KQ:
                    dataReturn["result"].append(data_transform[str(rs)])
                return dataReturn
        except:
            print("[error] check key (inputColumns) and value")
            return (
                "[error] check key (inputColumns) and value (check type inputColumns)"
            )
            pass
    else:
        modelId = request.form.get("modelId")
        if modelId == None:
            return "[error] modelId not found check (keys) modelId and values "
        else:
            file_test = request.files.getlist("data")[0]
            file_name = secure_filename(file_test.filename)
            if file_name == "":
                return "[error] Can't find data, check keys 'data' and values"
            else:
                try:
                    filename_random = str(uuid.uuid4())[:8] + "_" + file_name
                    if os.path.exists(app.config["DATA_API_FOLDER"]):
                        file_path_test = os.path.join(
                            app.config["DATA_API_FOLDER"], filename_random)
                    else:
                        os.makedirs(app.config["DATA_API_FOLDER"])
                        file_path_test = os.path.join(
                            app.config["DATA_API_FOLDER"], filename_random)
                    file_test.save(file_path_test)
                    df_test, columns, n, m = DATA.read("csv", file_path_test,
                                                       ",")
                except Exception as e:
                    print(e)
                    return "[error] can't save data, request fail"
                    pass
                try:
                    col_feature_test_string = request.form.getlist(
                        "inputColumns")[0]
                    col_feature_test_list = ast.literal_eval(
                        col_feature_test_string)
                    col_feature_test_array = np.array(col_feature_test_list)
                    r = API.get_model("Model", modelId)
                    modelUrl = r["modelFile"]["url"]
                    Nu_SVC_classifier = joblib.load(urlopen(modelUrl))
                except:
                    print("[error] request fail")
                    notification = (
                        "[error] request fail check key 'modelId', model " +
                        str(modelId) + " not found")
                    return notification
                    pass
                try:
                    data_test = df_test.iloc[:, col_feature_test_array]
                    KQ = np.array(Nu_SVC_classifier.predict(data_test))
                    data_transform = {
                        "0": "Thiếu cân (Insufficient weight)",
                        "1": "Bình thường (Normal weight)",
                        "2": "Thừa cân loại 1 (Overweight level 1)",
                        "3": "Thừa cân loại 2 (Overweight level 2)",
                        "4": "Béo phì loại 1 (Obesity type I)",
                        "5": "Béo phì loại 2 (Obesity type II)",
                        "6": "Béo phì loại 3 (Obesity type III)",
                    }
                    dataReturn = {
                        "result": [],
                    }
                    for rs in KQ:
                        dataReturn["result"].append(data_transform[str(rs)])
                    os.remove(file_path_test)
                    return dataReturn
                except IndexError:
                    print("[error] check key (inputColumns) and value")
                    return "[error] check key (inputColumns) and value check (number inputColumns)"
                    pass
                except ValueError:
                    print("[error] check key (inputColumns) and value")
                    return "[error] check key (inputColumns) and value (check type inputColumns)"
                    pass