Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesFiles changed (3)
- DockerFile+3-6
- app.py+75-54
- hosting.py+1-1
123456 unmodified lines121314151617181920# Use a Python base imageFROM python:3.9-slim# Set the working directory6 unmodified lines# Copy the application scriptCOPY app.py .# Expose the port Streamlit runs onEXPOSE 8501# CRITICAL FIX: Use CMD to combine the execution command and filename# This ensures 'streamlit run app.py' is executed upon container start.CMD ["streamlit", "run", "app.py"]123456 unmodified lines121314151617# Use a standard Python imageFROM python:3.9-slim# Set the working directory6 unmodified lines# Copy the application scriptCOPY app.py .# Command to run the Streamlit app# This is the industry standard for HF Streamlit Docker deploymentsCMD ["streamlit", "run", "app.py"]
3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879803 unmodified linesimport joblibfrom huggingface_hub import hf_hub_downloadMODEL_REPO_ID = "RajendrakumarPachaiappan/engine-predictive-model"MODEL_FILE = "final_random_forest_model.joblib"SCALER_FILE = "standard_scaler.joblib"FEATURE_COLS = ['Engine rpm', 'Lub oil pressure', 'Fuel pressure','Coolant pressure', 'lub oil temp', 'Coolant temp']@st.cache_resourcedef load_model_and_scaler():"""Downloads and loads the model and scaler from Hugging Face Hub."""st.info("Loading model and scaler from Hugging Face Hub...")try:model_path = hf_hub_download(repo_id=MODEL_REPO_ID, filename=MODEL_FILE)model = joblib.load(model_path)scaler_path = hf_hub_download(repo_id=MODEL_REPO_ID, filename=SCALER_FILE)scaler = joblib.load(scaler_path)st.success("Artifacts loaded successfully!")return model, scalerexcept Exception as e:st.error(f"Error loading artifacts from Hugging Face Hub: {e}")return None, Nonemodel, scaler = load_model_and_scaler()# Streamlit UI and Prediction Logicst.set_page_config(page_title="Predictive Maintenance", layout="wide")st.title("Engine Health Predictor")st.markdown("Use the sliders to simulate real-time sensor data and predict the **Engine Condition** (0=Healthy, 1=Faulty).")col1, col2, col3 = st.columns(3)with col1:Engine_rpm = st.slider("Engine RPM (rev/min)", min_value=60, max_value=2300, value=791, step=10)Lub_oil_pressure = st.slider("Lub Oil Pressure (bar)", min_value=0.0, max_value=7.3, value=3.3, step=0.1)Fuel_pressure = st.slider("Fuel Pressure (bar)", min_value=0.0, max_value=22.0, value=6.7, step=0.1)with col2:Coolant_pressure = st.slider("Coolant Pressure (bar)", min_value=0.0, max_value=7.5, value=2.3, step=0.1)Lub_oil_temp = st.slider("Lub Oil Temp (°C)", min_value=71.0, max_value=90.0, value=78.0, step=0.1)Coolant_temp = st.slider("Coolant Temp (°C)", min_value=60.0, max_value=200.0, value=78.5, step=0.5)# Predictionif st.button("Predict Engine Condition", type="primary"):if model and scaler:input_data = pd.DataFrame({'Engine rpm': [Engine_rpm],'Lub oil pressure': [Lub_oil_pressure],'Fuel pressure': [Fuel_pressure],'Coolant pressure': [Coolant_pressure],'lub oil temp': [Lub_oil_temp],'Coolant temp': [Coolant_temp]}, index=[0])scaled_data = scaler.transform(input_data)prediction = model.predict(scaled_data)[0]prediction_proba = model.predict_proba(scaled_data)[0]# Display Resultsst.subheader("Prediction Result:")if prediction == 1:st.error(f"**FAULTY (Requires Maintenance)**")st.markdown(f"**Confidence (Faulty):** `{prediction_proba[1]*100:.2f}%`")st.warning("**Actionable Insight:** The model predicts a high risk of failure. Schedule maintenance immediately.")else:st.success(f"**HEALTHY (Normal Operation)**")st.markdown(f"**Confidence (Healthy):** `{prediction_proba[0]*100:.2f}%`")st.info("Engine is operating within normal parameters. Continue monitoring.")3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001013 unmodified linesimport joblibfrom huggingface_hub import hf_hub_download# --- Configuration ---REPO_ID_MODEL = "RajendrakumarPachaiappan/engine-predictive-model"MODEL_FILE = "final_random_forest_model.joblib"SCALER_FILE = "standard_scaler.joblib"# The feature columns must match the order expected by the scaler (validated against joblib file)FEATURE_COLS = ['Engine_RPM', 'Lub_Oil_Pressure', 'Fuel_Pressure','Coolant_Pressure', 'Lub_Oil_Temperature', 'Coolant_Temperature']# --- Resource Loading Function ---@st.cache_resource(show_spinner=False) # Suppress default spinner since we use custom status messagesdef load_model_and_scaler():"""Downloads and loads the model and scaler from Hugging Face Hub.Does NOT use st. commands inside to avoid initial warnings."""try:# Download files from Hugging Facemodel_path = hf_hub_download(repo_id=REPO_ID_MODEL, filename=MODEL_FILE)model = joblib.load(model_path)scaler_path = hf_hub_download(repo_id=REPO_ID_MODEL, filename=SCALER_FILE)scaler = joblib.load(scaler_path)return model, scalerexcept Exception as e:# Re-raise a descriptive exception for the main script to catchraise Exception(f"Failed to load required artifacts: {e}")# --- Streamlit UI and Prediction Logic ---st.set_page_config(page_title="Predictive Maintenance", layout="wide")st.title("Engine Health Predictor ⚙️")# 1. Load Resources and Display Statusst.info("Loading predictive model and scaler from Hugging Face Hub...")try:# This call triggers the download/cachingmodel, scaler = load_model_and_scaler()st.success("Artifacts loaded successfully! Ready for prediction.")st.markdown("Use the sliders to simulate real-time sensor data and predict the **Engine Condition** (0=Healthy, 1=Faulty).")except Exception as e:# Display error and halt execution if resources fail to loadst.error(f"🔴 Error loading resources: {e}")st.stop()# 2. Input Sliders# Use columns for a cleaner layoutcol1, col2, col3 = st.columns(3)with col1:Engine_RPM = st.slider("Engine RPM (rev/min)", min_value=60, max_value=2300, value=791, step=10)Lub_Oil_Pressure = st.slider("Lub Oil Pressure (bar)", min_value=0.0, max_value=7.3, value=3.3, step=0.1)Fuel_Pressure = st.slider("Fuel Pressure (bar)", min_value=0.0, max_value=22.0, value=6.7, step=0.1)with col2:Coolant_Pressure = st.slider("Coolant Pressure (bar)", min_value=0.0, max_value=7.5, value=2.3, step=0.1)Lub_Oil_Temperature = st.slider("Lub Oil Temp (°C)", min_value=71.0, max_value=90.0, value=78.0, step=0.1)Coolant_Temperature = st.slider("Coolant Temp (°C)", min_value=60.0, max_value=200.0, value=78.5, step=0.5)# 3. Predictionif st.button("Predict Engine Condition", type="primary"):# a. Prepare Inputinput_data = pd.DataFrame({'Engine_RPM': [Engine_RPM],'Lub_Oil_Pressure': [Lub_Oil_Pressure],'Fuel_Pressure': [Fuel_Pressure],'Coolant_Pressure': [Coolant_Pressure],'Lub_Oil_Temperature': [Lub_Oil_Temperature],'Coolant_Temperature': [Coolant_Temperature]})# b. Scale Input# Important: Use FEATURE_COLS to ensure correct order for the scalerinput_scaled = scaler.transform(input_data[FEATURE_COLS])# c. Make Predictionprediction = model.predict(input_scaled)[0]# Get the probability of the *faulty* class (1)prediction_proba = model.predict_proba(input_scaled)[:, 1][0]# d. Display Resultsst.divider()st.subheader("Prediction Result:")if prediction == 1:st.error(f"Engine Condition: **FAULTY** (Probability of Fault: {prediction_proba:.2f}) ⚠️")st.write("Immediate maintenance is recommended to prevent breakdown.")else:st.success(f"Engine Condition: **HEALTHY** (Probability of Fault: {prediction_proba:.2f}) ✅")st.write("Engine is operating normally. Continue regular monitoring.")st.caption("Note: Probability of fault close to 0.5 indicates uncertainty.")
4 unmodified lines5678910114 unmodified linesapi = HfApi(token=os.getenv("HF_TOKEN"))api.upload_folder(folder_path="/content/Predictive_Maintenance_Project/deployment",repo_id="RajendrakumarPachaiappan/EnginePredictionModel",repo_type="space",4 unmodified lines5678910114 unmodified linesapi = HfApi(token=os.getenv("HF_TOKEN"))api.upload_folder(folder_path="/content/Predictive_Maintenance_Project/deployment",repo_id="RajendrakumarPachaiappan/EnginePredictionModel",repo_type="space",
DockerFile+3-6
app.py+75-54
hosting.py+1-1