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

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. DockerFile +3 -6
  2. app.py +75 -54
  3. hosting.py +1 -1
DockerFile CHANGED
@@ -1,5 +1,5 @@
1
 
2
- # Use a Python base image
3
  FROM python:3.9-slim
4
 
5
  # Set the working directory
@@ -12,9 +12,6 @@ RUN pip install --no-cache-dir -r requirements.txt
12
  # Copy the application script
13
  COPY app.py .
14
 
15
- # Expose the port Streamlit runs on
16
- EXPOSE 8501
17
-
18
- # CRITICAL FIX: Use CMD to combine the execution command and filename
19
- # This ensures 'streamlit run app.py' is executed upon container start.
20
  CMD ["streamlit", "run", "app.py"]
 
1
 
2
+ # Use a standard Python image
3
  FROM python:3.9-slim
4
 
5
  # Set the working directory
 
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"]
app.py CHANGED
@@ -4,77 +4,98 @@ import pandas as pd
4
  import joblib
5
  from huggingface_hub import hf_hub_download
6
 
7
-
8
- MODEL_REPO_ID = "RajendrakumarPachaiappan/engine-predictive-model"
9
- MODEL_FILE = "final_random_forest_model.joblib"
10
  SCALER_FILE = "standard_scaler.joblib"
11
 
12
- FEATURE_COLS = ['Engine rpm', 'Lub oil pressure', 'Fuel pressure',
13
- 'Coolant pressure', 'lub oil temp', 'Coolant temp']
14
-
15
 
16
- @st.cache_resource
 
17
  def load_model_and_scaler():
18
- """Downloads and loads the model and scaler from Hugging Face Hub."""
19
- st.info("Loading model and scaler from Hugging Face Hub...")
 
 
20
  try:
21
- model_path = hf_hub_download(repo_id=MODEL_REPO_ID, filename=MODEL_FILE)
 
22
  model = joblib.load(model_path)
23
- scaler_path = hf_hub_download(repo_id=MODEL_REPO_ID, filename=SCALER_FILE)
24
  scaler = joblib.load(scaler_path)
25
- st.success("Artifacts loaded successfully!")
26
  return model, scaler
27
  except Exception as e:
28
- st.error(f"Error loading artifacts from Hugging Face Hub: {e}")
29
- return None, None
30
 
31
- model, scaler = load_model_and_scaler()
32
 
33
- # Streamlit UI and Prediction Logic
34
  st.set_page_config(page_title="Predictive Maintenance", layout="wide")
35
- st.title("Engine Health Predictor")
36
- st.markdown("Use the sliders to simulate real-time sensor data and predict the **Engine Condition** (0=Healthy, 1=Faulty).")
 
 
 
 
 
 
 
 
37
 
 
 
 
 
 
 
 
 
38
  col1, col2, col3 = st.columns(3)
39
 
40
  with col1:
41
-
42
- Engine_rpm = st.slider("Engine RPM (rev/min)", min_value=60, max_value=2300, value=791, step=10)
43
- Lub_oil_pressure = st.slider("Lub Oil Pressure (bar)", min_value=0.0, max_value=7.3, value=3.3, step=0.1)
44
- Fuel_pressure = st.slider("Fuel Pressure (bar)", min_value=0.0, max_value=22.0, value=6.7, step=0.1)
45
 
46
  with col2:
 
 
 
47
 
48
- Coolant_pressure = st.slider("Coolant Pressure (bar)", min_value=0.0, max_value=7.5, value=2.3, step=0.1)
49
- Lub_oil_temp = st.slider("Lub Oil Temp (°C)", min_value=71.0, max_value=90.0, value=78.0, step=0.1)
50
- Coolant_temp = st.slider("Coolant Temp (°C)", min_value=60.0, max_value=200.0, value=78.5, step=0.5)
51
-
52
- # Prediction
53
  if st.button("Predict Engine Condition", type="primary"):
54
- if model and scaler:
55
-
56
- input_data = pd.DataFrame({
57
- 'Engine rpm': [Engine_rpm],
58
- 'Lub oil pressure': [Lub_oil_pressure],
59
- 'Fuel pressure': [Fuel_pressure],
60
- 'Coolant pressure': [Coolant_pressure],
61
- 'lub oil temp': [Lub_oil_temp],
62
- 'Coolant temp': [Coolant_temp]
63
- }, index=[0])
64
-
65
-
66
- scaled_data = scaler.transform(input_data)
67
-
68
- prediction = model.predict(scaled_data)[0]
69
- prediction_proba = model.predict_proba(scaled_data)[0]
70
-
71
- # Display Results
72
- st.subheader("Prediction Result:")
73
- if prediction == 1:
74
- st.error(f"**FAULTY (Requires Maintenance)**")
75
- st.markdown(f"**Confidence (Faulty):** `{prediction_proba[1]*100:.2f}%`")
76
- st.warning("**Actionable Insight:** The model predicts a high risk of failure. Schedule maintenance immediately.")
77
- else:
78
- st.success(f"**HEALTHY (Normal Operation)**")
79
- st.markdown(f"**Confidence (Healthy):** `{prediction_proba[0]*100:.2f}%`")
80
- st.info("Engine is operating within normal parameters. Continue monitoring.")
 
 
 
 
 
 
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.")
hosting.py CHANGED
@@ -5,7 +5,7 @@ import os
5
  api = HfApi(token=os.getenv("HF_TOKEN"))
6
  api.upload_folder(
7
  folder_path="/content/Predictive_Maintenance_Project/deployment",
8
-
9
  repo_id="RajendrakumarPachaiappan/EnginePredictionModel",
10
 
11
  repo_type="space",
 
5
  api = HfApi(token=os.getenv("HF_TOKEN"))
6
  api.upload_folder(
7
  folder_path="/content/Predictive_Maintenance_Project/deployment",
8
+
9
  repo_id="RajendrakumarPachaiappan/EnginePredictionModel",
10
 
11
  repo_type="space",