from fastapi import FastAPI from asgiref.wsgi import WsgiToAsgi from flask import Flask, request, render_template import pickle, os from fastapi.middleware.wsgi import WSGIMiddleware # Initialize Flask app flask_app = Flask(__name__) def validasi_inputan(form_data): errors = {} if not form_data.get("XT_1"): errors["XT_1"] = "XT_1 tidak boleh kosong." else: try: XT_1 = float(form_data.get("XT_1")) except ValueError: errors["XT_1"] = "XT_1 harus berupa angka." if not form_data.get("XT_2"): errors["XT_2"] = "XT_2 tidak boleh kosong." else: try: XT_2 = float(form_data.get("XT_2")) except ValueError: errors["XT_2"] = "XT_2 harus berupa angka." if not form_data.get("XT_3"): errors["XT_3"] = "XT_3 tidak boleh kosong." else: try: XT_3 = float(form_data.get("XT_3")) except ValueError: errors["XT_3"] = "XT_3 harus berupa angka." return errors def validate_data(record): errors = {} if record["XT_1"] < 5000 or record["XT_1"] > 40000: errors["XT_1"] = "XT_1 harus diantara 0 dan 1.0" if record["XT_2"] < 5000 or record["XT_2"] > 40000: errors["XT_2"] = "XT_2 harus diantara 0.0 dan 1.0" if record["XT_3"] < 5000 or record["XT_3"] > 40000: errors["XT_3"] = "XT_3 harus diantara 0.0 dan 1.0" return errors # Load models linear_model_load = pickle.load(open('best_bagging_model.sav', 'rb')) scaler_load = pickle.load(open('scaler.sav', 'rb')) # Flask route @flask_app.route("/", methods=["GET", "POST"]) def index(): prediction = None errors = {} if request.method == "POST": # Validasi inputan tidak boleh kosong errors = validasi_inputan(request.form) if not errors: record = { "XT_1": float(request.form.get("XT_1")), "XT_2": float(request.form.get("XT_2")), "XT_3": float(request.form.get("XT_3")), } errors = validate_data(record) if not errors: # Data input untuk prediksi input_data = [ record["XT_1"], record["XT_2"], record["XT_3"], ] # Normalisasi input data input_data_normalized = scaler_load.transform([input_data]) # Membuat prediksi dari model predicted_value_normalized = linear_model_load.predict(input_data_normalized) # Menyesuaikan bentuk data untuk inverse_transform predicted_value_normalized_full = [[predicted_value_normalized[0], 0, 0]] predicted_value_full = scaler_load.inverse_transform(predicted_value_normalized_full) # Mengambil elemen prediksi pertama sebagai hasil akhir prediction = int(predicted_value_full[0][0]) return render_template('index.html', prediction=prediction, errors=errors, record=request.form) # FastAPI app to mount Flask app app = FastAPI() # Mount Flask app inside FastAPI using WSGIMiddleware app.mount("/", WSGIMiddleware(flask_app))