Spaces:
Sleeping
Sleeping
Ravindra S commited on
Commit Β·
cb2f6b5
1
Parent(s): 4991529
added best model
Browse files- app.py +24 -33
- best_model_xgboost.h5 +3 -0
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import uvicorn
|
| 2 |
import joblib
|
| 3 |
import numpy as np
|
| 4 |
-
import
|
| 5 |
import sys
|
| 6 |
import os
|
| 7 |
from fastapi import FastAPI, HTTPException
|
|
@@ -9,7 +9,7 @@ from pydantic import BaseModel
|
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
|
| 11 |
# --- FILE PATHS (MUST match the export paths from your training script) ---
|
| 12 |
-
MODEL_EXPORT_PATH = "
|
| 13 |
SCALER_EXPORT_PATH = "scaler.joblib"
|
| 14 |
# -------------------------------------------------------------------------
|
| 15 |
|
|
@@ -25,23 +25,21 @@ class ConcreteInput(BaseModel):
|
|
| 25 |
|
| 26 |
# --- Initialize FastAPI App ---
|
| 27 |
app = FastAPI(
|
| 28 |
-
title="Concrete Strength Predictor",
|
| 29 |
-
description="API for predicting concrete compressive strength using
|
| 30 |
)
|
| 31 |
|
| 32 |
# --- CORS Configuration ---
|
| 33 |
-
origins = ["*"]
|
| 34 |
|
| 35 |
app.add_middleware(
|
| 36 |
CORSMiddleware,
|
| 37 |
allow_origins=origins,
|
| 38 |
allow_credentials=True,
|
| 39 |
-
allow_methods=["*"],
|
| 40 |
-
allow_headers=["*"],
|
| 41 |
)
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
# --- Global variables to store the loaded model and scaler ---
|
| 46 |
model = None
|
| 47 |
scaler = None
|
|
@@ -49,10 +47,10 @@ scaler = None
|
|
| 49 |
# --- Startup Event Handler to Load Assets ---
|
| 50 |
@app.on_event("startup")
|
| 51 |
def load_assets():
|
| 52 |
-
"""Load the
|
| 53 |
global model, scaler
|
| 54 |
-
print("Attempting to load model and scaler...")
|
| 55 |
-
|
| 56 |
# Load Scaler
|
| 57 |
try:
|
| 58 |
scaler = joblib.load(SCALER_EXPORT_PATH)
|
|
@@ -64,16 +62,16 @@ def load_assets():
|
|
| 64 |
print(f"β FATAL ERROR: Failed to load scaler: {e}")
|
| 65 |
sys.exit(1)
|
| 66 |
|
| 67 |
-
# Load Model
|
| 68 |
try:
|
| 69 |
-
|
| 70 |
-
model
|
| 71 |
-
print(f"β
|
| 72 |
except FileNotFoundError:
|
| 73 |
print(f"β FATAL ERROR: Model file not found at {MODEL_EXPORT_PATH}. Run the training script first!")
|
| 74 |
sys.exit(1)
|
| 75 |
except Exception as e:
|
| 76 |
-
print(f"β FATAL ERROR: Failed to load
|
| 77 |
sys.exit(1)
|
| 78 |
|
| 79 |
# --- Health Check Endpoint ---
|
|
@@ -85,37 +83,30 @@ def read_root():
|
|
| 85 |
# --- Prediction Endpoint ---
|
| 86 |
@app.post("/con-predict")
|
| 87 |
async def predict_strength(data: ConcreteInput):
|
| 88 |
-
"""
|
| 89 |
-
Accepts concrete component values and returns the predicted strength (MPa).
|
| 90 |
-
"""
|
| 91 |
if model is None or scaler is None:
|
| 92 |
raise HTTPException(status_code=503, detail="Model assets failed to load on startup.")
|
| 93 |
|
| 94 |
-
#
|
| 95 |
-
# This list must match the feature order: Cement, Slag, Ash, Water, Superplasticizer, Coarse Aggregate, Fine Aggregate, Age
|
| 96 |
input_list = [
|
| 97 |
-
data.cement, data.slag, data.ash, data.water,
|
| 98 |
-
data.superplasticizer, data.coarse_aggregate,
|
|
|
|
| 99 |
]
|
| 100 |
-
|
| 101 |
-
# Convert list to NumPy array, reshaping to (1, 8) for a single sample
|
| 102 |
input_array = np.array([input_list])
|
| 103 |
|
| 104 |
-
#
|
| 105 |
input_scaled = scaler.transform(input_array)
|
| 106 |
|
| 107 |
-
#
|
| 108 |
prediction = model.predict(input_scaled)
|
| 109 |
-
|
| 110 |
-
# Extract the single prediction value
|
| 111 |
-
predicted_strength = float(prediction[0][0])
|
| 112 |
|
| 113 |
-
#
|
| 114 |
return {
|
| 115 |
"predicted_strength_mpa": round(predicted_strength, 2),
|
| 116 |
"input_features": data.dict()
|
| 117 |
}
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
| 120 |
-
# Use --reload to automatically restart the server on file changes
|
| 121 |
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import uvicorn
|
| 2 |
import joblib
|
| 3 |
import numpy as np
|
| 4 |
+
import xgboost as xgb
|
| 5 |
import sys
|
| 6 |
import os
|
| 7 |
from fastapi import FastAPI, HTTPException
|
|
|
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
|
| 11 |
# --- FILE PATHS (MUST match the export paths from your training script) ---
|
| 12 |
+
MODEL_EXPORT_PATH = "best_model_xgboost.h5"
|
| 13 |
SCALER_EXPORT_PATH = "scaler.joblib"
|
| 14 |
# -------------------------------------------------------------------------
|
| 15 |
|
|
|
|
| 25 |
|
| 26 |
# --- Initialize FastAPI App ---
|
| 27 |
app = FastAPI(
|
| 28 |
+
title="Concrete Strength Predictor (XGBoost)",
|
| 29 |
+
description="API for predicting concrete compressive strength using XGBoost model."
|
| 30 |
)
|
| 31 |
|
| 32 |
# --- CORS Configuration ---
|
| 33 |
+
origins = ["*"]
|
| 34 |
|
| 35 |
app.add_middleware(
|
| 36 |
CORSMiddleware,
|
| 37 |
allow_origins=origins,
|
| 38 |
allow_credentials=True,
|
| 39 |
+
allow_methods=["*"],
|
| 40 |
+
allow_headers=["*"],
|
| 41 |
)
|
| 42 |
|
|
|
|
|
|
|
| 43 |
# --- Global variables to store the loaded model and scaler ---
|
| 44 |
model = None
|
| 45 |
scaler = None
|
|
|
|
| 47 |
# --- Startup Event Handler to Load Assets ---
|
| 48 |
@app.on_event("startup")
|
| 49 |
def load_assets():
|
| 50 |
+
"""Load the XGBoost model and StandardScaler on application startup."""
|
| 51 |
global model, scaler
|
| 52 |
+
print("Attempting to load XGBoost model and scaler...")
|
| 53 |
+
|
| 54 |
# Load Scaler
|
| 55 |
try:
|
| 56 |
scaler = joblib.load(SCALER_EXPORT_PATH)
|
|
|
|
| 62 |
print(f"β FATAL ERROR: Failed to load scaler: {e}")
|
| 63 |
sys.exit(1)
|
| 64 |
|
| 65 |
+
# Load XGBoost Model
|
| 66 |
try:
|
| 67 |
+
model = xgb.XGBRegressor()
|
| 68 |
+
model.load_model(MODEL_EXPORT_PATH)
|
| 69 |
+
print(f"β
XGBoost model loaded successfully from {MODEL_EXPORT_PATH}")
|
| 70 |
except FileNotFoundError:
|
| 71 |
print(f"β FATAL ERROR: Model file not found at {MODEL_EXPORT_PATH}. Run the training script first!")
|
| 72 |
sys.exit(1)
|
| 73 |
except Exception as e:
|
| 74 |
+
print(f"β FATAL ERROR: Failed to load XGBoost model: {e}")
|
| 75 |
sys.exit(1)
|
| 76 |
|
| 77 |
# --- Health Check Endpoint ---
|
|
|
|
| 83 |
# --- Prediction Endpoint ---
|
| 84 |
@app.post("/con-predict")
|
| 85 |
async def predict_strength(data: ConcreteInput):
|
| 86 |
+
"""Accepts concrete component values and returns the predicted strength (MPa)."""
|
|
|
|
|
|
|
| 87 |
if model is None or scaler is None:
|
| 88 |
raise HTTPException(status_code=503, detail="Model assets failed to load on startup.")
|
| 89 |
|
| 90 |
+
# Prepare input
|
|
|
|
| 91 |
input_list = [
|
| 92 |
+
data.cement, data.slag, data.ash, data.water,
|
| 93 |
+
data.superplasticizer, data.coarse_aggregate,
|
| 94 |
+
data.fine_aggregate, data.age
|
| 95 |
]
|
|
|
|
|
|
|
| 96 |
input_array = np.array([input_list])
|
| 97 |
|
| 98 |
+
# Scale input
|
| 99 |
input_scaled = scaler.transform(input_array)
|
| 100 |
|
| 101 |
+
# Predict strength
|
| 102 |
prediction = model.predict(input_scaled)
|
| 103 |
+
predicted_strength = float(prediction[0])
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Return result
|
| 106 |
return {
|
| 107 |
"predicted_strength_mpa": round(predicted_strength, 2),
|
| 108 |
"input_features": data.dict()
|
| 109 |
}
|
| 110 |
|
| 111 |
if __name__ == "__main__":
|
|
|
|
| 112 |
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|
best_model_xgboost.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1abba2c0ce8f2a746c9f0ad2033de0c2595efdf00a68d86466c8b1ada97dfca7
|
| 3 |
+
size 918884
|