Sarvamangalak commited on
Commit
c9e09d0
·
verified ·
1 Parent(s): de1ade4

Delete app_error2_2models.py

Browse files
Files changed (1) hide show
  1. app_error2_2models.py +0 -390
app_error2_2models.py DELETED
@@ -1,390 +0,0 @@
1
- import gradio as gr
2
- import torch
3
- import numpy as np
4
- import cv2
5
- import sqlite3
6
- import pandas as pd
7
- import matplotlib.pyplot as plt
8
- from PIL import Image, ImageDraw
9
- from transformers import YolosImageProcessor, YolosForObjectDetection
10
- import easyocr
11
- from datetime import datetime
12
-
13
- # -------------------- Database --------------------
14
- conn = sqlite3.connect("vehicles.db", check_same_thread=False)
15
- cursor = conn.cursor()
16
- cursor.execute("""
17
- CREATE TABLE IF NOT EXISTS vehicles (
18
- id INTEGER PRIMARY KEY AUTOINCREMENT,
19
- date TEXT NOT NULL,
20
- time TEXT NOT NULL,
21
- plate TEXT,
22
- vehicle_type TEXT,
23
- is_ev INTEGER NOT NULL DEFAULT 0,
24
- toll REAL DEFAULT 0.0,
25
- parking REAL DEFAULT 0.0,
26
- confidence REAL DEFAULT 0.0
27
- )
28
- """)
29
- conn.commit()
30
-
31
- # -------------------- Models --------------------
32
- processor = YolosImageProcessor.from_pretrained(
33
- "nickmuchi/yolos-small-finetuned-license-plate-detection"
34
- )
35
- model = YolosForObjectDetection.from_pretrained(
36
- "nickmuchi/yolos-small-finetuned-license-plate-detection"
37
- )
38
- model.eval()
39
-
40
- reader = easyocr.Reader(['en'], gpu=False)
41
-
42
-
43
- # -------------------- Vehicle Detection Model --------------------
44
- vehicle_processor = YolosImageProcessor.from_pretrained(
45
- "hustvl/yolos-small"
46
- )
47
-
48
- vehicle_model = YolosForObjectDetection.from_pretrained(
49
- "hustvl/yolos-small"
50
- )
51
-
52
- vehicle_model.eval()
53
-
54
- # -------------------- Plate Color Classifier --------------------
55
- def classify_plate_color(plate_img):
56
- img = np.array(plate_img)
57
- hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
58
-
59
- green = np.sum(cv2.inRange(hsv, (35, 40, 40), (85, 255, 255)))
60
- yellow = np.sum(cv2.inRange(hsv, (15, 50, 50), (35, 255, 255)))
61
- white = np.sum(cv2.inRange(hsv, (0, 0, 200), (180, 30, 255)))
62
-
63
- if green > yellow and green > white:
64
- return "EV"
65
- elif yellow > green and yellow > white:
66
- return "Commercial"
67
- else:
68
- return "Personal"
69
-
70
- # -------------------- OCR --------------------
71
- def read_plate(plate_img):
72
- results = reader.readtext(np.array(plate_img))
73
- if results:
74
- return results[0][1]
75
- return "UNKNOWN"
76
-
77
-
78
- # -------------------- Vehicle Detection --------------------
79
-
80
- VEHICLE_CLASSES = {
81
- "car",
82
- "bus",
83
- "truck",
84
- "motorcycle",
85
- "bicycle"
86
- }
87
-
88
- def detect_vehicle_type(image):
89
-
90
- inputs = vehicle_processor(
91
- images=image,
92
- return_tensors="pt"
93
- )
94
-
95
- with torch.no_grad():
96
- outputs = vehicle_model(**inputs)
97
-
98
- results = vehicle_processor.post_process_object_detection(
99
- outputs,
100
- threshold=0.40,
101
- target_sizes=torch.tensor([[image.size[1], image.size[0]]])
102
- )[0]
103
-
104
- best_vehicle = "Unknown"
105
- confidence = 0.0
106
-
107
- for score, label in zip(
108
- results["scores"],
109
- results["labels"]
110
- ):
111
-
112
- cls = vehicle_model.config.id2label[
113
- label.item()
114
- ].lower()
115
-
116
- if cls in VEHICLE_CLASSES:
117
-
118
- if score.item() > confidence:
119
-
120
- confidence = score.item()
121
-
122
- best_vehicle = cls.capitalize()
123
-
124
- return best_vehicle, confidence
125
-
126
- # -------------------- Discount Engine --------------------
127
-
128
- def calculate_discounts(vehicle_type, is_ev):
129
-
130
- toll = 0
131
- parking = 0
132
- incentive = 0
133
-
134
- if is_ev:
135
-
136
- toll = 50
137
-
138
- parking = 100
139
-
140
- if vehicle_type == "Car":
141
- incentive = 10000
142
-
143
- elif vehicle_type == "Bus":
144
- incentive = 50000
145
-
146
- elif vehicle_type == "Truck":
147
- incentive = 75000
148
-
149
- else:
150
- incentive = 5000
151
-
152
- return {
153
-
154
- "toll_discount": toll,
155
-
156
- "parking_discount": parking,
157
-
158
- "government_incentive": incentive
159
-
160
- }
161
-
162
- # -------------------- Dashboard --------------------
163
- def get_dashboard():
164
- df = pd.read_sql("SELECT * FROM vehicles", conn)
165
-
166
- # Larger figure for better readability
167
- fig, ax = plt.subplots(figsize=(6, 4))
168
-
169
- if df.empty:
170
- ax.text(
171
- 0.5,
172
- 0.5,
173
- "No vehicles scanned yet",
174
- ha="center",
175
- va="center",
176
- fontsize=16,
177
- fontweight="bold"
178
- )
179
- ax.axis("off")
180
- return fig
181
-
182
- # Count vehicle types
183
- counts = df["vehicle_type"].value_counts()
184
-
185
- # Create bar chart
186
- bars = ax.bar(
187
- counts.index,
188
- counts.values,
189
- width=0.6
190
- )
191
-
192
- # Titles and labels
193
- ax.set_title(
194
- "Vehicle Classification Dashboard",
195
- fontsize=18,
196
- fontweight="bold",
197
- pad=15
198
- )
199
-
200
- ax.set_xlabel(
201
- "Vehicle Type",
202
- fontsize=14,
203
- fontweight="bold"
204
- )
205
-
206
- ax.set_ylabel(
207
- "Number of Vehicles",
208
- fontsize=14,
209
- fontweight="bold"
210
- )
211
-
212
- # Rotate x-axis labels
213
- plt.xticks(
214
- rotation=30,
215
- ha="right",
216
- fontsize=12
217
- )
218
-
219
- plt.yticks(fontsize=12)
220
-
221
- # Add grid
222
- ax.grid(
223
- axis="y",
224
- linestyle="--",
225
- alpha=0.5
226
- )
227
-
228
- # Display values on top of bars
229
- for bar in bars:
230
- height = bar.get_height()
231
- ax.text(
232
- bar.get_x() + bar.get_width()/2,
233
- height + 0.05,
234
- str(int(height)),
235
- ha="center",
236
- va="bottom",
237
- fontsize=11,
238
- fontweight="bold"
239
- )
240
-
241
- # Add some space above bars
242
- ax.set_ylim(0, max(counts.values) * 1.2)
243
-
244
- # Prevent labels from getting cut off
245
- plt.tight_layout()
246
-
247
- return fig
248
-
249
-
250
- # -------------------- Main Pipeline --------------------
251
- def process_image(img):
252
- image = Image.fromarray(img)
253
-
254
- inputs = processor(images=image, return_tensors="pt")
255
- with torch.no_grad():
256
- outputs = model(**inputs)
257
-
258
- results = processor.post_process_object_detection(
259
- outputs,
260
- threshold=0.3,
261
- target_sizes=torch.tensor([[image.size[1], image.size[0]]])
262
- )[0]
263
-
264
- draw = ImageDraw.Draw(image)
265
-
266
- if len(results["boxes"]) == 0:
267
- return (
268
- image,
269
- plate_text,
270
- vehicle_type,
271
- f"{discount['toll_discount']}%",
272
- f"{discount['parking_discount']}%",
273
- f"₹{discount['government_incentive']}",
274
- get_dashboard()
275
- )
276
-
277
- x1, y1, x2, y2 = map(int, results["boxes"][0].tolist())
278
- plate_img = image.crop((x1, y1, x2, y2))
279
-
280
- plate_text = read_plate(plate_img)
281
-
282
- detected_vehicle, confidence = detect_vehicle_type(image)
283
-
284
- plate_category = classify_plate_color(plate_img)
285
-
286
- is_ev = (plate_category == "EV")
287
-
288
- discount = calculate_discounts(
289
- detected_vehicle,
290
- is_ev
291
- )
292
-
293
- discount = calculate_discounts(
294
- vehicle_type,
295
- is_ev
296
- )
297
-
298
- now = datetime.now()
299
-
300
- cursor.execute("""
301
- INSERT INTO vehicles
302
- (
303
- date,
304
- time,
305
- plate,
306
- vehicle_type,
307
- is_ev,
308
- toll,
309
- parking,
310
- confidence
311
- )
312
- VALUES (?,?,?,?,?,?,?,?)
313
- """,
314
- (
315
- now.strftime("%Y-%m-%d"),
316
- now.strftime("%H:%M:%S"),
317
- plate_text,
318
- vehicle_type,
319
- int(is_ev),
320
- discount["toll_discount"],
321
- discount["parking_discount"],
322
- confidence
323
- ))
324
-
325
- conn.commit()
326
-
327
- draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
328
- draw.text(
329
- (x1, y1-15),
330
- f"{vehicle_type} | {plate_category} | {plate_text}",
331
- fill="red"
332
- )
333
-
334
- return image, plate_text, vehicle_type, get_dashboard()
335
-
336
- # -------------------- Gradio UI --------------------
337
- css = """
338
- textarea {
339
- white-space: pre-wrap !important;
340
- word-break: break-word !important;
341
- overflow-wrap: break-word !important;
342
- }
343
- """
344
-
345
- with gr.Blocks() as demo:
346
- gr.Markdown("## Smart Traffic & EV Analytics System")
347
- gr.Markdown(
348
- "Detects license plates, reads number plate text, "
349
- "classifies EV / Commercial / Personal vehicles, "
350
- "and shows live analytics."
351
- )
352
-
353
- with gr.Row():
354
- input_img = gr.Image(type="numpy", sources=["upload", "webcam"])
355
- output_img = gr.Image()
356
-
357
- with gr.Row():
358
-
359
- plate_box = gr.Textbox(label="Number Plate")
360
- vehicle_type_box = gr.Textbox(label="Vehicle Type")
361
-
362
- with gr.Row():
363
-
364
- toll_box = gr.Textbox(label="Toll Discount")
365
-
366
- parking_box = gr.Textbox(label="Parking Discount")
367
-
368
- incentive_box = gr.Textbox(label="Government Incentive")
369
-
370
- dashboard = gr.Plot(label="Live Vehicle Dashboard")
371
-
372
- btn = gr.Button("Scan Vehicle")
373
- btn.click(
374
- fn=process_image,
375
- inputs=input_img,
376
- outputs=[
377
- output_img,
378
- plate_box,
379
- vehicle_type_box,
380
- toll_box,
381
- parking_box,
382
- incentive_box,
383
- dashboard
384
- ]
385
- )
386
-
387
-
388
- demo.launch()
389
-
390
-