Sarvamangalak commited on
Commit
b58a070
Β·
verified Β·
1 Parent(s): 1b1f12f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -59
app.py CHANGED
@@ -1,28 +1,32 @@
1
  import gradio as gr
2
  import matplotlib.pyplot as plt
3
- import numpy as np
4
- from PIL import Image
5
  import random
6
 
7
- # -------------------------------
8
- # Global Counters
9
- # -------------------------------
10
  total_vehicles = 0
11
  ev_count = 0
12
- total_co2_saved = 0 # in kg
13
 
14
- # -------------------------------
15
- # CO2 Assumptions
16
- # -------------------------------
17
  DISTANCE_KM = 10
18
  CO2_PER_KM_PETROL = 0.150 # 150g = 0.15kg per km
19
  CO2_SAVED_PER_EV = DISTANCE_KM * CO2_PER_KM_PETROL # 1.5 kg
20
 
 
21
 
22
- # -------------------------------
23
- # Dummy Vehicle Classifier
24
- # Replace this with your YOLO model
25
- # -------------------------------
 
 
 
 
 
 
26
  def classify_vehicle():
27
  vehicle_types = [
28
  "Car",
@@ -34,11 +38,11 @@ def classify_vehicle():
34
  return random.choice(vehicle_types)
35
 
36
 
37
- # -------------------------------
38
- # Dashboard Plot
39
- # -------------------------------
40
  def generate_dashboard():
41
- global total_vehicles, ev_count, total_co2_saved
42
 
43
  non_ev = total_vehicles - ev_count
44
 
@@ -53,36 +57,33 @@ def generate_dashboard():
53
  return fig
54
 
55
 
56
- # -------------------------------
57
- # Main Detection Function
58
- # -------------------------------
59
  def detect_image(image, threshold):
60
 
61
  global total_vehicles, ev_count, total_co2_saved
62
 
63
  if image is None:
64
- return None, "Please upload an image.", \
65
  "### 🚘 Total Vehicles: 0", \
66
  "### ⚑ EV Vehicles: 0", \
67
  "### πŸ“Š EV Adoption Rate: 0%", \
68
  "### 🌱 COβ‚‚ Saved: 0 kg", \
69
- generate_dashboard()
70
 
71
- # Simulated detection
72
  vehicle_type = classify_vehicle()
73
 
74
  total_vehicles += 1
75
-
76
  co2_saved_this = 0
77
 
78
- if vehicle_type.lower() == "electric vehicle":
79
  ev_count += 1
80
  co2_saved_this = CO2_SAVED_PER_EV
81
  total_co2_saved += co2_saved_this
82
 
83
  ev_percent = (ev_count / total_vehicles) * 100
84
 
85
- # Create dummy detection visualization
86
  fig, ax = plt.subplots()
87
  ax.imshow(image)
88
  ax.set_title(f"Detected: {vehicle_type}")
@@ -90,8 +91,8 @@ def detect_image(image, threshold):
90
 
91
  result_text = f"""
92
  Vehicle Type: {vehicle_type}
93
- Confidence Threshold Used: {threshold}
94
- COβ‚‚ Saved (This Vehicle): {co2_saved_this:.2f} kg
95
  """
96
 
97
  total_card = f"### 🚘 Total Vehicles: {total_vehicles}"
@@ -108,48 +109,174 @@ COβ‚‚ Saved (This Vehicle): {co2_saved_this:.2f} kg
108
  ev_card,
109
  percent_card,
110
  co2_card,
111
- dashboard_fig
 
112
  )
113
 
114
 
115
- # -------------------------------
116
- # Gradio UI
117
- # -------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
119
 
120
- gr.Markdown("## 🚦 Smart Vehicle Classification & EV COβ‚‚ Analytics Dashboard")
 
 
 
121
 
122
- slider = gr.Slider(0.3, 1.0, 0.5, step=0.05, label="Confidence Threshold")
123
 
124
- with gr.Row():
125
- img_input = gr.Image(type="pil", label="Upload Vehicle Image")
126
- img_output = gr.Plot(label="Detection Output")
127
 
128
- result_box = gr.Textbox(label="Detection Result", lines=5)
 
 
129
 
130
- # Metric Cards
131
- with gr.Row():
132
- total_card = gr.Markdown("### 🚘 Total Vehicles: 0")
133
- ev_card = gr.Markdown("### ⚑ EV Vehicles: 0")
134
- percent_card = gr.Markdown("### πŸ“Š EV Adoption Rate: 0%")
135
- co2_card = gr.Markdown("### 🌱 COβ‚‚ Saved: 0 kg")
136
 
137
- dashboard_plot = gr.Plot(label="Analytics Dashboard")
 
 
 
 
138
 
139
- detect_btn = gr.Button("πŸ” Detect Vehicle")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- detect_btn.click(
142
- fn=detect_image,
143
- inputs=[img_input, slider],
144
- outputs=[
145
- img_output,
146
- result_box,
147
- total_card,
148
- ev_card,
149
- percent_card,
150
- co2_card,
151
- dashboard_plot
152
- ]
153
- )
154
 
155
  demo.launch()
 
1
  import gradio as gr
2
  import matplotlib.pyplot as plt
3
+ import pandas as pd
4
+ import os
5
  import random
6
 
7
+ # ===============================
8
+ # GLOBAL VARIABLES
9
+ # ===============================
10
  total_vehicles = 0
11
  ev_count = 0
12
+ total_co2_saved = 0
13
 
 
 
 
14
  DISTANCE_KM = 10
15
  CO2_PER_KM_PETROL = 0.150 # 150g = 0.15kg per km
16
  CO2_SAVED_PER_EV = DISTANCE_KM * CO2_PER_KM_PETROL # 1.5 kg
17
 
18
+ FEEDBACK_FILE = "feedback.csv"
19
 
20
+ # Create CSV if not exists
21
+ if not os.path.exists(FEEDBACK_FILE):
22
+ df_init = pd.DataFrame(columns=["Predicted_Label", "Feedback"])
23
+ df_init.to_csv(FEEDBACK_FILE, index=False)
24
+
25
+
26
+ # ===============================
27
+ # DUMMY VEHICLE CLASSIFIER
28
+ # Replace with YOLO model
29
+ # ===============================
30
  def classify_vehicle():
31
  vehicle_types = [
32
  "Car",
 
38
  return random.choice(vehicle_types)
39
 
40
 
41
+ # ===============================
42
+ # DASHBOARD PLOT
43
+ # ===============================
44
  def generate_dashboard():
45
+ global total_vehicles, ev_count
46
 
47
  non_ev = total_vehicles - ev_count
48
 
 
57
  return fig
58
 
59
 
60
+ # ===============================
61
+ # DETECTION FUNCTION
62
+ # ===============================
63
  def detect_image(image, threshold):
64
 
65
  global total_vehicles, ev_count, total_co2_saved
66
 
67
  if image is None:
68
+ return None, "Upload an image first.", \
69
  "### 🚘 Total Vehicles: 0", \
70
  "### ⚑ EV Vehicles: 0", \
71
  "### πŸ“Š EV Adoption Rate: 0%", \
72
  "### 🌱 COβ‚‚ Saved: 0 kg", \
73
+ generate_dashboard(), ""
74
 
 
75
  vehicle_type = classify_vehicle()
76
 
77
  total_vehicles += 1
 
78
  co2_saved_this = 0
79
 
80
+ if vehicle_type == "Electric Vehicle":
81
  ev_count += 1
82
  co2_saved_this = CO2_SAVED_PER_EV
83
  total_co2_saved += co2_saved_this
84
 
85
  ev_percent = (ev_count / total_vehicles) * 100
86
 
 
87
  fig, ax = plt.subplots()
88
  ax.imshow(image)
89
  ax.set_title(f"Detected: {vehicle_type}")
 
91
 
92
  result_text = f"""
93
  Vehicle Type: {vehicle_type}
94
+ Confidence Threshold: {threshold}
95
+ COβ‚‚ Saved (This Detection): {co2_saved_this:.2f} kg
96
  """
97
 
98
  total_card = f"### 🚘 Total Vehicles: {total_vehicles}"
 
109
  ev_card,
110
  percent_card,
111
  co2_card,
112
+ dashboard_fig,
113
+ vehicle_type
114
  )
115
 
116
 
117
+ # ===============================
118
+ # FEEDBACK FUNCTIONS
119
+ # ===============================
120
+ def save_feedback(predicted_label, feedback):
121
+
122
+ df = pd.read_csv(FEEDBACK_FILE)
123
+
124
+ new_row = {
125
+ "Predicted_Label": predicted_label,
126
+ "Feedback": feedback
127
+ }
128
+
129
+ df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
130
+ df.to_csv(FEEDBACK_FILE, index=False)
131
+
132
+ return "βœ… Feedback Saved!"
133
+
134
+
135
+ def calculate_metrics():
136
+
137
+ df = pd.read_csv(FEEDBACK_FILE)
138
+
139
+ if len(df) == 0:
140
+ return "No feedback data available.", None
141
+
142
+ tp = len(df[df["Feedback"] == "Correct"])
143
+ fp = len(df[df["Feedback"] == "Incorrect"])
144
+
145
+ total = len(df)
146
+
147
+ precision = tp / (tp + fp) if (tp + fp) != 0 else 0
148
+ recall = tp / total if total != 0 else 0
149
+
150
+ metrics_text = f"""
151
+ Total Samples: {total}
152
+
153
+ True Positives (Correct): {tp}
154
+ False Positives (Incorrect): {fp}
155
+
156
+ Precision: {precision:.2f}
157
+ Recall: {recall:.2f}
158
+ """
159
+
160
+ fig, ax = plt.subplots()
161
+ matrix = [[tp, fp],
162
+ [0, 0]]
163
+
164
+ ax.imshow(matrix)
165
+ ax.set_xticks([0,1])
166
+ ax.set_yticks([0,1])
167
+ ax.set_xticklabels(["Correct", "Incorrect"])
168
+ ax.set_yticklabels(["Predicted"])
169
+
170
+ for i in range(2):
171
+ for j in range(2):
172
+ ax.text(j, i, matrix[i][j], ha="center", va="center")
173
+
174
+ ax.set_title("Confusion Matrix")
175
+
176
+ return metrics_text, fig
177
+
178
+
179
+ def reset_database():
180
+ df = pd.DataFrame(columns=["Predicted_Label", "Feedback"])
181
+ df.to_csv(FEEDBACK_FILE, index=False)
182
+ return "πŸ—‘ Database Reset Successfully!"
183
+
184
+
185
+ def download_feedback():
186
+ return FEEDBACK_FILE
187
+
188
+
189
+ # ===============================
190
+ # GRADIO UI
191
+ # ===============================
192
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
193
 
194
+ # ----------------------------
195
+ # DETECTION TAB
196
+ # ----------------------------
197
+ with gr.Tab("🚦 Detection System"):
198
 
199
+ gr.Markdown("## Smart Vehicle Classification & EV COβ‚‚ Dashboard")
200
 
201
+ slider = gr.Slider(0.3, 1.0, 0.5, step=0.05, label="Confidence Threshold")
 
 
202
 
203
+ with gr.Row():
204
+ img_input = gr.Image(type="pil", label="Upload Vehicle Image")
205
+ img_output = gr.Plot(label="Detection Output")
206
 
207
+ result_box = gr.Textbox(label="Detection Result", lines=5)
 
 
 
 
 
208
 
209
+ with gr.Row():
210
+ total_card = gr.Markdown("### 🚘 Total Vehicles: 0")
211
+ ev_card = gr.Markdown("### ⚑ EV Vehicles: 0")
212
+ percent_card = gr.Markdown("### πŸ“Š EV Adoption Rate: 0%")
213
+ co2_card = gr.Markdown("### 🌱 COβ‚‚ Saved: 0 kg")
214
 
215
+ dashboard_plot = gr.Plot(label="Analytics Dashboard")
216
+
217
+ predicted_label_state = gr.State()
218
+
219
+ detect_btn = gr.Button("πŸ” Detect Vehicle")
220
+
221
+ detect_btn.click(
222
+ fn=detect_image,
223
+ inputs=[img_input, slider],
224
+ outputs=[
225
+ img_output,
226
+ result_box,
227
+ total_card,
228
+ ev_card,
229
+ percent_card,
230
+ co2_card,
231
+ dashboard_plot,
232
+ predicted_label_state
233
+ ]
234
+ )
235
+
236
+ gr.Markdown("### Provide Feedback")
237
+
238
+ correct_btn = gr.Button("βœ” Correct")
239
+ incorrect_btn = gr.Button("✘ Incorrect")
240
+ feedback_status = gr.Textbox(label="Feedback Status")
241
+
242
+ correct_btn.click(
243
+ fn=save_feedback,
244
+ inputs=[predicted_label_state, gr.State("Correct")],
245
+ outputs=feedback_status
246
+ )
247
+
248
+ incorrect_btn.click(
249
+ fn=save_feedback,
250
+ inputs=[predicted_label_state, gr.State("Incorrect")],
251
+ outputs=feedback_status
252
+ )
253
+
254
+ # ----------------------------
255
+ # ADMIN DASHBOARD TAB
256
+ # ----------------------------
257
+ with gr.Tab("πŸ“Š Admin Dashboard"):
258
+
259
+ gr.Markdown("## Model Evaluation Dashboard")
260
+
261
+ metrics_box = gr.Textbox(label="Evaluation Metrics", lines=10)
262
+ confusion_plot = gr.Plot()
263
+
264
+ evaluate_btn = gr.Button("Calculate Metrics")
265
+
266
+ evaluate_btn.click(
267
+ fn=calculate_metrics,
268
+ outputs=[metrics_box, confusion_plot]
269
+ )
270
+
271
+ gr.Markdown("### Download Feedback CSV")
272
+ download_btn = gr.File()
273
+ download_btn.click(fn=download_feedback, outputs=download_btn)
274
+
275
+ gr.Markdown("### Reset Database")
276
+ reset_btn = gr.Button("Reset Database")
277
+ reset_output = gr.Textbox()
278
+
279
+ reset_btn.click(fn=reset_database, outputs=reset_output)
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
  demo.launch()