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
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author Sarvamangala Kokatanur
2
+ # Import libraries
3
+ import gradio as gr
4
+ import torch
5
+ import numpy as np
6
+ import cv2
7
+ import sqlite3
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+
11
+ from datetime import datetime, timedelta
12
+
13
+ from PIL import Image, ImageDraw
14
+
15
+ from transformers import (
16
+ YolosImageProcessor,
17
+ YolosForObjectDetection
18
+ )
19
+
20
+ # Load model
21
+ processor = YolosImageProcessor.from_pretrained(
22
+ "nickmuchi/yolos-small-finetuned-license-plate-detection"
23
+ )
24
+ model = YolosForObjectDetection.from_pretrained(
25
+ "nickmuchi/yolos-small-finetuned-license-plate-detection"
26
+ )
27
+ model.eval()
28
+ # ---------------- DATABASE ----------------
29
+
30
+ conn = sqlite3.connect(
31
+ "vehicles.db",
32
+ check_same_thread=False
33
+ )
34
+
35
+ cursor = conn.cursor()
36
+
37
+ cursor.execute("""
38
+ CREATE TABLE IF NOT EXISTS vehicles(
39
+
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+
42
+ timestamp TEXT,
43
+
44
+ license_plate TEXT,
45
+
46
+ vehicle_status TEXT,
47
+
48
+ discount INTEGER
49
+
50
+ )
51
+ """)
52
+
53
+ conn.commit()
54
+
55
+ # -------- Plate Color Classifier -------- #
56
+ def classify_plate_color(plate_img):
57
+
58
+ img = np.array(plate_img)
59
+
60
+ # Convert RGB → HSV
61
+ hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
62
+
63
+ h, w = hsv.shape[:2]
64
+
65
+ # Only inspect the left 20% of the plate
66
+ left = hsv[:, :int(w*0.2)]
67
+
68
+ # Green mask
69
+ green = cv2.inRange(
70
+ left,
71
+ (35, 40, 40),
72
+ (90, 255, 255)
73
+ )
74
+
75
+ green_ratio = np.count_nonzero(green) / green.size
76
+
77
+ # If more than 15% of the left strip is green,
78
+ # classify as EV
79
+ if green_ratio > 0.15:
80
+ return "EV"
81
+
82
+ return "Non-EV"
83
+
84
+ # Avoid duplicate vehicle details to the dashboard
85
+
86
+ def is_duplicate_vehicle(plate_number):
87
+
88
+ cursor.execute("""
89
+ SELECT timestamp
90
+ FROM vehicles
91
+ WHERE license_plate=?
92
+ ORDER BY id DESC
93
+ LIMIT 1
94
+ """,(plate_number,))
95
+
96
+ row = cursor.fetchone()
97
+
98
+ if row is None:
99
+ return False
100
+
101
+ last_time = datetime.strptime(
102
+ row[0],
103
+ "%Y-%m-%d %H:%M:%S"
104
+ )
105
+
106
+ if datetime.now() - last_time < timedelta(minutes=5):
107
+
108
+ return True
109
+
110
+ return False
111
+
112
+ # to save vehicle details in the database
113
+
114
+ def save_vehicle(plate,status):
115
+
116
+ if status=="EV":
117
+ discount=50
118
+ else:
119
+ discount=0
120
+
121
+ if is_duplicate_vehicle(plate):
122
+ return "Duplicate"
123
+
124
+ current_time=datetime.now().strftime(
125
+ "%Y-%m-%d %H:%M:%S"
126
+ )
127
+
128
+ cursor.execute("""
129
+
130
+ INSERT INTO vehicles(
131
+
132
+ timestamp,
133
+
134
+ license_plate,
135
+
136
+ vehicle_status,
137
+
138
+ discount
139
+
140
+ )
141
+
142
+ VALUES(?,?,?,?)
143
+
144
+ """,
145
+
146
+ (
147
+
148
+ current_time,
149
+
150
+ plate,
151
+
152
+ status,
153
+
154
+ discount
155
+
156
+ ))
157
+
158
+ conn.commit()
159
+ return "Saved"
160
+
161
+ # --------get_dashboard function ------#
162
+ def get_dashboard():
163
+
164
+ df = pd.read_sql(
165
+ "SELECT * FROM vehicles",
166
+ conn
167
+ )
168
+
169
+ fig, axs = plt.subplots(2, 2, figsize=(8, 6))
170
+
171
+ if df.empty:
172
+
173
+ for ax in axs.flatten():
174
+ ax.text(
175
+ 0.5,
176
+ 0.5,
177
+ "No Data Available",
178
+ ha="center",
179
+ va="center",
180
+ fontsize=10
181
+ )
182
+ ax.axis("off")
183
+
184
+ plt.tight_layout()
185
+ return fig
186
+
187
+ status_counts = df["vehicle_status"].value_counts()
188
+
189
+ axs[0,0].bar(
190
+ status_counts.index,
191
+ status_counts.values
192
+ )
193
+
194
+ axs[0,0].set_title("EV vs Non-EV")
195
+ if status_counts.empty:
196
+ plt.tight_layout()
197
+ return fig
198
+
199
+ axs[0,1].pie(
200
+ status_counts.values,
201
+ labels=status_counts.index,
202
+ autopct="%1.1f%%"
203
+ )
204
+
205
+ axs[0,1].set_title("Vehicle Distribution")
206
+
207
+ total_discount = df["discount"].sum()
208
+
209
+ axs[1,0].bar(
210
+ ["Discount"],
211
+ [total_discount]
212
+ )
213
+
214
+ axs[1,0].set_title("Total Discount")
215
+
216
+ axs[1,1].axis("off")
217
+
218
+ report = (
219
+ f"Today's Report\n\n"
220
+ f"Total Vehicles : {len(df)}\n\n"
221
+ f"EV : {len(df[df.vehicle_status=='EV'])}\n\n"
222
+ f"Non-EV : {len(df[df.vehicle_status=='Non-EV'])}\n\n"
223
+ f"Discount Given : ₹{total_discount}"
224
+ )
225
+
226
+ axs[1,1].text(
227
+ 0,
228
+ 1,
229
+ report,
230
+ fontsize=10,
231
+ va="top"
232
+ )
233
+
234
+ plt.tight_layout()
235
+
236
+ plt.close(fig)
237
+ return fig
238
+
239
+ # -------- Main Pipeline -------- #
240
+ def process_image(img):
241
+
242
+ if img is None:
243
+ return (
244
+ None,
245
+ "Please upload an image.",
246
+ "0",
247
+ "0",
248
+ "₹0",
249
+ get_dashboard()
250
+ )
251
+
252
+ image = Image.fromarray(img)
253
+
254
+ inputs = processor(images=image, return_tensors="pt")
255
+
256
+ with torch.no_grad():
257
+ outputs = model(**inputs)
258
+
259
+ target_sizes = torch.tensor([[image.size[1], image.size[0]]])
260
+
261
+ results = processor.post_process_object_detection(
262
+ outputs,
263
+ threshold=0.3,
264
+ target_sizes=target_sizes
265
+ )[0]
266
+
267
+ draw = ImageDraw.Draw(image)
268
+
269
+ ev_count = 0
270
+ non_ev_count = 0
271
+ discount_total = 0
272
+
273
+ output_text = ""
274
+
275
+ # No detection
276
+ if len(results["boxes"]) == 0:
277
+ return (
278
+ image,
279
+ "No license plate detected.",
280
+ "0",
281
+ "0",
282
+ "₹0",
283
+ get_dashboard()
284
+ )
285
+
286
+ # Process each detected plate
287
+ for i, box in enumerate(results["boxes"]):
288
+
289
+ x1, y1, x2, y2 = map(int, box.tolist())
290
+
291
+ plate = image.crop((x1, y1, x2, y2))
292
+
293
+ status = classify_plate_color(plate)
294
+
295
+ # Temporary plate number
296
+ # Replace with OCR later
297
+ plate_number = f"Vehicle_{datetime.now().strftime('%H%M%S%f')}_{i}"
298
+
299
+ saved = save_vehicle(
300
+ plate_number,
301
+ status
302
+ )
303
+
304
+ # Skip duplicate entries
305
+ if saved == "Duplicate":
306
+ continue
307
+
308
+ if status == "EV":
309
+
310
+ ev_count += 1
311
+ discount = 50
312
+ discount_total += discount
313
+
314
+ color = "green"
315
+ label = f"{plate_number}\nEV | ₹{discount}"
316
+
317
+ else:
318
+
319
+ non_ev_count += 1
320
+ discount = 0
321
+
322
+ color = "red"
323
+ label = f"{plate_number}\nNon-EV"
324
+
325
+ # Draw bounding box
326
+ draw.rectangle(
327
+ [x1, y1, x2, y2],
328
+ outline=color,
329
+ width=3
330
+ )
331
+
332
+ # Draw label
333
+ draw.text(
334
+ (x1, max(0, y1 - 30)),
335
+ label,
336
+ fill=color
337
+ )
338
+
339
+ output_text += (
340
+ f"Vehicle {i+1}\n"
341
+ f"Plate : {plate_number}\n"
342
+ f"Status : {status}\n"
343
+ f"Discount : ₹{discount}\n\n"
344
+ )
345
+
346
+ conn.commit()
347
+
348
+ dashboard = get_dashboard()
349
+
350
+ return (
351
+ image,
352
+ output_text,
353
+ str(ev_count),
354
+ str(non_ev_count),
355
+ f"₹{discount_total}",
356
+ dashboard
357
+ )
358
+ # -------- Gradio UI -------- #
359
+ css = """
360
+ .gradio-container{
361
+ max-width:98% !important;
362
+ margin:auto;
363
+ }
364
+
365
+ textarea{
366
+ font-size:15px !important;
367
+ }
368
+
369
+ h1{
370
+ text-align:center;
371
+ }
372
+
373
+ .block{
374
+ border-radius:12px;
375
+ }
376
+
377
+ .gr-image{
378
+ min-height:350px;
379
+ }
380
+ """
381
+ with gr.Blocks(css=css, fill_width=True) as demo:
382
+
383
+ gr.Markdown("# 🚦 Smart Traffic & EV Analytics System")
384
+ gr.Markdown(
385
+ "Automatic License Plate Detection • EV Classification • Discount Calculation"
386
+ )
387
+
388
+ ##################################################
389
+ # TOP SECTION
390
+ ##################################################
391
+
392
+ with gr.Row(equal_height=True):
393
+
394
+ # LEFT
395
+ with gr.Column(scale=1):
396
+
397
+ input_img = gr.Image(
398
+ type="numpy",
399
+ label="Input Image",
400
+ sources=["upload","webcam"],
401
+ height=350
402
+ )
403
+
404
+ btn = gr.Button(
405
+ "🚗 Scan Vehicle",
406
+ variant="primary",
407
+ size="lg"
408
+ )
409
+
410
+ # CENTER
411
+ with gr.Column(scale=1):
412
+
413
+ output_img = gr.Image(
414
+ label="Detection Result",
415
+ height=350
416
+ )
417
+
418
+ # RIGHT
419
+ with gr.Column(scale=1):
420
+
421
+ summary_box = gr.Textbox(
422
+ label="Detection Summary",
423
+ lines=16
424
+ )
425
+
426
+ ##################################################
427
+ # STATISTICS
428
+ ##################################################
429
+
430
+ with gr.Row():
431
+
432
+ ev_box = gr.Textbox(
433
+ label="EV Vehicles"
434
+ )
435
+
436
+ non_ev_box = gr.Textbox(
437
+ label="Non-EV Vehicles"
438
+ )
439
+
440
+ discount_box = gr.Textbox(
441
+ label="Total Discount"
442
+ )
443
+
444
+ ##################################################
445
+ # DASHBOARD
446
+ ##################################################
447
+
448
+ gr.Markdown("## 📊 Today's Traffic Dashboard")
449
+
450
+ dashboard = gr.Plot(
451
+ label="Analytics",
452
+ height=600
453
+ )
454
+
455
+ btn.click(
456
+ fn=process_image,
457
+ inputs=input_img,
458
+ outputs=[
459
+ output_img,
460
+ summary_box,
461
+ ev_box,
462
+ non_ev_box,
463
+ discount_box,
464
+ dashboard
465
+ ]
466
+ )
467
+ if __name__ == "__main__":
468
+ demo.queue()
469
+ demo.launch(
470
+ ssr_mode=False
471
+ )