ShaksML commited on
Commit
85c601b
·
verified ·
1 Parent(s): e59ed1d

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. Dockerfile +19 -0
  2. dt_app.py +139 -0
  3. hosting.py +23 -0
  4. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use a minimal base image with Python 3.9 installed
2
+ FROM python:3.9
3
+
4
+ WORKDIR /app
5
+
6
+ COPY . .
7
+
8
+ RUN pip3 install -r requirements.txt
9
+ RUN useradd -m -u 1000 user
10
+ USER user
11
+
12
+ ENV HOME=/home/user \
13
+ PATH=/home/user/.local/bin:$PATH
14
+
15
+ WORKDIR $HOME/app
16
+
17
+ COPY --chown=user . $HOME/app
18
+
19
+ CMD ["streamlit", "run", "dt_app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false"]
dt_app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib
5
+ from huggingface_hub import hf_hub_download
6
+ import os
7
+
8
+ # --- Constants: MODIFIED FOR DECISION TREE MODEL (CODE 4) ---
9
+ # Use the exact repository ID from Code 4
10
+ HF_MODEL_REPO_ID = "ShaksML/dt-model-predective-maintenance"
11
+ # The model file was saved and uploaded as 'optimized_dt_predictor.pkl' in Code 4
12
+ HF_MODEL_FILENAME = "optimized_dt_predictor.pkl"
13
+ # Note: Since Code 4 trained a scikit-learn Pipeline (Scaler + DT), the pipeline handles preprocessing.
14
+
15
+ # --- Function to Load Model from Hugging Face ---
16
+ @st.cache_resource
17
+ def load_model():
18
+ """Downloads the model artifact from the Hugging Face Hub and loads it."""
19
+ try:
20
+ # Download the model file from the Hugging Face repository
21
+ model_path = hf_hub_download(
22
+ repo_id=HF_MODEL_REPO_ID,
23
+ filename=HF_MODEL_FILENAME,
24
+ repo_type="model", # Explicitly set repo_type to 'model'
25
+ local_dir=".",
26
+ local_dir_use_symlinks=False
27
+ )
28
+ st.success(f"Model '{HF_MODEL_FILENAME}' successfully loaded from {HF_MODEL_REPO_ID}!")
29
+ # Load the model using joblib (which is the format used by Code 4)
30
+ model = joblib.load(model_path)
31
+ return model
32
+ except Exception as e:
33
+ st.error(f"Error loading model from Hugging Face Hub. Please check repo ID and filename: {e}")
34
+ st.stop() # Stop execution if the model cannot be loaded
35
+
36
+ # --- Streamlit Application Layout ---
37
+
38
+ st.set_page_config(
39
+ page_title="DT Predictive Maintenance App",
40
+ layout="wide"
41
+ )
42
+
43
+ st.title("⚙️ Decision Tree Engine Maintenance Dashboard")
44
+ st.subheader("Forecast potential engine failures using real-time sensor data.")
45
+
46
+ # Load the trained model
47
+ model = load_model()
48
+
49
+ # Define the columns exactly as expected by the model (using the names from the original data)
50
+ # Assuming the column names are:
51
+ INPUT_COLUMNS = [
52
+ 'Engine rpm', 'Lub oil pressure', 'Fuel pressure',
53
+ 'Coolant pressure', 'lub oil temp', 'Coolant temp'
54
+ ]
55
+
56
+ if model is not None:
57
+ # --- Input Form for Sensor Readings ---
58
+ st.markdown("---")
59
+ st.header("Enter Engine Sensor Readings")
60
+
61
+ # Dictionary to hold the user inputs
62
+ input_data = {}
63
+
64
+ # Define the input columns in a three-column layout
65
+ col1, col2, col3 = st.columns(3)
66
+
67
+ with col1:
68
+ # Engine rpm (int)
69
+ input_data['Engine rpm'] = st.number_input(
70
+ "Engine RPM (Revolutions per Minute)",
71
+ min_value=400, max_value=2000, value=790, step=10, key='rpm'
72
+ )
73
+ # Lub oil pressure (float)
74
+ input_data['Lub oil pressure'] = st.number_input(
75
+ "Lub Oil Pressure (bar)",
76
+ min_value=0.0, max_value=8.0, value=3.30, step=0.1, format="%.2f", key='lop'
77
+ )
78
+
79
+ with col2:
80
+ # Fuel pressure (float)
81
+ input_data['Fuel pressure'] = st.number_input(
82
+ "Fuel Pressure (bar)",
83
+ min_value=0.0, max_value=25.0, value=6.60, step=0.1, format="%.2f", key='fp'
84
+ )
85
+ # Coolant pressure (float)
86
+ input_data['Coolant pressure'] = st.number_input(
87
+ "Coolant Pressure (bar)",
88
+ min_value=0.0, max_value=8.0, value=2.30, step=0.1, format="%.2f", key='cp'
89
+ )
90
+
91
+ with col3:
92
+ # lub oil temp (float)
93
+ input_data['lub oil temp'] = st.number_input(
94
+ "Lub Oil Temperature (°C)",
95
+ min_value=70.0, max_value=100.0, value=78.0, step=0.1, format="%.2f", key='lot'
96
+ )
97
+ # Coolant temp (float)
98
+ input_data['Coolant temp'] = st.number_input(
99
+ "Coolant Temperature (°C)",
100
+ min_value=70.0, max_value=110.0, value=78.0, step=0.1, format="%.2f", key='ct'
101
+ )
102
+
103
+ # --- Prediction Logic ---
104
+ if st.button("Predict Engine Condition", type="primary"):
105
+ # 1. Get the inputs and save them into a dataframe
106
+ input_df = pd.DataFrame([input_data])
107
+
108
+ # 2. Ensure the order of columns matches the training data (CRITICAL)
109
+ input_df = input_df[INPUT_COLUMNS]
110
+
111
+ # 3. Make Prediction
112
+ try:
113
+ # Predict probability for both classes (0 and 1)
114
+ prediction_proba = model.predict_proba(input_df)[0]
115
+ # Prediction is the class index (0 or 1)
116
+ prediction = model.predict(input_df)[0]
117
+
118
+ # 4. Display Result
119
+ st.markdown("---")
120
+ st.header("Prediction Result")
121
+
122
+ if prediction == 1:
123
+ st.error("🚨 FAULT PREDICTED (Requires Maintenance)")
124
+ st.markdown(f"**Probability of Failure (Class 1):** `{prediction_proba[1]*100:.2f}%`")
125
+ st.markdown("Immediate inspection and preventive maintenance are **strongly recommended** to avoid unexpected breakdown and costly repairs.")
126
+ else:
127
+ st.success("✅ NORMAL OPERATION")
128
+ st.markdown(f"**Probability of Normal Operation (Class 0):** `{prediction_proba[0]*100:.2f}%`")
129
+ st.markdown("The engine is operating within normal parameters. Continue with scheduled monitoring.")
130
+
131
+ st.markdown("---")
132
+ st.caption("Input Data Used for Prediction:")
133
+ st.dataframe(input_df, hide_index=True) # Show the data that was fed to the model
134
+
135
+ except Exception as e:
136
+ st.error(f"An error occurred during prediction. Please check input values. Full error: {e}")
137
+
138
+ else:
139
+ st.warning("Cannot proceed without a successfully loaded model. Please ensure the Decision Tree model exists in the Hugging Face repo.")
hosting.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi, create_repo
2
+ import os
3
+
4
+ api = HfApi(token=os.getenv("HF_PM_TOKEN"))
5
+
6
+ repo_id = "ShaksML/predictive_maintenance"
7
+ repo_type = "space"
8
+
9
+ # Create the Hugging Face Space if it doesn't exist
10
+ try:
11
+ api.repo_info(repo_id=repo_id, repo_type=repo_type)
12
+ print(f"Space '{repo_id}' already exists. Using it.")
13
+ except Exception:
14
+ print(f"Space '{repo_id}' not found. Creating new space...")
15
+ create_repo(repo_id=repo_id, repo_type=repo_type, private=False, token=os.getenv("HF_PM_TOKEN"), space_sdk='docker') # Changed space_sdk to 'docker'
16
+ print(f"Space '{repo_id}' created.")
17
+
18
+ api.upload_folder(
19
+ folder_path="predictive_maintenance/deployment",
20
+ repo_id=repo_id,
21
+ repo_type=repo_type,
22
+ path_in_repo="",
23
+ )
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
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
+ mlflow==3.0.1