[59083a]: / app.py

Download this file

64 lines (45 with data), 1.6 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from utils import Preprocess, MissingValue
import pickle
from fastapi import FastAPI, Request
import pandas as pd
import numpy as np
import onnxruntime as ort
# Load pre-trained model, scaler, and column names
with open(f'model/columns.pkl', 'rb') as f:
cols = pickle.load(f)
with open(f'model/scaler.pkl', 'rb') as f:
sc = pickle.load(f)
with open(f'model/model.pkl', 'rb') as f:
model = pickle.load(f)
app = FastAPI()
@app.post("/predict/")
async def predict(request: Request):
try:
data = await request.json()
df = pd.read_json(data, orient='records')
preprocessor = Preprocess(
dataframe=df,
missing_value_per=0,
variance_threshold=0,
min_null_per=0
)
test = preprocessor._mapping(df)
m = MissingValue(test)
test = m.fill_dataframe()
x_test = test[cols]
x_test = sc.transform(x_test)
optimized_model_path = 'model/optimized_random_forest_model.onnx'
session = ort.InferenceSession(optimized_model_path)
# Run inference
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
x_test = np.array(x_test, dtype=np.float32)
# Make predictions
y_pred = session.run([output_name], {input_name: x_test})
y_pred = y_pred[0]
# y_pred = model.predict(x_test)
return {"predictions": y_pred.tolist()}
# return {"predictions": y_pred.tolist()}
except Exception as e:
return {"error": str(e)}
# Run the application using: uvicorn main:app --reload