harishsohani commited on
Commit
76fbb44
·
verified ·
1 Parent(s): f6f706e

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. app.py +31 -26
  2. utils/__init__.py +1 -0
  3. utils/validation.py +6 -5
app.py CHANGED
@@ -2,12 +2,13 @@
2
  import joblib
3
  import pandas as pd
4
  from flask import Flask, request, jsonify
 
5
 
6
  # Initialize Flask app with a name
7
  pred_mainteanance_api = Flask ("Engine Maintenance Predictor")
8
 
9
  # Load the trained churn prediction model
10
- model = joblib.load ("best_eng_fail_pred_model.joblib.joblib")
11
 
12
  # Define a route for the home page
13
  @pred_mainteanance_api.get ('/')
@@ -20,31 +21,35 @@ def predict_need_maintenance ():
20
  # Get JSON data from the request
21
  engine_sensor_inputs = request.get_json ()
22
 
23
- import datetime
24
-
25
- current_year = datetime.datetime.now ().year # dynamic current year
26
-
27
- # Extract relevant features from the input data
28
- data_info = {
29
- 'Engine_rpm' : engine_sensor_inputs ['Engine_rpm'],
30
- 'Lub_oil_pressure' : engine_sensor_inputs ['Lub_oil_pressure'],
31
- 'Fuel_pressure' : engine_sensor_inputs ['Fuel_pressure'],
32
- 'Coolant_pressure' : engine_sensor_inputs ['Coolant_pressure'],
33
- 'lub_oil_temp' : engine_sensor_inputs ['lub_oil_temp'],
34
- 'Coolant_temp' : engine_sensor_inputs ['Coolant_temp']
35
- }
36
-
37
- # Convert the extracted data into a DataFrame
38
- input_data = pd.DataFrame ([data_info])
39
-
40
- # Enforce types - convert all to float
41
- input_data = input_data.astype (float)
42
-
43
- # Make prediction using the trained model
44
- predicted_sales = model.predict (input_data).tolist ()[0]
45
-
46
- # Return the prediction as a JSON response
47
- return jsonify ({'NeedsMaintenance': predicted_sales})
 
 
 
 
48
 
49
 
50
  # Run the Flask app
 
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 ('/')
 
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
utils/__init__.py CHANGED
@@ -0,0 +1 @@
 
 
1
+
utils/validation.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import pandas as pd
2
 
3
 
@@ -22,7 +23,7 @@ def validate_and_prepare_input(input_df: pd.DataFrame, model):
22
  raise InputValidationError("Unable to retrieve model feature names.")
23
 
24
  # -------------------------
25
- # 1️⃣ Check missing columns
26
  # -------------------------
27
  missing_cols = set(expected_features) - set(input_df.columns)
28
  if missing_cols:
@@ -31,7 +32,7 @@ def validate_and_prepare_input(input_df: pd.DataFrame, model):
31
  )
32
 
33
  # -------------------------
34
- # 2️⃣ Check extra columns
35
  # -------------------------
36
  extra_cols = set(input_df.columns) - set(expected_features)
37
  if extra_cols:
@@ -40,7 +41,7 @@ def validate_and_prepare_input(input_df: pd.DataFrame, model):
40
  )
41
 
42
  # -------------------------
43
- # 3️⃣ Enforce numeric types
44
  # -------------------------
45
  for col in expected_features:
46
  if not pd.api.types.is_numeric_dtype(input_df[col]):
@@ -49,8 +50,8 @@ def validate_and_prepare_input(input_df: pd.DataFrame, model):
49
  )
50
 
51
  # -------------------------
52
- # 4️⃣ Reorder columns safely
53
  # -------------------------
54
  input_df = input_df[expected_features]
55
 
56
- return input_df
 
1
+
2
  import pandas as pd
3
 
4
 
 
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:
 
32
  )
33
 
34
  # -------------------------
35
+ # 2 Check extra columns
36
  # -------------------------
37
  extra_cols = set(input_df.columns) - set(expected_features)
38
  if 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]):
 
50
  )
51
 
52
  # -------------------------
53
+ # 4 Reorder columns safely
54
  # -------------------------
55
  input_df = input_df[expected_features]
56
 
57
+ return input_df