VeerendraManikonda commited on
Commit
4f06a74
·
verified ·
1 Parent(s): 9cd8f74

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +24 -7
app.py CHANGED
@@ -4,6 +4,10 @@ import joblib # For loading the serialized model
4
  import pandas as pd # For data manipulation
5
  from flask import Flask, request, jsonify # For creating the Flask API
6
  import os # For accessing environment variables if needed
 
 
 
 
7
 
8
  # Initialize the Flask application
9
  predictive_maintenance_api = Flask("Predictive Maintenance API")
@@ -13,12 +17,12 @@ predictive_maintenance_api = Flask("Predictive Maintenance API")
13
  MODEL_PATH = "backend_files/Predictive_Maintenance_XGB_Tuned_model_v1_0.joblib"
14
 
15
  # Load the trained machine learning model
 
16
  try:
17
  model = joblib.load(MODEL_PATH)
18
- print(f"Model loaded successfully from {MODEL_PATH}")
19
  except Exception as e:
20
- print(f"Error loading model: {e}")
21
- model = None # Set model to None if loading fails
22
 
23
  # Define a route for the home page (GET request)
24
  @predictive_maintenance_api.get('/')
@@ -27,6 +31,7 @@ def home():
27
  This function handles GET requests to the root URL ('/') of the API.
28
  It returns a simple welcome message.
29
  """
 
30
  return "Welcome to the Predictive Maintenance API for Engine Health!"
31
 
32
  # Define an endpoint for engine condition prediction (POST request)
@@ -37,11 +42,14 @@ def predict_engine_condition():
37
  It expects a JSON payload containing engine sensor data and returns
38
  the predicted engine condition (0 for Normal, 1 for Faulty) as a JSON response.
39
  """
 
40
  if model is None:
 
41
  return jsonify({"error": "Model not loaded. Please check server logs."}), 500
42
 
43
  # Get the JSON data from the request body
44
  engine_data = request.get_json()
 
45
 
46
  # Extract relevant features from the JSON data
47
  # Features: 'Engine_RPM', 'Lub_Oil_Pressure', 'Fuel_Pressure', 'Coolant_Pressure', 'Lub_Oil_Temperature', 'Coolant_Temperature'
@@ -54,18 +62,27 @@ def predict_engine_condition():
54
  'Lub_Oil_Temperature': [engine_data['Lub_Oil_Temperature']],
55
  'Coolant_Temperature': [engine_data['Coolant_Temperature']]
56
  }
 
57
  except KeyError as e:
 
58
  return jsonify({"error": f"Missing data for feature: {e}. Please provide all required sensor readings."}), 400
 
 
 
 
59
 
60
  # Convert the extracted data into a Pandas DataFrame
61
  # Ensure the order of columns matches the training data
62
  input_df = pd.DataFrame(sample_data)
63
 
64
  # Make prediction
65
- # model.predict_proba will give probabilities for both classes [prob_class_0, prob_class_1]
66
- # model.predict will give the predicted class (0 or 1)
67
- prediction_proba = model.predict_proba(input_df)
68
- predicted_class = model.predict(input_df)[0]
 
 
 
69
 
70
  # Map the predicted class to a readable string
71
  condition_map = {0: "Normal", 1: "Faulty"}
 
4
  import pandas as pd # For data manipulation
5
  from flask import Flask, request, jsonify # For creating the Flask API
6
  import os # For accessing environment variables if needed
7
+ import logging # For logging
8
+
9
+ # Configure logging
10
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
11
 
12
  # Initialize the Flask application
13
  predictive_maintenance_api = Flask("Predictive Maintenance API")
 
17
  MODEL_PATH = "backend_files/Predictive_Maintenance_XGB_Tuned_model_v1_0.joblib"
18
 
19
  # Load the trained machine learning model
20
+ model = None
21
  try:
22
  model = joblib.load(MODEL_PATH)
23
+ logging.info(f"Model loaded successfully from {MODEL_PATH}")
24
  except Exception as e:
25
+ logging.error(f"Error loading model: {e}")
 
26
 
27
  # Define a route for the home page (GET request)
28
  @predictive_maintenance_api.get('/')
 
31
  This function handles GET requests to the root URL ('/') of the API.
32
  It returns a simple welcome message.
33
  """
34
+ logging.info("Home page accessed.")
35
  return "Welcome to the Predictive Maintenance API for Engine Health!"
36
 
37
  # Define an endpoint for engine condition prediction (POST request)
 
42
  It expects a JSON payload containing engine sensor data and returns
43
  the predicted engine condition (0 for Normal, 1 for Faulty) as a JSON response.
44
  """
45
+ logging.info("Prediction request received.")
46
  if model is None:
47
+ logging.error("Model not loaded when prediction request came. Returning 500.")
48
  return jsonify({"error": "Model not loaded. Please check server logs."}), 500
49
 
50
  # Get the JSON data from the request body
51
  engine_data = request.get_json()
52
+ logging.info(f"Received engine data: {engine_data}")
53
 
54
  # Extract relevant features from the JSON data
55
  # Features: 'Engine_RPM', 'Lub_Oil_Pressure', 'Fuel_Pressure', 'Coolant_Pressure', 'Lub_Oil_Temperature', 'Coolant_Temperature'
 
62
  'Lub_Oil_Temperature': [engine_data['Lub_Oil_Temperature']],
63
  'Coolant_Temperature': [engine_data['Coolant_Temperature']]
64
  }
65
+ logging.debug(f"Extracted sample data: {sample_data}")
66
  except KeyError as e:
67
+ logging.error(f"Missing data for feature: {e}. Returning 400.")
68
  return jsonify({"error": f"Missing data for feature: {e}. Please provide all required sensor readings."}), 400
69
+ except Exception as e:
70
+ logging.error(f"Unexpected error during data extraction: {e}. Returning 400.")
71
+ return jsonify({"error": f"An unexpected error occurred during data processing: {e}"}), 400
72
+
73
 
74
  # Convert the extracted data into a Pandas DataFrame
75
  # Ensure the order of columns matches the training data
76
  input_df = pd.DataFrame(sample_data)
77
 
78
  # Make prediction
79
+ try:
80
+ prediction_proba = model.predict_proba(input_df)
81
+ predicted_class = model.predict(input_df)[0]
82
+ logging.info(f"Prediction made: class={predicted_class}, probabilities={prediction_proba}")
83
+ except Exception as e:
84
+ logging.error(f"Error during model prediction: {e}. Returning 500.")
85
+ return jsonify({"error": f"Error during model prediction: {e}"}), 500
86
 
87
  # Map the predicted class to a readable string
88
  condition_map = {0: "Normal", 1: "Faulty"}