VeerendraManikonda commited on
Commit
8ac5efa
·
verified ·
1 Parent(s): a2b7689

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +17 -10
  2. app.py +45 -104
  3. requirements.txt +5 -8
Dockerfile CHANGED
@@ -1,16 +1,23 @@
1
- FROM python:3.10-slim
 
2
 
3
- # Set the working directory inside the container
4
  WORKDIR /app
5
 
6
- # Copy all files from the current directory to the container's working directory
7
  COPY . .
8
 
9
- # Install dependencies from the requirements file without using cache to reduce image size
10
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
 
12
- # Define the command to start the application using Gunicorn with 4 worker processes
13
- # - `-w 4`: Uses 4 worker processes for handling requests
14
- # - `-b 0.0.0.0:7860`: Binds the server to port 7860 on all network interfaces
15
- # - `app:app`: Runs the Flask app (assuming `app.py` contains the Flask instance named `app`)
16
- CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "app:predictive_maintenance_api"]
 
 
 
 
 
 
 
1
+ # Use a minimal base image with Python 3.9 installed
2
+ FROM python:3.9
3
 
4
+ # Set the working directory inside the container to /app
5
  WORKDIR /app
6
 
7
+ # Copy all files from the current directory on the host to the container's /app directory
8
  COPY . .
9
 
10
+ # Install Python dependencies listed in requirements.txt
11
+ RUN pip3 install -r requirements.txt
12
 
13
+ RUN useradd -m -u 1000 user
14
+ USER user
15
+ ENV HOME=/home/user \
16
+ PATH=/home/user/.local/bin:$PATH
17
+
18
+ WORKDIR $HOME/app
19
+
20
+ COPY --chown=user . $HOME/app
21
+
22
+ # Define the command to run the Streamlit app on port "8501" and make it accessible externally
23
+ CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false"]
app.py CHANGED
@@ -1,104 +1,45 @@
1
- # Import necessary libraries
2
- import numpy as np
3
- 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
- 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")
14
-
15
- # Define the model path
16
- # Use the correct path as defined in the notebook
17
- #MODEL_PATH = "backend_files/Predictive_Maintenance_XGB_Tuned_model_v1_0.joblib"
18
- MODEL_PATH = "Predictive_Maintenance_XGB_Tuned_model_v1_0.joblib" # Corrected path
19
-
20
- # Load the trained machine learning model
21
- model = None
22
- try:
23
- model = joblib.load(MODEL_PATH)
24
- logging.info(f"Model loaded successfully from {MODEL_PATH}")
25
- except Exception as e:
26
- logging.error(f"Error loading model: {e}")
27
-
28
- # Define a route for the home page (GET request)
29
- @predictive_maintenance_api.get('/')
30
- def home():
31
- """
32
- This function handles GET requests to the root URL ('/') of the API.
33
- It returns a simple welcome message.
34
- """
35
- logging.info("Home page accessed.")
36
- return "Welcome to the Predictive Maintenance API for Engine Health!"
37
-
38
- # Define an endpoint for engine condition prediction (POST request)
39
- @predictive_maintenance_api.post('/v1/engine_condition_prediction')
40
- def predict_engine_condition():
41
- """
42
- This function handles POST requests to the '/v1/engine_condition_prediction' endpoint.
43
- It expects a JSON payload containing engine sensor data and returns
44
- the predicted engine condition (0 for Normal, 1 for Faulty) as a JSON response.
45
- """
46
- logging.info("Prediction request received.")
47
- if model is None:
48
- logging.error("Model not loaded when prediction request came. Returning 500.")
49
- return jsonify({"error": "Model not loaded. Please check server logs."}), 500
50
-
51
- # Get the JSON data from the request body
52
- engine_data = request.get_json()
53
- logging.info(f"Received engine data: {engine_data}")
54
-
55
- # Extract relevant features from the JSON data
56
- # Features: 'Engine_RPM', 'Lub_Oil_Pressure', 'Fuel_Pressure', 'Coolant_Pressure', 'Lub_Oil_Temperature', 'Coolant_Temperature'
57
- try:
58
- sample_data = {
59
- 'Engine_RPM': [engine_data['Engine_RPM']],
60
- 'Lub_Oil_Pressure': [engine_data['Lub_Oil_Pressure']],
61
- 'Fuel_Pressure': [engine_data['Fuel_Pressure']],
62
- 'Coolant_Pressure': [engine_data['Coolant_Pressure']],
63
- 'Lub_Oil_Temperature': [engine_data['Lub_Oil_Temperature']],
64
- 'Coolant_Temperature': [engine_data['Coolant_Temperature']]
65
- }
66
- logging.debug(f"Extracted sample data: {sample_data}")
67
- except KeyError as e:
68
- logging.error(f"Missing data for feature: {e}. Returning 400.")
69
- return jsonify({"error": f"Missing data for feature: {e}. Please provide all required sensor readings."}), 400
70
- except Exception as e:
71
- logging.error(f"Unexpected error during data extraction: {e}. Returning 400.")
72
- return jsonify({"error": f"An unexpected error occurred during data processing: {e}"}), 400
73
-
74
-
75
- # Convert the extracted data into a Pandas DataFrame
76
- # Ensure the order of columns matches the training data
77
- input_df = pd.DataFrame(sample_data)
78
-
79
- # Make prediction
80
- try:
81
- prediction_proba = model.predict_proba(input_df)
82
- predicted_class = model.predict(input_df)[0]
83
- logging.info(f"Prediction made: class={predicted_class}, probabilities={prediction_proba}")
84
- except Exception as e:
85
- logging.error(f"Error during model prediction: {e}. Returning 500.")
86
- return jsonify({"error": f"Error during model prediction: {e}"}), 500
87
-
88
- # Map the predicted class to a readable string
89
- condition_map = {0: "Normal", 1: "Faulty"}
90
- predicted_condition_str = condition_map.get(predicted_class, "Unknown")
91
-
92
- # Return the prediction as a JSON response
93
- return jsonify({
94
- "predicted_engine_condition_class": int(predicted_class), # Ensure it's a standard Python int
95
- "predicted_engine_condition_label": predicted_condition_str,
96
- "probability_normal": round(float(prediction_proba[0][0]), 4),
97
- "probability_faulty": round(float(prediction_proba[0][1]), 4)
98
- })
99
-
100
- # To run the Flask app (for local testing)
101
- if __name__ == '__main__':
102
- # You might want to get the port from an environment variable for deployment
103
- port = int(os.environ.get('PORT', 5000))
104
- predictive_maintenance_api.run(host='0.0.0.0', port=port, debug=True)
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from huggingface_hub import hf_hub_download
4
+ import joblib
5
+
6
+ # Download and load the model
7
+ model_path = hf_hub_download(repo_id="VeerendraManikonda/predictive_maintenance", filename="best_predictive_maintenance_model_v1.joblib")
8
+ model = joblib.load(model_path)
9
+
10
+ # Streamlit UI for Machine Failure Prediction
11
+ st.title("Predictive Maintenance for Engine Health")
12
+ st.write("""
13
+ This application predicts the potential Machine Failures based on the pitch parameters.
14
+ Please enter the Machine Sensor details.
15
+ """)
16
+
17
+ # Input form
18
+ with st.form("prediction_form"):
19
+ engine_rpm = st.number_input("Engine RPM", min_value=0.0, max_value=3000, value=700)
20
+ lub_oil_pressure = st.number_input("Lub Oil Pressure (bar/kPa)", min_value=0.0, max_value=10.0, value=2.5)
21
+ fuel_pressure = st.number_input("Fuel Pressure (bar/kPa)", min_value=0.0, max_value=30.0, value=12.0)
22
+ coolant_pressure = st.number_input("Coolant Pressure (bar/kPa)", min_value=0.0, max_value=10.0, value=3.0)
23
+ lub_oil_temperature = st.number_input("Lub Oil Temperature (°C)", min_value=0.0, max_value=150.0, value=85.0)
24
+ coolant_temperature = st.number_input("Coolant Temperature (°C)", min_value=0.0, max_value=150.0, value=80.0)
25
+
26
+ submit = st.form_submit_button("Predict")
27
+
28
+ if submit:
29
+ # Convert inputs to DataFrame
30
+ input_data = pd.DataFrame([{
31
+ "engine_rpm": engine_rpm,
32
+ "lub_oil_pressure": lub_oil_pressure,
33
+ "fuel_pressure": fuel_pressure,
34
+ "coolant_pressure": coolant_pressure,
35
+ "lub_oil_temperature": lub_oil_temperature,
36
+ "coolant_temperature": coolant_temperature
37
+ }])
38
+
39
+ # Predict
40
+ prediction = model.predict(input_data)[0]
41
+
42
+ if prediction == 1:
43
+ st.success("Engine is likely to be failing")
44
+ else:
45
+ st.error("Engine is in good condition.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,10 +1,7 @@
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]
 
1
  pandas==2.2.2
2
+ huggingface_hub==0.32.6
3
+ streamlit==1.43.2
4
+ joblib==1.5.1
5
+ scikit-learn==1.6.0
6
  xgboost==2.1.4
7
+ mlflow==3.0.1