RajendrakumarPachaiappan commited on
Commit
f718541
·
verified ·
1 Parent(s): ffbd98b

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. DockerFile +9 -6
  2. app.py +65 -82
  3. requirements.txt +2 -2
DockerFile CHANGED
@@ -1,17 +1,20 @@
1
 
2
- # Use a standard Python image
3
  FROM python:3.9-slim
4
 
5
- # Set the working directory
6
  WORKDIR /app
7
 
8
  # Copy the requirements file and install dependencies
9
  COPY requirements.txt .
10
  RUN pip install --no-cache-dir -r requirements.txt
11
 
12
- # Copy the application script
13
  COPY app.py .
14
 
15
- # Command to run the Streamlit app
16
- # This is the industry standard for HF Streamlit Docker deployments
17
- CMD ["streamlit", "run", "app.py"]
 
 
 
 
1
 
2
+ # Use a slim Python base image for smaller size
3
  FROM python:3.9-slim
4
 
5
+ # Set the working directory in the container
6
  WORKDIR /app
7
 
8
  # Copy the requirements file and install dependencies
9
  COPY requirements.txt .
10
  RUN pip install --no-cache-dir -r requirements.txt
11
 
12
+ # Copy the application file
13
  COPY app.py .
14
 
15
+ # Expose the port (Gradio/Hugging Face Spaces default to 7860)
16
+ EXPOSE 7860
17
+
18
+ # Command to run the application
19
+ # Gradio applications are typically run with host 0.0.0.0 for container compatibility
20
+ CMD ["python", "app.py"]
app.py CHANGED
@@ -1,101 +1,84 @@
1
 
2
- import streamlit as st
3
- import pandas as pd
4
  import joblib
 
 
5
  from huggingface_hub import hf_hub_download
6
 
7
- # --- Configuration ---
 
8
  REPO_ID_MODEL = "RajendrakumarPachaiappan/engine-predictive-model"
9
- MODEL_FILE = "final_random_forest_model.joblib"
10
- SCALER_FILE = "standard_scaler.joblib"
11
-
12
- # The feature columns must match the order expected by the scaler (validated against joblib file)
13
- FEATURE_COLS = ['Engine_RPM', 'Lub_Oil_Pressure', 'Fuel_Pressure',
14
- 'Coolant_Pressure', 'Lub_Oil_Temperature', 'Coolant_Temperature']
15
-
16
- # --- Resource Loading Function ---
17
- @st.cache_resource(show_spinner=False) # Suppress default spinner since we use custom status messages
18
- def load_model_and_scaler():
19
- """
20
- Downloads and loads the model and scaler from Hugging Face Hub.
21
- Does NOT use st. commands inside to avoid initial warnings.
22
- """
23
- try:
24
- # Download files from Hugging Face
25
- model_path = hf_hub_download(repo_id=REPO_ID_MODEL, filename=MODEL_FILE)
26
- model = joblib.load(model_path)
27
- scaler_path = hf_hub_download(repo_id=REPO_ID_MODEL, filename=SCALER_FILE)
28
- scaler = joblib.load(scaler_path)
29
- return model, scaler
30
- except Exception as e:
31
- # Re-raise a descriptive exception for the main script to catch
32
- raise Exception(f"Failed to load required artifacts: {e}")
33
 
34
- # --- Streamlit UI and Prediction Logic ---
 
 
 
 
35
 
36
- st.set_page_config(page_title="Predictive Maintenance", layout="wide")
37
- st.title("Engine Health Predictor ⚙️")
38
-
39
- # 1. Load Resources and Display Status
40
- st.info("Loading predictive model and scaler from Hugging Face Hub...")
41
  try:
42
- # This call triggers the download/caching
43
- model, scaler = load_model_and_scaler()
44
- st.success("Artifacts loaded successfully! Ready for prediction.")
 
45
 
46
- st.markdown("Use the sliders to simulate real-time sensor data and predict the **Engine Condition** (0=Healthy, 1=Faulty).")
 
 
 
47
 
48
  except Exception as e:
49
- # Display error and halt execution if resources fail to load
50
- st.error(f"🔴 Error loading resources: {e}")
51
- st.stop()
52
-
53
 
54
- # 2. Input Sliders
55
- # Use columns for a cleaner layout
56
- col1, col2, col3 = st.columns(3)
57
-
58
- with col1:
59
- Engine_RPM = st.slider("Engine RPM (rev/min)", min_value=60, max_value=2300, value=791, step=10)
60
- Lub_Oil_Pressure = st.slider("Lub Oil Pressure (bar)", min_value=0.0, max_value=7.3, value=3.3, step=0.1)
61
- Fuel_Pressure = st.slider("Fuel Pressure (bar)", min_value=0.0, max_value=22.0, value=6.7, step=0.1)
62
-
63
- with col2:
64
- Coolant_Pressure = st.slider("Coolant Pressure (bar)", min_value=0.0, max_value=7.5, value=2.3, step=0.1)
65
- Lub_Oil_Temperature = st.slider("Lub Oil Temp (°C)", min_value=71.0, max_value=90.0, value=78.0, step=0.1)
66
- Coolant_Temperature = st.slider("Coolant Temp (°C)", min_value=60.0, max_value=200.0, value=78.5, step=0.5)
67
-
68
- # 3. Prediction
69
- if st.button("Predict Engine Condition", type="primary"):
70
 
71
- # a. Prepare Input
72
- input_data = pd.DataFrame({
73
- 'Engine_RPM': [Engine_RPM],
74
- 'Lub_Oil_Pressure': [Lub_Oil_Pressure],
75
- 'Fuel_Pressure': [Fuel_Pressure],
76
- 'Coolant_Pressure': [Coolant_Pressure],
77
- 'Lub_Oil_Temperature': [Lub_Oil_Temperature],
78
- 'Coolant_Temperature': [Coolant_Temperature]
79
- })
80
 
81
- # b. Scale Input
82
- # Important: Use FEATURE_COLS to ensure correct order for the scaler
83
- input_scaled = scaler.transform(input_data[FEATURE_COLS])
84
 
85
- # c. Make Prediction
86
  prediction = model.predict(input_scaled)[0]
87
- # Get the probability of the *faulty* class (1)
88
- prediction_proba = model.predict_proba(input_scaled)[:, 1][0]
89
-
90
- # d. Display Results
91
- st.divider()
92
- st.subheader("Prediction Result:")
93
 
 
94
  if prediction == 1:
95
- st.error(f"Engine Condition: **FAULTY** (Probability of Fault: {prediction_proba:.2f}) ⚠️")
96
- st.write("Immediate maintenance is recommended to prevent breakdown.")
97
  else:
98
- st.success(f"Engine Condition: **HEALTHY** (Probability of Fault: {prediction_proba:.2f}) ✅")
99
- st.write("Engine is operating normally. Continue regular monitoring.")
100
-
101
- st.caption("Note: Probability of fault close to 0.5 indicates uncertainty.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ import gradio as gr
 
3
  import joblib
4
+ import pandas as pd
5
+ import numpy as np
6
  from huggingface_hub import hf_hub_download
7
 
8
+ # --- Hugging Face Model Repository Details ---
9
+ # Assuming your model and scaler are stored in this repo
10
  REPO_ID_MODEL = "RajendrakumarPachaiappan/engine-predictive-model"
11
+ MODEL_FILENAME = "final_random_forest_model.joblib"
12
+ SCALER_FILENAME = "standard_scaler.joblib"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # The six feature columns for input
15
+ FEATURE_COLS = [
16
+ 'Engine_RPM', 'Lub_Oil_Pressure', 'Fuel_Pressure',
17
+ 'Coolant_Pressure', 'Lub_Oil_Temperature', 'Coolant_Temperature'
18
+ ]
19
 
20
+ # --- Load Model and Scaler ---
 
 
 
 
21
  try:
22
+ # Download and load the model
23
+ model_path = hf_hub_download(repo_id=REPO_ID_MODEL, filename=MODEL_FILENAME, repo_type="model")
24
+ model = joblib.load(model_path)
25
+ print(f"Model loaded successfully from {model_path}")
26
 
27
+ # Download and load the scaler
28
+ scaler_path = hf_hub_download(repo_id=REPO_ID_MODEL, filename=SCALER_FILENAME, repo_type="model")
29
+ scaler = joblib.load(scaler_path)
30
+ print(f"Scaler loaded successfully from {scaler_path}")
31
 
32
  except Exception as e:
33
+ print(f"CRITICAL ERROR: Failed to load model or scaler. Check your repository ID and filenames. Error: {e}")
34
+ # In a real app, you might raise an error or use a dummy model
35
+ model, scaler = None, None
 
36
 
37
+ # --- Prediction Function ---
38
+ def predict_engine_condition(*args):
39
+ """
40
+ Takes 6 float values as input, scales them, and predicts the engine condition.
41
+ """
42
+ if model is None or scaler is None:
43
+ return "ERROR: Model not loaded. Check server logs."
 
 
 
 
 
 
 
 
 
44
 
45
+ # Convert inputs to a DataFrame for scaling
46
+ input_data = pd.DataFrame([list(args)], columns=FEATURE_COLS)
 
 
 
 
 
 
 
47
 
48
+ # Scale the input data using the loaded StandardScaler
49
+ input_scaled = scaler.transform(input_data)
 
50
 
51
+ # Make prediction
52
  prediction = model.predict(input_scaled)[0]
 
 
 
 
 
 
53
 
54
+ # Map the numerical prediction to a descriptive label
55
  if prediction == 1:
56
+ return "FAULTY (1) - Immediate Maintenance Required!"
 
57
  else:
58
+ return "NORMAL (0) - Operating within expected parameters."
59
+
60
+ # --- Gradio Interface Setup ---
61
+
62
+ # Create a list of Gradio Number components for the 6 features
63
+ input_components = [
64
+ gr.Number(label="Engine RPM (rev/min)", value=750),
65
+ gr.Number(label="Lub Oil Pressure (bar/kPa)", value=3.0),
66
+ gr.Number(label="Fuel Pressure (bar/kPa)", value=10.0),
67
+ gr.Number(label="Coolant Pressure (bar/kPa)", value=2.5),
68
+ gr.Number(label="Lub Oil Temperature (°C)", value=80.0),
69
+ gr.Number(label="Coolant Temperature (°C)", value=80.0),
70
+ ]
71
+
72
+ # Define the Gradio Interface
73
+ iface = gr.Interface(
74
+ fn=predict_engine_condition,
75
+ inputs=input_components,
76
+ outputs=gr.Label(label="Engine Condition Prediction", show_label=True),
77
+ title="Engine Predictive Maintenance Model",
78
+ description="Input the engine sensor readings to predict if the engine is operating normally (0) or is faulty (1). The inputs will be scaled using the pre-trained standard scaler before prediction.",
79
+ allow_flagging="never"
80
+ )
81
+
82
+ # Launch the app
83
+ if __name__ == "__main__":
84
+ iface.launch()
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
  pandas
 
2
  scikit-learn
3
  joblib
4
- streamlit
5
  huggingface-hub
6
- numpy
 
1
  pandas
2
+ numpy
3
  scikit-learn
4
  joblib
5
+ gradio
6
  huggingface-hub