harishsohani commited on
Commit
f9db8a8
·
verified ·
1 Parent(s): 2444100

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. Dockerfile +17 -0
  2. app.py +59 -0
  3. requirements.txt +12 -0
  4. utils/__init__.py +1 -0
  5. utils/validation.py +57 -0
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use a minimal base image with Python 3.9 installed
2
+ FROM python:3.9-slim
3
+
4
+ # Set the working directory inside the container to /app
5
+ WORKDIR /app
6
+
7
+ # Copy all files from the current directory to the container's working directory
8
+ COPY . .
9
+
10
+ # Install dependencies from the requirements file without using cache to reduce image size
11
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
12
+
13
+ # Define the command to start the application using Gunicorn with 4 worker processes
14
+ # - `-w 4`: Uses 4 worker processes for handling requests
15
+ # - `-b 0.0.0.0:7860`: Binds the server to port 7860 on all network interfaces
16
+ # - `app:app`: Runs the Flask app (assuming `app.py` contains the Flask instance named `app`)
17
+ CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "app:pred_mainteanance_api"]
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import joblib
3
+ import pandas as pd
4
+ from flask import Flask, request, jsonify
5
+ from utils.validation import validate_and_prepare_input, InputValidationError
6
+
7
+ # Initialize Flask app with a name
8
+ pred_mainteanance_api = Flask ("Engine Maintenance Predictor")
9
+
10
+ # Load the trained churn prediction model
11
+ model = joblib.load ("best_eng_fail_pred_model.joblib")
12
+
13
+ # Define a route for the home page
14
+ @pred_mainteanance_api.get ('/')
15
+ def home ():
16
+ return "Welcome to the Engine Maintenance Prediction!"
17
+
18
+ # Define an endpoint to predict sales for Super Kart
19
+ @pred_mainteanance_api.post ('/v1/EngPredMaintenance')
20
+ def predict_need_maintenance ():
21
+ # Get JSON data from the request
22
+ engine_sensor_inputs = request.get_json ()
23
+
24
+ # validate request (json)
25
+ # if input is valid - return prediction
26
+ # in case of error - return appropriate error
27
+ try:
28
+ input_json = request.get_json()
29
+ input_df = pd.DataFrame([input_json])
30
+
31
+ validated_df = validate_and_prepare_input(input_df, model)
32
+
33
+ prediction = model.predict(validated_df)[0]
34
+
35
+ return jsonify({
36
+ "status": "success",
37
+ "prediction": int(prediction)
38
+ })
39
+
40
+ except InputValidationError as e:
41
+ return jsonify({
42
+ "status": "error",
43
+ "error_type": "validation_error",
44
+ "message": str(e)
45
+ }), 400
46
+
47
+ except Exception as e:
48
+ return jsonify({
49
+ "status": "error",
50
+ "error_type": "internal_error",
51
+ "message": "Unexpected server error"
52
+ }), 500
53
+
54
+
55
+ # Run the Flask app
56
+ if __name__ == "__main__":
57
+ import os
58
+ port = int (os.environ.get("PORT", 7860))
59
+ pred_mainteanance_api.run(host="0.0.0.0", port=port)
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pandas==2.2.2
2
+ numpy==2.0.2
3
+ scikit-learn==1.6.1
4
+ xgboost==2.1.4
5
+ joblib==1.4.2
6
+ Werkzeug==2.2.2
7
+ flask==2.2.2
8
+ gunicorn==20.1.0
9
+ requests==2.28.1
10
+ uvicorn[standard]
11
+ streamlit==1.43.2
12
+ dill==0.3.8
utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
utils/validation.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pandas as pd
3
+
4
+
5
+ class InputValidationError(Exception):
6
+ """Custom exception for input validation errors."""
7
+ pass
8
+
9
+
10
+ def validate_and_prepare_input(input_df: pd.DataFrame, model):
11
+ """
12
+ Validates input dataframe against model expected features.
13
+ Returns a clean dataframe ready for prediction.
14
+ """
15
+
16
+ if not isinstance(input_df, pd.DataFrame):
17
+ raise InputValidationError("Input must be a pandas DataFrame.")
18
+
19
+ # Get expected feature names from trained XGBoost model
20
+ try:
21
+ expected_features = model.get_booster().feature_names
22
+ except Exception:
23
+ raise InputValidationError("Unable to retrieve model feature names.")
24
+
25
+ # -------------------------
26
+ # 1 Check missing columns
27
+ # -------------------------
28
+ missing_cols = set(expected_features) - set(input_df.columns)
29
+ if missing_cols:
30
+ raise InputValidationError(
31
+ f"Missing required columns: {list(missing_cols)}"
32
+ )
33
+
34
+ # -------------------------
35
+ # 2 Check extra columns
36
+ # -------------------------
37
+ extra_cols = set(input_df.columns) - set(expected_features)
38
+ if extra_cols:
39
+ raise InputValidationError(
40
+ f"Unexpected columns provided: {list(extra_cols)}"
41
+ )
42
+
43
+ # -------------------------
44
+ # 3 Enforce numeric types
45
+ # -------------------------
46
+ for col in expected_features:
47
+ if not pd.api.types.is_numeric_dtype(input_df[col]):
48
+ raise InputValidationError(
49
+ f"Column '{col}' must be numeric."
50
+ )
51
+
52
+ # -------------------------
53
+ # 4 Reorder columns safely
54
+ # -------------------------
55
+ input_df = input_df[expected_features]
56
+
57
+ return input_df