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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -232
app.py CHANGED
@@ -1,265 +1,155 @@
1
- import io
2
- import cv2
3
  import gradio as gr
4
- import matplotlib
5
- matplotlib.use("Agg")
6
-
7
  import matplotlib.pyplot as plt
8
- import torch
9
  import numpy as np
10
- import sqlite3
11
- import pandas as pd
12
- import pytesseract
13
-
14
  from PIL import Image
15
- from transformers import YolosImageProcessor, YolosForObjectDetection
16
-
17
- # ---------------- CONFIG ----------------
18
-
19
- MODEL_NAME = "nickmuchi/yolos-small-finetuned-license-plate-detection"
20
- BASE_AMT = 100
21
-
22
- # ---------------- DATABASE ----------------
23
-
24
- conn = sqlite3.connect("vehicles.db", check_same_thread=False)
25
- cursor = conn.cursor()
26
-
27
- cursor.execute("""
28
- CREATE TABLE IF NOT EXISTS vehicles (
29
- plate TEXT,
30
- type TEXT,
31
- amount REAL,
32
- time TEXT
33
- )
34
- """)
35
-
36
- cursor.execute("""
37
- CREATE TABLE IF NOT EXISTS feedback (
38
- result TEXT,
39
- feedback TEXT
40
- )
41
- """)
42
-
43
- conn.commit()
44
-
45
- # ---------------- MODEL (Lazy Load) ----------------
46
-
47
- processor = None
48
- model = None
49
-
50
- def load_model():
51
- global processor, model
52
- if processor is None:
53
- processor = YolosImageProcessor.from_pretrained(MODEL_NAME)
54
- model = YolosForObjectDetection.from_pretrained(MODEL_NAME)
55
- model.eval()
56
- return processor, model
57
-
58
- # ---------------- LOGIC ----------------
59
-
60
- def compute_discount(vehicle_type):
61
- if vehicle_type == "EV":
62
- return BASE_AMT * 0.9
63
- return BASE_AMT
64
-
65
- def classify_plate_color(plate_img):
66
- try:
67
- img = np.array(plate_img)
68
- img = cv2.GaussianBlur(img, (5,5), 0)
69
- hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
70
-
71
- green_mask = cv2.inRange(hsv, (35, 40, 40), (85, 255, 255))
72
- yellow_mask = cv2.inRange(hsv, (15, 50, 50), (35, 255, 255))
73
- white_mask = cv2.inRange(hsv, (0, 0, 200), (180, 40, 255))
74
-
75
- green = np.sum(green_mask)
76
- yellow = np.sum(yellow_mask)
77
- white = np.sum(white_mask)
78
-
79
- if green > yellow and green > white:
80
- return "EV"
81
- elif yellow > green and yellow > white:
82
- return "Commercial"
83
- elif white > green and white > yellow:
84
- return "Personal"
85
- else:
86
- return "Unknown"
87
-
88
- except Exception as e:
89
- return "Unknown"
90
-
91
- def read_plate(plate_img):
92
- try:
93
- gray = cv2.cvtColor(np.array(plate_img), cv2.COLOR_RGB2GRAY)
94
- gray = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)[1]
95
-
96
- text = pytesseract.image_to_string(
97
- gray,
98
- config="--psm 7 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
99
- )
100
- return text.strip() if text.strip() else "UNKNOWN"
101
- except:
102
- return "UNKNOWN"
103
-
104
- def make_prediction(img):
105
- processor, model = load_model()
106
- inputs = processor(images=img, return_tensors="pt")
107
-
108
- with torch.no_grad():
109
- outputs = model(**inputs)
110
-
111
- img_size = torch.tensor([img.size[::-1]])
112
- results = processor.post_process_object_detection(
113
- outputs, threshold=0.3, target_sizes=img_size
114
- )
115
-
116
- return results[0], model.config.id2label
117
-
118
- # ---------------- VISUALIZATION ----------------
119
-
120
- def visualize(img, output, id2label, threshold):
121
- try:
122
- keep = output["scores"] > threshold
123
- boxes = output["boxes"][keep]
124
- labels = output["labels"][keep]
125
-
126
- fig, ax = plt.subplots(figsize=(6,6))
127
- ax.imshow(img)
128
- results_text = []
129
 
130
- for box, label in zip(boxes, labels):
131
- label_name = id2label[label.item()].lower()
132
-
133
- if "plate" not in label_name:
134
- continue
135
-
136
- x1,y1,x2,y2 = map(int, box.tolist())
137
- plate_img = img.crop((x1,y1,x2,y2))
138
-
139
- plate = read_plate(plate_img)
140
- vtype = classify_plate_color(plate_img)
141
- toll = compute_discount(vtype)
142
 
143
- cursor.execute(
144
- "INSERT INTO vehicles VALUES (?, ?, ?, datetime('now'))",
145
- (plate, vtype, toll)
146
- )
147
- conn.commit()
148
 
149
- results_text.append(f"{plate} | {vtype} | β‚Ή{int(toll)}")
 
 
 
150
 
151
- ax.add_patch(
152
- plt.Rectangle((x1,y1), x2-x1, y2-y1,
153
- fill=False, color="red", linewidth=2)
154
- )
155
- ax.text(x1, y1-5, f"{plate} ({vtype})",
156
- color="yellow", fontsize=8)
157
 
158
- ax.axis("off")
 
 
 
 
 
 
159
 
160
- if not results_text:
161
- return fig, "No plate detected"
162
 
163
- return fig, "\n".join(results_text)
164
 
165
- except Exception as e:
166
- return None, f"Error: {str(e)}"
167
 
168
- # ---------------- DASHBOARD ----------------
 
 
 
169
 
170
- def get_dashboard():
171
- df = pd.read_sql("SELECT * FROM vehicles", conn)
172
- fig, ax = plt.subplots(figsize=(8,5))
173
 
174
- if df.empty:
175
- ax.text(0.5, 0.5, "No vehicle data yet",
176
- ha="center", va="center", fontsize=12)
177
- ax.axis("off")
178
- return fig
179
 
180
- counts = df["type"].value_counts()
 
 
 
 
181
 
182
- counts.plot(kind="bar", ax=ax)
 
 
 
183
 
184
- ax.set_title("Vehicle Classification Distribution", fontsize=12)
185
- ax.set_xlabel("Vehicle Type")
186
- ax.set_ylabel("Number of Vehicles")
187
- ax.tick_params(axis='x', rotation=30)
188
 
189
- plt.tight_layout()
190
- return fig
 
 
 
 
 
 
 
191
 
192
- def detect_image(img, threshold):
193
- if img is None:
194
- return None, "No image provided"
195
- output, id2label = make_prediction(img)
196
- return visualize(img, output, id2label, threshold)
197
 
198
- # ---------------- UI ----------------
 
 
 
199
 
200
- with gr.Blocks() as demo:
201
- gr.Markdown("## 🚦 Smart Vehicle Classification System")
202
 
203
- slider = gr.Slider(0.3, 1.0, 0.5, label="Confidence Threshold")
204
 
205
  with gr.Row():
206
- img_input = gr.Image(type="pil")
207
- img_output = gr.Plot()
208
-
209
- result_box = gr.Textbox(label="Detection Result", lines=4)
210
 
211
- dashboard_plot = gr.Plot()
212
- detect_btn.click(
213
- detect_image,
214
- inputs=[img_input, slider],
215
- outputs=[img_output, result_box, dashboard_plot]
216
- )
217
-
218
- gr.Markdown("### Feedback")
219
- feedback_radio = gr.Radio(["Correct", "Incorrect"], label="Prediction correct?")
220
- feedback_btn = gr.Button("Submit Feedback")
221
- feedback_msg = gr.Textbox(label="Feedback Status")
222
-
223
- feedback_btn.click(
224
- submit_feedback,
225
- inputs=[result_box, feedback_radio],
226
- outputs=feedback_msg
227
- )
228
-
229
- gr.Markdown("### Model Accuracy")
230
- accuracy_btn = gr.Button("Show Accuracy")
231
- accuracy_box = gr.Textbox(label="Accuracy")
232
-
233
- accuracy_btn.click(show_accuracy, outputs=accuracy_box)
234
 
235
- gr.Markdown("### πŸ“Š Dashboard")
236
- dashboard_plot = gr.Plot()
 
 
 
 
237
 
238
- # ---------------- FEEDBACK ----------------
239
 
240
- def submit_feedback(result_text, feedback_choice):
241
- if not result_text:
242
- return "No result available."
243
 
244
- cursor.execute(
245
- "INSERT INTO feedback VALUES (?, ?)",
246
- (result_text, feedback_choice)
 
 
 
 
 
 
 
 
 
247
  )
248
- conn.commit()
249
- return "Feedback recorded!"
250
-
251
- def show_accuracy():
252
- df = pd.read_sql("SELECT * FROM feedback", conn)
253
-
254
- if df.empty:
255
- return "No feedback yet."
256
-
257
- correct = len(df[df["feedback"] == "Correct"])
258
- total = len(df)
259
-
260
- accuracy = (correct / total) * 100
261
- return f"Accuracy (User Feedback Based): {accuracy:.2f}%"
262
-
263
- # ---------------- CALLBACK ----------------
264
 
265
  demo.launch()
 
 
 
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",
29
+ "Bus",
30
+ "Truck",
31
+ "Motorcycle",
32
+ "Electric Vehicle"
33
+ ]
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
+
45
+ fig, ax = plt.subplots()
46
+ labels = ["EV", "Non-EV"]
47
+ values = [ev_count, non_ev]
48
+
49
+ ax.bar(labels, values)
50
+ ax.set_title("Vehicle Distribution")
51
+ ax.set_ylabel("Count")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
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}")
89
+ ax.axis("off")
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}"
98
+ ev_card = f"### ⚑ EV Vehicles: {ev_count}"
99
+ percent_card = f"### πŸ“Š EV Adoption Rate: {ev_percent:.2f}%"
100
+ co2_card = f"### 🌱 COβ‚‚ Saved: {total_co2_saved:.2f} kg"
101
 
102
+ dashboard_fig = generate_dashboard()
 
 
 
103
 
104
+ return (
105
+ fig,
106
+ result_text,
107
+ total_card,
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()