File size: 2,522 Bytes
8fc0265
 
 
 
 
 
 
c9fdbee
8fc0265
 
 
 
 
 
 
d002f8c
 
 
 
d95ffbd
8fc0265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f97ece8
 
8fc0265
f97ece8
8fc0265
f97ece8
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
import json
import numpy as np
import joblib
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

# Load model from the local storage (ensure the model file is in the same directory)
model_path = "model.pkl"
gb_model_loaded = joblib.load(model_path)

# Create FastAPI app
app = FastAPI()

# Define class labels
class_names = [
    'Emergency & Accident Unit ศูนย์อุบัติเหตุ-ฉุกเฉิน', 'Heart Clinic คลินิกโรคหัวใจ',
    'Neuro Med Center ศูนย์ระบบประสาทเเละสมอง', 'OPD:EYE คลินิกตา', 'Dental คลินิกทันตกรรม',
    'OPD:MED คลินิกอายุกรรมทั่วไป', 'OPD:ENT คลินิกหู คอ จมูก', 'OPD:OBG คลินิกสูติ-นรีเวชกรรม',
    'OPD:Surgery + Uro. คลินิกศัลยกรรมและทางเดินปัสสาวะ', 'Orthopedic Surgery คลินิกศัลยกรรมกระดูก',
    'GI Clinic ศูนย์ระบบทางเดินอาหารเเละตับ', 'Breast Clinic คลินิกเต้านม', 'Skin & Dermatology ศูนย์ผิวหนัง & ความงามด้านผิวพรรณ'
]

# Define the input format for FastAPI using Pydantic BaseModel
class InputData(BaseModel):
    features: list[float]  # List of 32 feature inputs

@app.post("/predict")
def predict(data: InputData):
    try:
        # Validate input length
        if len(data.features) != 32:
            raise HTTPException(status_code=400, detail=f"Expected 32 features, but got {len(data.features)}")

        # Convert list to numpy array and reshape
        input_array = np.array(data.features).reshape(1, -1)

        # Get predictions
        prediction = gb_model_loaded.predict_proba(input_array)

        # Convert probabilities to percentage and format
        probabilities = (prediction[0] * 100).round(2)
        result_pro = {class_name: f"{prob:.2f}%" for class_name, prob in zip(class_names, probabilities)}

        # Return result as JSON
        return {'result': result_pro}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# To run the FastAPI app locally for testing
# Uncomment the following lines
# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="0.0.0.0", port=8501)