saba000farahani commited on
Commit
3895530
·
verified ·
1 Parent(s): 699fbf2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -0
app.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import json
4
+ import joblib
5
+ import tensorflow as tf
6
+ import pandas as pd
7
+ from joblib import load
8
+ from tensorflow.keras.models import load_model
9
+ from sklearn.preprocessing import MinMaxScaler
10
+ import matplotlib.pyplot as plt
11
+ import os
12
+ import sklearn
13
+
14
+ # Display library versions
15
+ print(f"Gradio version: {gr.__version__}")
16
+ print(f"NumPy version: {np.__version__}")
17
+ print(f"Scikit-learn version: {sklearn.__version__}")
18
+ print(f"Joblib version: {joblib.__version__}")
19
+ print(f"TensorFlow version: {tf.__version__}")
20
+ print(f"Pandas version: {pd.__version__}")
21
+
22
+ # Directory paths for the saved models
23
+ script_dir = os.path.dirname(os.path.abspath(__file__))
24
+ scaler_path = os.path.join(script_dir, 'toolkit', 'scaler_X.json')
25
+ rf_model_path = os.path.join(script_dir, 'toolkit', 'rf_model.joblib')
26
+ mlp_model_path = os.path.join(script_dir, 'toolkit', 'mlp_model.keras')
27
+ meta_model_path = os.path.join(script_dir, 'toolkit', 'meta_model.joblib')
28
+ image_path = os.path.join(script_dir, 'toolkit', 'car.png')
29
+
30
+ # Load the scaler and models
31
+ try:
32
+ # Load the scaler
33
+ with open(scaler_path, 'r') as f:
34
+ scaler_params = json.load(f)
35
+ scaler_X = MinMaxScaler()
36
+ scaler_X.scale_ = np.array(scaler_params["scale_"])
37
+ scaler_X.min_ = np.array(scaler_params["min_"])
38
+ scaler_X.data_min_ = np.array(scaler_params["data_min_"])
39
+ scaler_X.data_max_ = np.array(scaler_params["data_max_"])
40
+ scaler_X.data_range_ = np.array(scaler_params["data_range_"])
41
+ scaler_X.n_features_in_ = scaler_params["n_features_in_"]
42
+ scaler_X.feature_names_in_ = np.array(scaler_params["feature_names_in_"])
43
+
44
+ # Load the models
45
+ loaded_rf_model = load(rf_model_path)
46
+ print("Random Forest model loaded successfully.")
47
+ loaded_mlp_model = load_model(mlp_model_path)
48
+ print("MLP model loaded successfully.")
49
+ loaded_meta_model = load(meta_model_path)
50
+ print("Meta model loaded successfully.")
51
+ except Exception as e:
52
+ print(f"Error loading models or scaler: {e}")
53
+
54
+ def predict_and_plot(velocity, temperature, precipitation, humidity):
55
+ try:
56
+ # Prepare the example data
57
+ example_data = pd.DataFrame({
58
+ 'Velocity(mph)': [velocity],
59
+ 'Temperature': [temperature],
60
+ 'Precipitation': [precipitation],
61
+ 'Humidity': [humidity]
62
+ })
63
+
64
+ # Scale the example data
65
+ example_data_scaled = scaler_X.transform(example_data)
66
+
67
+ # Function to predict contamination levels and gradients
68
+ def predict_contamination_and_gradients(example_data_scaled):
69
+ # Predict using MLP model
70
+ mlp_predictions_contamination, mlp_predictions_gradients = loaded_mlp_model.predict(example_data_scaled)
71
+
72
+ # Predict using RF model
73
+ rf_predictions = loaded_rf_model.predict(example_data_scaled)
74
+
75
+ # Combine predictions for meta model
76
+ combined_features = np.concatenate([np.concatenate([mlp_predictions_contamination, mlp_predictions_gradients], axis=1), rf_predictions], axis=1)
77
+
78
+ # Predict using meta model
79
+ meta_predictions = loaded_meta_model.predict(combined_features)
80
+
81
+ return meta_predictions[:, :6], meta_predictions[:, 6:] # Split predictions into contamination and gradients
82
+
83
+ # Predict contamination levels and gradients for the single example
84
+ contamination_levels, gradients = predict_contamination_and_gradients(example_data_scaled)
85
+
86
+ # Simulate contamination levels at multiple time intervals
87
+ time_intervals = np.arange(0, 3601, 60) # Simulating time intervals from 0 to 600 seconds
88
+
89
+ # Generate simulated contamination levels (linear interpolation between predicted values)
90
+ simulated_contamination_levels = np.array([
91
+ np.linspace(contamination_levels[0][i], contamination_levels[0][i] * 2, len(time_intervals))
92
+ for i in range(contamination_levels.shape[1])
93
+ ]).T
94
+
95
+ # Function to calculate cleaning time using linear interpolation
96
+ def calculate_cleaning_time(time_intervals, contamination_levels, threshold=0.4):
97
+ cleaning_times = []
98
+ for i in range(contamination_levels.shape[1]):
99
+ levels = contamination_levels[:, i]
100
+ for j in range(1, len(levels)):
101
+ if levels[j-1] <= threshold <= levels[j]:
102
+ # Linear interpolation
103
+ t1, t2 = time_intervals[j-1], time_intervals[j]
104
+ c1, c2 = levels[j-1], levels[j]
105
+ cleaning_time = t1 + (threshold - c1) * (t2 - t1) / (c2 - c1)
106
+ cleaning_times.append(cleaning_time)
107
+ break
108
+ else:
109
+ cleaning_times.append(time_intervals[-1]) # If threshold is not reached
110
+ return cleaning_times
111
+
112
+ # Calculate cleaning times for all 6 lidars
113
+ cleaning_times = calculate_cleaning_time(time_intervals, simulated_contamination_levels)
114
+
115
+ # Lidar names
116
+ lidar_names = ['F/L', 'F/R', 'Left', 'Right', 'Roof', 'Rear']
117
+
118
+ # Plot the graph
119
+ fig, ax = plt.subplots(figsize=(12, 8))
120
+
121
+ for i in range(simulated_contamination_levels.shape[1]):
122
+ ax.plot(time_intervals, simulated_contamination_levels[:, i], label=f'{lidar_names[i]}')
123
+ ax.axhline(y=0.4, color='r', linestyle='--', label='Contamination Threshold' if i == 0 else "")
124
+ if i < len(cleaning_times):
125
+ ax.scatter(cleaning_times[i], 0.4, color='k') # Mark the cleaning time point
126
+
127
+ ax.set_title('Contamination Levels Over Time for Each Lidar')
128
+ ax.set_xlabel('Time (seconds)')
129
+ ax.set_ylabel('Contamination Level')
130
+ ax.legend()
131
+ ax.grid(True)
132
+
133
+ # Flatten the results into a single list of 19 outputs (1 plot + 6 contamination + 6 gradients + 6 cleaning times)
134
+ plot_output = fig
135
+ contamination_output = [f"{val * 100:.2f}%" for val in contamination_levels[0]]
136
+ gradients_output = [f"{val:.4f}" for val in gradients[0]]
137
+ cleaning_time_output = [f"{val:.2f}" for val in cleaning_times]
138
+
139
+ return [plot_output] + contamination_output + gradients_output + cleaning_time_output
140
+
141
+ except Exception as e:
142
+ print(f"Error in Gradio interface: {e}")
143
+ return [plt.figure()] + ["Error"] * 18
144
+
145
+ inputs = [
146
+ gr.Slider(minimum=0, maximum=100, value=50, step=0.05, label="Velocity (mph)"),
147
+ gr.Slider(minimum=-2, maximum=30, value=0, step=0.5, label="Temperature (°C)"),
148
+ gr.Slider(minimum=0, maximum=1, value=0, step=0.01, label="Precipitation (inch)"),
149
+ gr.Slider(minimum=0, maximum=100, value=50, label="Humidity (%)")
150
+ ]
151
+
152
+ contamination_outputs = [
153
+ gr.Textbox(label="Front Left Contamination"),
154
+ gr.Textbox(label="Front Right Contamination"),
155
+ gr.Textbox(label="Left Contamination"),
156
+ gr.Textbox(label="Right Contamination"),
157
+ gr.Textbox(label="Roof Contamination"),
158
+ gr.Textbox(label="Rear Contamination")
159
+ ]
160
+
161
+ gradients_outputs = [
162
+ gr.Textbox(label="Front Left Gradient"),
163
+ gr.Textbox(label="Front Right Gradient"),
164
+ gr.Textbox(label="Left Gradient"),
165
+ gr.Textbox(label="Right Gradient"),
166
+ gr.Textbox(label="Roof Gradient"),
167
+ gr.Textbox(label="Rear Gradient")
168
+ ]
169
+
170
+ cleaning_time_outputs = [
171
+ gr.Textbox(label="Front Left Cleaning Time"),
172
+ gr.Textbox(label="Front Right Cleaning Time"),
173
+ gr.Textbox(label="Left Cleaning Time"),
174
+ gr.Textbox(label="Right Cleaning Time"),
175
+ gr.Textbox(label="Roof Cleaning Time"),
176
+ gr.Textbox(label="Rear Cleaning Time")
177
+ ]
178
+
179
+ with gr.Blocks(css=".column-container {height: 100%; display: flex; flex-direction: column; justify-content: space-between;}") as demo:
180
+ gr.Markdown("<h1 style='text-align: center;'>Environmental Factor-Based Contamination, Gradient, & Cleaning Time Prediction</h1>")
181
+ gr.Markdown("This application predicts the contamination levels, gradients, and cleaning times for different parts of a car's LiDAR system based on environmental factors such as velocity, temperature, precipitation, and humidity.")
182
+
183
+ # Top Section: Inputs and Car Image
184
+ with gr.Row():
185
+ with gr.Column(scale=2, elem_classes="column-container"):
186
+ gr.Markdown("### Input Parameters")
187
+ for inp in inputs:
188
+ inp.render()
189
+ submit_button = gr.Button(value="Submit", variant="primary")
190
+ clear_button = gr.Button(value="Clear")
191
+
192
+ with gr.Column(scale=1):
193
+ gr.Markdown("### Location of LiDARs")
194
+ gr.Image(image_path)
195
+
196
+ # Bottom Section: Outputs (Three columns)
197
+ with gr.Row():
198
+ with gr.Column(scale=2):
199
+ gr.Markdown("### Contamination Predictions")
200
+ for out in contamination_outputs:
201
+ out.render()
202
+
203
+ with gr.Column(scale=2):
204
+ gr.Markdown("### Gradient Predictions")
205
+ for out in gradients_outputs:
206
+ out.render()
207
+
208
+ with gr.Column(scale=2):
209
+ gr.Markdown("### Cleaning Time Predictions")
210
+ for out in cleaning_time_outputs:
211
+ out.render()
212
+
213
+ # Graph below the outputs
214
+ with gr.Row():
215
+ plot_output = gr.Plot(label="Contamination Levels Over Time")
216
+
217
+ submit_button.click(
218
+ fn=predict_and_plot,
219
+ inputs=inputs,
220
+ outputs=[plot_output] + contamination_outputs + gradients_outputs + cleaning_time_outputs
221
+ )
222
+ clear_button.click(fn=lambda: None)
223
+
224
+ demo.launch()