dhani10 commited on
Commit
5b111f0
Β·
verified Β·
1 Parent(s): 8c2a293

Initial deploy

Browse files
Files changed (5) hide show
  1. .gitignore +11 -0
  2. README.md +8 -6
  3. app.py +66 -0
  4. model_loader.py +86 -0
  5. requirements.txt +6 -0
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ env/
6
+ venv/
7
+ .venv/
8
+ .DS_Store
9
+ *.csv
10
+ *.pkl
11
+ *.joblib
README.md CHANGED
@@ -1,12 +1,14 @@
1
  ---
2
- title: Predictive Maintenance
3
- emoji: 🏒
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
+ title: Engine Maintenance Prediction
3
+ emoji: πŸ”§
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 3.35.0
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+ # Engine Maintenance Prediction
13
+
14
+ Predict engine condition using ML.
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import os
5
+ import sys
6
+
7
+ sys.path.append('.')
8
+
9
+ try:
10
+ from model_loader import load_engine_model
11
+ print("βœ… Model loader imported!")
12
+ except ImportError as e:
13
+ print(f"Import error for model_loader: {e}")
14
+ class MockModel:
15
+ def predict(self, X):
16
+ return {'prediction': 0, 'probability': 0.50, 'condition': 'Normal'}
17
+ def predict_proba(self, X):
18
+ return np.array([[0.50, 0.50]])
19
+ def load_engine_model(model_name="dhani10/engine-condition-model"):
20
+ print("⚠️ Using Mock Model.")
21
+ return MockModel()
22
+
23
+ # Default model repo (adjust if needed)
24
+ MODEL_REPO = os.getenv("MODEL_REPO", "dhani10/engine-condition-model")
25
+ model = load_engine_model(MODEL_REPO)
26
+ print(f"Model loaded: {type(model)}")
27
+
28
+ def predict_condition(engine_rpm, oil_pressure, fuel_pressure, coolant_pressure, oil_temp, coolant_temp):
29
+ input_data = {
30
+ 'Engine rpm': engine_rpm,
31
+ 'Lub oil pressure': oil_pressure,
32
+ 'Fuel pressure': fuel_pressure,
33
+ 'Coolant pressure': coolant_pressure,
34
+ 'lub oil temp': oil_temp,
35
+ 'Coolant temp': coolant_temp
36
+ }
37
+ result = model.predict(input_data)
38
+ color = "green" if result.get('condition','Error') == 'Normal' else "red"
39
+ emoji = "βœ…" if result.get('condition','Error') == 'Normal' else "⚠️"
40
+ proba = result.get('probability', 0.0)
41
+ return f"<h2 style='color:{color};'>{emoji} {result.get('condition','Error')}</h2><p>Confidence: {proba:.2%}</p>"
42
+
43
+ with gr.Blocks(title="Engine Maintenance Prediction") as demo:
44
+ gr.Markdown("# πŸš€ Engine Maintenance Prediction")
45
+ gr.Markdown("Enter sensor readings to predict engine condition.")
46
+
47
+ with gr.Row():
48
+ with gr.Column():
49
+ engine_rpm = gr.Number(label="Engine RPM", value=791.0, step=1.0)
50
+ oil_pressure = gr.Number(label="Lub Oil Pressure (bar)", value=3.3, step=0.01)
51
+ fuel_pressure = gr.Number(label="Fuel Pressure (bar)", value=6.6, step=0.01)
52
+ coolant_pressure = gr.Number(label="Coolant Pressure (bar)", value=2.3, step=0.01)
53
+ oil_temp = gr.Number(label="Lub Oil Temp (Β°C)", value=77.6, step=0.1)
54
+ coolant_temp = gr.Number(label="Coolant Temp (Β°C)", value=78.4, step=0.1)
55
+ btn = gr.Button("Predict", variant="primary")
56
+ with gr.Column():
57
+ output = gr.HTML(label="Prediction Result")
58
+
59
+ btn.click(
60
+ predict_condition,
61
+ inputs=[engine_rpm, oil_pressure, fuel_pressure, coolant_pressure, oil_temp, coolant_temp],
62
+ outputs=output
63
+ )
64
+
65
+ if __name__ == "__main__":
66
+ demo.launch(server_name="0.0.0.0", server_port=7860)
model_loader.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import joblib
4
+ import os
5
+ from huggingface_hub import hf_hub_download, login
6
+
7
+ class EngineConditionModel:
8
+ def __init__(self, model_name):
9
+ self.model_name = model_name
10
+ self.model = None
11
+ self.scaler = None
12
+ self.features = [
13
+ 'Engine rpm', 'Lub oil pressure', 'Fuel pressure',
14
+ 'Coolant pressure', 'lub oil temp', 'Coolant temp'
15
+ ]
16
+ self.load_model()
17
+
18
+ def load_model(self):
19
+ try:
20
+ hf_token = os.getenv("HF_TOKEN")
21
+ if hf_token:
22
+ try:
23
+ login(token=hf_token)
24
+ except Exception as e:
25
+ print(f"HF login warning: {e}")
26
+
27
+ model_path = hf_hub_download(
28
+ repo_id=self.model_name,
29
+ filename="model/best_engine_model.joblib", # adjust if different
30
+ repo_type="model",
31
+ token=hf_token
32
+ )
33
+ self.model = joblib.load(model_path)
34
+ print("βœ… Loaded model artifact.")
35
+
36
+ # Optional scaler
37
+ try:
38
+ scaler_path = hf_hub_download(
39
+ repo_id=self.model_name,
40
+ filename="scaler.joblib",
41
+ repo_type="model",
42
+ token=hf_token
43
+ )
44
+ self.scaler = joblib.load(scaler_path)
45
+ print("βœ… Loaded scaler.")
46
+ except Exception:
47
+ self.scaler = None
48
+ except Exception as e:
49
+ print(f"❌ HF Hub load error: {e}
50
+ ⚠️ Falling back to dummy model.")
51
+ from sklearn.ensemble import RandomForestClassifier
52
+ self.model = RandomForestClassifier(n_estimators=10, random_state=42)
53
+ X_dummy = np.random.rand(10, len(self.features))
54
+ y_dummy = np.random.randint(0, 2, 10)
55
+ self.model.fit(X_dummy, y_dummy)
56
+ self.scaler = None
57
+
58
+ def preprocess(self, data):
59
+ df = pd.DataFrame([data]) if isinstance(data, dict) else data.copy()
60
+ X = df[self.features]
61
+ if self.scaler is not None:
62
+ return self.scaler.transform(X)
63
+ return X.values
64
+
65
+ def predict(self, data):
66
+ try:
67
+ X = self.preprocess(data)
68
+ pred = int(self.model.predict(X)[0])
69
+ if hasattr(self.model, "predict_proba"):
70
+ proba = self.model.predict_proba(X)
71
+ conf = float(proba[0, 1]) if proba.shape[1] > 1 else float(proba[0, 0])
72
+ else:
73
+ conf = 0.5
74
+ condition = 'Maintenance Required' if pred == 1 else 'Normal'
75
+ return {"prediction": pred, "probability": conf, "condition": condition}
76
+ except Exception as e:
77
+ print(f"❌ Prediction error: {e}")
78
+ return {"prediction": -1, "probability": 0.0, "condition": "Error"}
79
+
80
+ _engine_model_instance = None
81
+
82
+ def load_engine_model(model_name="dhani10/engine-condition-model"):
83
+ global _engine_model_instance
84
+ if _engine_model_instance is None:
85
+ _engine_model_instance = EngineConditionModel(model_name)
86
+ return _engine_model_instance
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=3.35.0
2
+ pandas>=1.5.0
3
+ numpy>=1.21.0
4
+ scikit-learn>=1.0.0
5
+ joblib>=1.2.0
6
+ huggingface-hub>=0.20.0