Sarvamangalak commited on
Commit
7c2368f
·
verified ·
1 Parent(s): b1ca7ab

Create app_phase2_review2.py

Browse files
Files changed (1) hide show
  1. app_phase2_review2.py +2067 -0
app_phase2_review2.py ADDED
@@ -0,0 +1,2067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # Smart Traffic & EV Analytics System
3
+ # Agentic AI Dynamic Dashboard
4
+ # Author: Sarvamangala Kokatanur
5
+ # ============================================================
6
+
7
+ # ---------------- IMPORT LIBRARIES ----------------
8
+
9
+ import os
10
+ import json
11
+ import sqlite3
12
+ from datetime import datetime, timedelta
13
+
14
+ import gradio as gr
15
+ import torch
16
+ import numpy as np
17
+ import cv2
18
+ import pandas as pd
19
+ import matplotlib.pyplot as plt
20
+
21
+ from PIL import Image, ImageDraw
22
+
23
+ from transformers import (
24
+ YolosImageProcessor,
25
+ YolosForObjectDetection
26
+ )
27
+
28
+ from huggingface_hub import InferenceClient
29
+
30
+
31
+ # ============================================================
32
+ # CONFIGURATION
33
+ # ============================================================
34
+
35
+ MODEL_NAME = "nickmuchi/yolos-small-finetuned-license-plate-detection"
36
+
37
+ # EV incentive used by this prototype
38
+ EV_DISCOUNT = 50
39
+
40
+ # Hugging Face LLM
41
+ LLM_MODEL = "openai/gpt-oss-120b"
42
+
43
+ # Read Hugging Face token from Space Secret
44
+ HF_TOKEN = os.getenv("HF_TOKEN")
45
+
46
+ llm_client = None
47
+
48
+
49
+ # ============================================================
50
+ # INITIALIZE LLM
51
+ # ============================================================
52
+
53
+ if HF_TOKEN and HF_TOKEN.strip():
54
+
55
+ try:
56
+
57
+ llm_client = InferenceClient(
58
+ token=HF_TOKEN.strip(),
59
+ provider="auto"
60
+ )
61
+
62
+ print("========================================")
63
+ print("✓ Hugging Face LLM initialized")
64
+ print("✓ Model:", LLM_MODEL)
65
+ print("========================================")
66
+
67
+ except Exception as e:
68
+
69
+ print("========================================")
70
+ print("✗ LLM initialization failed")
71
+ print(str(e))
72
+ print("========================================")
73
+
74
+ llm_client = None
75
+
76
+ else:
77
+
78
+ print("========================================")
79
+ print("⚠ HF_TOKEN not found")
80
+ print("Add HF_TOKEN in Hugging Face Space Secrets")
81
+ print("========================================")
82
+
83
+
84
+ # ============================================================
85
+ # LOAD YOLOS LICENSE PLATE MODEL
86
+ # ============================================================
87
+
88
+ print("Loading license plate detection model...")
89
+
90
+ processor = YolosImageProcessor.from_pretrained(
91
+ MODEL_NAME
92
+ )
93
+
94
+ model = YolosForObjectDetection.from_pretrained(
95
+ MODEL_NAME
96
+ )
97
+
98
+ model.eval()
99
+
100
+ print("✓ YOLOS model loaded")
101
+
102
+
103
+ # ============================================================
104
+ # DATABASE
105
+ # ============================================================
106
+
107
+ conn = sqlite3.connect(
108
+ "vehicles.db",
109
+ check_same_thread=False
110
+ )
111
+
112
+ cursor = conn.cursor()
113
+
114
+
115
+ cursor.execute("""
116
+ CREATE TABLE IF NOT EXISTS vehicles(
117
+
118
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
119
+
120
+ timestamp TEXT,
121
+
122
+ license_plate TEXT,
123
+
124
+ vehicle_status TEXT,
125
+
126
+ discount INTEGER
127
+
128
+ )
129
+ """)
130
+
131
+
132
+ conn.commit()
133
+
134
+
135
+ # ============================================================
136
+ # PLATE COLOUR CLASSIFICATION
137
+ # ============================================================
138
+
139
+ def classify_plate_color(plate_img):
140
+
141
+ try:
142
+
143
+ img = np.array(plate_img)
144
+
145
+ if img.size == 0:
146
+ return "Non-EV"
147
+
148
+ # RGB → HSV
149
+ hsv = cv2.cvtColor(
150
+ img,
151
+ cv2.COLOR_RGB2HSV
152
+ )
153
+
154
+ h, w = hsv.shape[:2]
155
+
156
+ if w == 0:
157
+ return "Non-EV"
158
+
159
+ # Inspect the left portion of the plate
160
+ left_width = max(
161
+ 1,
162
+ int(w * 0.20)
163
+ )
164
+
165
+ left = hsv[:, :left_width]
166
+
167
+ # Green colour range
168
+ green = cv2.inRange(
169
+ left,
170
+ (35, 40, 40),
171
+ (90, 255, 255)
172
+ )
173
+
174
+ green_ratio = (
175
+ np.count_nonzero(green)
176
+ / green.size
177
+ )
178
+
179
+ # EV if sufficient green pixels
180
+ if green_ratio > 0.15:
181
+ return "EV"
182
+
183
+ return "Non-EV"
184
+
185
+ except Exception as e:
186
+
187
+ print(
188
+ "Plate colour classification error:",
189
+ e
190
+ )
191
+
192
+ return "Non-EV"
193
+
194
+
195
+ # ============================================================
196
+ # DUPLICATE VEHICLE CHECK
197
+ # ============================================================
198
+
199
+ def is_duplicate_vehicle(plate_number):
200
+
201
+ cursor.execute("""
202
+ SELECT timestamp
203
+ FROM vehicles
204
+ WHERE license_plate=?
205
+ ORDER BY id DESC
206
+ LIMIT 1
207
+ """, (plate_number,))
208
+
209
+ row = cursor.fetchone()
210
+
211
+ if row is None:
212
+ return False
213
+
214
+ try:
215
+
216
+ last_time = datetime.strptime(
217
+ row[0],
218
+ "%Y-%m-%d %H:%M:%S"
219
+ )
220
+
221
+ if (
222
+ datetime.now() - last_time
223
+ < timedelta(minutes=5)
224
+ ):
225
+ return True
226
+
227
+ except Exception:
228
+
229
+ return False
230
+
231
+ return False
232
+
233
+
234
+ # ============================================================
235
+ # SAVE VEHICLE
236
+ # ============================================================
237
+
238
+ def save_vehicle(
239
+ plate,
240
+ status
241
+ ):
242
+
243
+ if status == "EV":
244
+ discount = EV_DISCOUNT
245
+ else:
246
+ discount = 0
247
+
248
+ if is_duplicate_vehicle(plate):
249
+
250
+ return "Duplicate"
251
+
252
+ current_time = datetime.now().strftime(
253
+ "%Y-%m-%d %H:%M:%S"
254
+ )
255
+
256
+ cursor.execute("""
257
+ INSERT INTO vehicles(
258
+ timestamp,
259
+ license_plate,
260
+ vehicle_status,
261
+ discount
262
+ )
263
+ VALUES (?, ?, ?, ?)
264
+ """, (
265
+ current_time,
266
+ plate,
267
+ status,
268
+ discount
269
+ ))
270
+
271
+ conn.commit()
272
+
273
+ return "Saved"
274
+
275
+
276
+ # ============================================================
277
+ # AGENT ANALYTICS TOOL 1
278
+ # OVERALL SUMMARY
279
+ # ============================================================
280
+
281
+ def get_database_summary():
282
+
283
+ df = pd.read_sql(
284
+ "SELECT * FROM vehicles",
285
+ conn
286
+ )
287
+
288
+ if df.empty:
289
+
290
+ return {
291
+ "total_vehicles": 0,
292
+ "ev_vehicles": 0,
293
+ "non_ev_vehicles": 0,
294
+ "ev_percentage": 0,
295
+ "non_ev_percentage": 0,
296
+ "total_discount": 0
297
+ }
298
+
299
+ total = len(df)
300
+
301
+ ev = len(
302
+ df[
303
+ df["vehicle_status"] == "EV"
304
+ ]
305
+ )
306
+
307
+ non_ev = len(
308
+ df[
309
+ df["vehicle_status"] == "Non-EV"
310
+ ]
311
+ )
312
+
313
+ total_discount = int(
314
+ df["discount"].sum()
315
+ )
316
+
317
+ return {
318
+
319
+ "total_vehicles": total,
320
+
321
+ "ev_vehicles": ev,
322
+
323
+ "non_ev_vehicles": non_ev,
324
+
325
+ "ev_percentage": round(
326
+ (ev / total) * 100,
327
+ 2
328
+ ),
329
+
330
+ "non_ev_percentage": round(
331
+ (non_ev / total) * 100,
332
+ 2
333
+ ),
334
+
335
+ "total_discount": total_discount
336
+
337
+ }
338
+
339
+
340
+ # ============================================================
341
+ # AGENT ANALYTICS TOOL 2
342
+ # TODAY'S ANALYSIS
343
+ # ============================================================
344
+
345
+ def get_today_analysis():
346
+
347
+ df = pd.read_sql(
348
+ "SELECT * FROM vehicles",
349
+ conn
350
+ )
351
+
352
+ if df.empty:
353
+
354
+ return {
355
+
356
+ "today_total": 0,
357
+
358
+ "today_ev": 0,
359
+
360
+ "today_non_ev": 0,
361
+
362
+ "today_ev_percentage": 0,
363
+
364
+ "today_discount": 0
365
+
366
+ }
367
+
368
+ df["timestamp"] = pd.to_datetime(
369
+ df["timestamp"],
370
+ errors="coerce"
371
+ )
372
+
373
+ today = datetime.now().date()
374
+
375
+ today_df = df[
376
+ df["timestamp"].dt.date == today
377
+ ]
378
+
379
+ total = len(today_df)
380
+
381
+ ev = len(
382
+ today_df[
383
+ today_df["vehicle_status"] == "EV"
384
+ ]
385
+ )
386
+
387
+ non_ev = len(
388
+ today_df[
389
+ today_df["vehicle_status"] == "Non-EV"
390
+ ]
391
+ )
392
+
393
+ discount = int(
394
+ today_df["discount"].sum()
395
+ )
396
+
397
+ ev_percentage = (
398
+ round((ev / total) * 100, 2)
399
+ if total > 0
400
+ else 0
401
+ )
402
+
403
+ return {
404
+
405
+ "today_total": total,
406
+
407
+ "today_ev": ev,
408
+
409
+ "today_non_ev": non_ev,
410
+
411
+ "today_ev_percentage": ev_percentage,
412
+
413
+ "today_discount": discount
414
+
415
+ }
416
+
417
+
418
+ # ============================================================
419
+ # AGENT ANALYTICS TOOL 3
420
+ # EV ANALYSIS
421
+ # ============================================================
422
+
423
+ def get_ev_analysis():
424
+
425
+ df = pd.read_sql(
426
+ "SELECT * FROM vehicles",
427
+ conn
428
+ )
429
+
430
+ if df.empty:
431
+
432
+ return {
433
+
434
+ "total_vehicles": 0,
435
+
436
+ "ev_vehicles": 0,
437
+
438
+ "non_ev_vehicles": 0,
439
+
440
+ "ev_percentage": 0,
441
+
442
+ "non_ev_percentage": 0,
443
+
444
+ "ev_discount": 0
445
+
446
+ }
447
+
448
+ total = len(df)
449
+
450
+ ev_df = df[
451
+ df["vehicle_status"] == "EV"
452
+ ]
453
+
454
+ non_ev_df = df[
455
+ df["vehicle_status"] == "Non-EV"
456
+ ]
457
+
458
+ ev_count = len(ev_df)
459
+
460
+ non_ev_count = len(non_ev_df)
461
+
462
+ ev_percentage = round(
463
+ ev_count / total * 100,
464
+ 2
465
+ )
466
+
467
+ non_ev_percentage = round(
468
+ non_ev_count / total * 100,
469
+ 2
470
+ )
471
+
472
+ ev_discount = int(
473
+ ev_df["discount"].sum()
474
+ )
475
+
476
+ return {
477
+
478
+ "total_vehicles": total,
479
+
480
+ "ev_vehicles": ev_count,
481
+
482
+ "non_ev_vehicles": non_ev_count,
483
+
484
+ "ev_percentage": ev_percentage,
485
+
486
+ "non_ev_percentage": non_ev_percentage,
487
+
488
+ "ev_discount": ev_discount
489
+
490
+ }
491
+
492
+
493
+ # ============================================================
494
+ # AGENT ANALYTICS TOOL 4
495
+ # DISCOUNT ANALYSIS
496
+ # ============================================================
497
+
498
+ def get_discount_analysis():
499
+
500
+ df = pd.read_sql(
501
+ "SELECT * FROM vehicles",
502
+ conn
503
+ )
504
+
505
+ if df.empty:
506
+
507
+ return {
508
+
509
+ "total_discount": 0,
510
+
511
+ "ev_count": 0,
512
+
513
+ "discount_per_ev": EV_DISCOUNT
514
+
515
+ }
516
+
517
+ ev_count = len(
518
+ df[
519
+ df["vehicle_status"] == "EV"
520
+ ]
521
+ )
522
+
523
+ total_discount = int(
524
+ df["discount"].sum()
525
+ )
526
+
527
+ return {
528
+
529
+ "total_discount": total_discount,
530
+
531
+ "ev_count": ev_count,
532
+
533
+ "discount_per_ev": EV_DISCOUNT
534
+
535
+ }
536
+
537
+
538
+ # ============================================================
539
+ # AGENT ANALYTICS TOOL 5
540
+ # TRAFFIC TREND
541
+ # ============================================================
542
+
543
+ def get_traffic_trend():
544
+
545
+ df = pd.read_sql(
546
+ "SELECT * FROM vehicles",
547
+ conn
548
+ )
549
+
550
+ if df.empty:
551
+ return []
552
+
553
+ df["timestamp"] = pd.to_datetime(
554
+ df["timestamp"],
555
+ errors="coerce"
556
+ )
557
+
558
+ df = df.dropna(
559
+ subset=["timestamp"]
560
+ )
561
+
562
+ if df.empty:
563
+ return []
564
+
565
+ df["date"] = (
566
+ df["timestamp"]
567
+ .dt.strftime("%Y-%m-%d")
568
+ )
569
+
570
+ trend = (
571
+ df.groupby("date")
572
+ .size()
573
+ .reset_index(
574
+ name="vehicles"
575
+ )
576
+ )
577
+
578
+ return trend.to_dict(
579
+ orient="records"
580
+ )
581
+
582
+
583
+ # ============================================================
584
+ # AGENT ANALYTICS TOOL 6
585
+ # EV TREND
586
+ # ============================================================
587
+
588
+ def get_ev_trend():
589
+
590
+ df = pd.read_sql(
591
+ "SELECT * FROM vehicles",
592
+ conn
593
+ )
594
+
595
+ if df.empty:
596
+ return []
597
+
598
+ df["timestamp"] = pd.to_datetime(
599
+ df["timestamp"],
600
+ errors="coerce"
601
+ )
602
+
603
+ df = df.dropna(
604
+ subset=["timestamp"]
605
+ )
606
+
607
+ ev_df = df[
608
+ df["vehicle_status"] == "EV"
609
+ ]
610
+
611
+ if ev_df.empty:
612
+ return []
613
+
614
+ ev_df["date"] = (
615
+ ev_df["timestamp"]
616
+ .dt.strftime("%Y-%m-%d")
617
+ )
618
+
619
+ trend = (
620
+ ev_df.groupby("date")
621
+ .size()
622
+ .reset_index(
623
+ name="ev_vehicles"
624
+ )
625
+ )
626
+
627
+ return trend.to_dict(
628
+ orient="records"
629
+ )
630
+
631
+
632
+ # ============================================================
633
+ # AGENT ANALYTICS TOOL 7
634
+ # VEHICLE RECORDS
635
+ # ============================================================
636
+
637
+ def get_vehicle_records():
638
+
639
+ df = pd.read_sql(
640
+ "SELECT * FROM vehicles",
641
+ conn
642
+ )
643
+
644
+ if df.empty:
645
+ return []
646
+
647
+ return df.to_dict(
648
+ orient="records"
649
+ )
650
+
651
+
652
+ # ============================================================
653
+ # AGENT TOOL DEFINITIONS
654
+ # ============================================================
655
+
656
+ AGENT_TOOLS = [
657
+
658
+ "SUMMARY",
659
+
660
+ "TODAY",
661
+
662
+ "EV_ANALYSIS",
663
+
664
+ "DISCOUNT",
665
+
666
+ "TRAFFIC_TREND",
667
+
668
+ "EV_TREND",
669
+
670
+ "RECORDS"
671
+
672
+ ]
673
+
674
+
675
+ # ============================================================
676
+ # LLM AGENT PLANNER
677
+ # ============================================================
678
+
679
+ def choose_agent_tool(user_query):
680
+
681
+ # Fallback when LLM is unavailable
682
+ if llm_client is None:
683
+
684
+ query = user_query.lower()
685
+
686
+ if (
687
+ "trend" in query
688
+ and "ev" in query
689
+ ):
690
+ return "EV_TREND"
691
+
692
+ if "trend" in query:
693
+ return "TRAFFIC_TREND"
694
+
695
+ if (
696
+ "discount" in query
697
+ or "saving" in query
698
+ or "incentive" in query
699
+ ):
700
+ return "DISCOUNT"
701
+
702
+ if (
703
+ "today" in query
704
+ or "current day" in query
705
+ ):
706
+ return "TODAY"
707
+
708
+ if (
709
+ "ev" in query
710
+ or "electric" in query
711
+ or "adoption" in query
712
+ ):
713
+ return "EV_ANALYSIS"
714
+
715
+ if (
716
+ "record" in query
717
+ or "plate" in query
718
+ or "vehicle details" in query
719
+ ):
720
+ return "RECORDS"
721
+
722
+ return "SUMMARY"
723
+
724
+
725
+ system_prompt = """
726
+ You are the planning agent for a Smart Traffic
727
+ and EV Analytics System.
728
+
729
+ Your job is to select exactly ONE analytics tool.
730
+
731
+ Available tools:
732
+
733
+ SUMMARY
734
+ - Overall traffic statistics.
735
+
736
+ TODAY
737
+ - Statistics for today's detected vehicles.
738
+
739
+ EV_ANALYSIS
740
+ - EV count, Non-EV count, EV percentage,
741
+ and EV adoption.
742
+
743
+ DISCOUNT
744
+ - EV incentive, discount and savings.
745
+
746
+ TRAFFIC_TREND
747
+ - Number of vehicles detected over time.
748
+
749
+ EV_TREND
750
+ - Number of EV vehicles detected over time.
751
+
752
+ RECORDS
753
+ - Vehicle records and license plate records.
754
+
755
+ Rules:
756
+
757
+ 1. Select exactly ONE tool.
758
+ 2. Return ONLY the tool name.
759
+ 3. Do not explain your decision.
760
+ 4. Do not return JSON.
761
+ 5. Do not return anything else.
762
+ """
763
+
764
+
765
+ try:
766
+
767
+ response = llm_client.chat.completions.create(
768
+
769
+ model=LLM_MODEL,
770
+
771
+ messages=[
772
+
773
+ {
774
+ "role": "system",
775
+ "content": system_prompt
776
+ },
777
+
778
+ {
779
+ "role": "user",
780
+ "content": user_query
781
+ }
782
+
783
+ ],
784
+
785
+ temperature=0,
786
+
787
+ max_tokens=30
788
+
789
+ )
790
+
791
+ result = (
792
+ response
793
+ .choices[0]
794
+ .message
795
+ .content
796
+ .strip()
797
+ .upper()
798
+ )
799
+
800
+ for tool in AGENT_TOOLS:
801
+
802
+ if tool in result:
803
+
804
+ return tool
805
+
806
+ return "SUMMARY"
807
+
808
+
809
+ except Exception as e:
810
+
811
+ print(
812
+ "Agent planner error:",
813
+ e
814
+ )
815
+
816
+ return "SUMMARY"
817
+
818
+
819
+ # ============================================================
820
+ # EXECUTE SELECTED ANALYTICS TOOL
821
+ # ============================================================
822
+
823
+ def execute_agent_tool(tool):
824
+
825
+ if tool == "SUMMARY":
826
+
827
+ return get_database_summary()
828
+
829
+ elif tool == "TODAY":
830
+
831
+ return get_today_analysis()
832
+
833
+ elif tool == "EV_ANALYSIS":
834
+
835
+ return get_ev_analysis()
836
+
837
+ elif tool == "DISCOUNT":
838
+
839
+ return get_discount_analysis()
840
+
841
+ elif tool == "TRAFFIC_TREND":
842
+
843
+ return get_traffic_trend()
844
+
845
+ elif tool == "EV_TREND":
846
+
847
+ return get_ev_trend()
848
+
849
+ elif tool == "RECORDS":
850
+
851
+ return get_vehicle_records()
852
+
853
+ return get_database_summary()
854
+
855
+
856
+ # ============================================================
857
+ # LLM ANALYST
858
+ # ============================================================
859
+
860
+ def generate_agent_response(
861
+ user_query,
862
+ selected_tool,
863
+ tool_result
864
+ ):
865
+
866
+ if llm_client is None:
867
+
868
+ return (
869
+ "### ⚠️ Agentic AI Not Configured\n\n"
870
+ "The analytics system is working, but the "
871
+ "LLM is not configured.\n\n"
872
+ "**Please add `HF_TOKEN` to the Hugging Face "
873
+ "Space Secrets and restart the Space.**\n\n"
874
+ f"Selected analytics tool: **{selected_tool}**"
875
+ )
876
+
877
+
878
+ system_prompt = f"""
879
+ You are the AI analyst of a Smart Traffic
880
+ and EV Analytics System.
881
+
882
+ The system contains:
883
+
884
+ 1. YOLOS license plate detection
885
+ 2. OpenCV license plate colour analysis
886
+ 3. EV / Non-EV classification
887
+ 4. License plate recognition
888
+ 5. EV discount calculation
889
+ 6. SQLite traffic analytics
890
+ 7. Agentic AI analytics
891
+
892
+ The prototype gives an EV incentive of ₹{EV_DISCOUNT}.
893
+
894
+ The user asked a question.
895
+
896
+ An analytics agent selected one tool:
897
+
898
+ {selected_tool}
899
+
900
+ You MUST use only the supplied analytics result.
901
+
902
+ Do not invent data.
903
+
904
+ Do not estimate missing values.
905
+
906
+ Do not create statistics that are not present
907
+ in the analytics result.
908
+
909
+ Answer the user's question directly.
910
+
911
+ Use this structure when appropriate:
912
+
913
+ **Answer**
914
+
915
+ Give the direct result.
916
+
917
+ **Key Statistics**
918
+
919
+ Give the relevant numbers.
920
+
921
+ **Interpretation**
922
+
923
+ Explain what the result means.
924
+
925
+ **Recommendation**
926
+
927
+ Give a short recommendation only when useful.
928
+
929
+ Keep the response concise and professional.
930
+ """
931
+
932
+
933
+ prompt = f"""
934
+ User question:
935
+
936
+ {user_query}
937
+
938
+ Selected analytics tool:
939
+
940
+ {selected_tool}
941
+
942
+ Analytics result:
943
+
944
+ {json.dumps(
945
+ tool_result,
946
+ indent=2,
947
+ default=str
948
+ )}
949
+
950
+ Generate the final analytical response.
951
+ """
952
+
953
+
954
+ try:
955
+
956
+ response = llm_client.chat.completions.create(
957
+
958
+ model=LLM_MODEL,
959
+
960
+ messages=[
961
+
962
+ {
963
+ "role": "system",
964
+ "content": system_prompt
965
+ },
966
+
967
+ {
968
+ "role": "user",
969
+ "content": prompt
970
+ }
971
+
972
+ ],
973
+
974
+ temperature=0.2,
975
+
976
+ max_tokens=500
977
+
978
+ )
979
+
980
+ return (
981
+ response
982
+ .choices[0]
983
+ .message
984
+ .content
985
+ .strip()
986
+ )
987
+
988
+
989
+ except Exception as e:
990
+
991
+ print(
992
+ "LLM response error:",
993
+ e
994
+ )
995
+
996
+ return (
997
+ "### ⚠️ LLM Response Error\n\n"
998
+ f"{str(e)}"
999
+ )
1000
+
1001
+
1002
+ # ============================================================
1003
+ # DYNAMIC GRAPH GENERATOR
1004
+ # ============================================================
1005
+
1006
+ def generate_agent_graph(
1007
+ selected_tool
1008
+ ):
1009
+
1010
+ fig, ax = plt.subplots(
1011
+ figsize=(9, 5)
1012
+ )
1013
+
1014
+
1015
+ # --------------------------------------------------------
1016
+ # SUMMARY / EV ANALYSIS
1017
+ # --------------------------------------------------------
1018
+
1019
+ if selected_tool in [
1020
+ "SUMMARY",
1021
+ "EV_ANALYSIS"
1022
+ ]:
1023
+
1024
+ result = get_database_summary()
1025
+
1026
+ labels = [
1027
+ "EV",
1028
+ "Non-EV"
1029
+ ]
1030
+
1031
+ values = [
1032
+
1033
+ result["ev_vehicles"],
1034
+
1035
+ result["non_ev_vehicles"]
1036
+
1037
+ ]
1038
+
1039
+ ax.bar(
1040
+ labels,
1041
+ values
1042
+ )
1043
+
1044
+ ax.set_title(
1045
+ "EV vs Non-EV Vehicles"
1046
+ )
1047
+
1048
+ ax.set_ylabel(
1049
+ "Number of Vehicles"
1050
+ )
1051
+
1052
+ for i, value in enumerate(values):
1053
+
1054
+ ax.text(
1055
+ i,
1056
+ value,
1057
+ str(value),
1058
+ ha="center",
1059
+ va="bottom"
1060
+ )
1061
+
1062
+
1063
+ # --------------------------------------------------------
1064
+ # TODAY
1065
+ # --------------------------------------------------------
1066
+
1067
+ elif selected_tool == "TODAY":
1068
+
1069
+ result = get_today_analysis()
1070
+
1071
+ labels = [
1072
+ "EV",
1073
+ "Non-EV"
1074
+ ]
1075
+
1076
+ values = [
1077
+
1078
+ result["today_ev"],
1079
+
1080
+ result["today_non_ev"]
1081
+
1082
+ ]
1083
+
1084
+ ax.bar(
1085
+ labels,
1086
+ values
1087
+ )
1088
+
1089
+ ax.set_title(
1090
+ "Today's Traffic"
1091
+ )
1092
+
1093
+ ax.set_ylabel(
1094
+ "Vehicles"
1095
+ )
1096
+
1097
+ for i, value in enumerate(values):
1098
+
1099
+ ax.text(
1100
+ i,
1101
+ value,
1102
+ str(value),
1103
+ ha="center",
1104
+ va="bottom"
1105
+ )
1106
+
1107
+
1108
+ # --------------------------------------------------------
1109
+ # DISCOUNT
1110
+ # --------------------------------------------------------
1111
+
1112
+ elif selected_tool == "DISCOUNT":
1113
+
1114
+ result = get_discount_analysis()
1115
+
1116
+ discount = result[
1117
+ "total_discount"
1118
+ ]
1119
+
1120
+ ax.bar(
1121
+ ["Total EV Discount"],
1122
+ [discount]
1123
+ )
1124
+
1125
+ ax.set_title(
1126
+ "EV Incentive / Discount"
1127
+ )
1128
+
1129
+ ax.set_ylabel(
1130
+ "Discount (₹)"
1131
+ )
1132
+
1133
+ ax.text(
1134
+ 0,
1135
+ discount,
1136
+ f"₹{discount}",
1137
+ ha="center",
1138
+ va="bottom"
1139
+ )
1140
+
1141
+
1142
+ # --------------------------------------------------------
1143
+ # TRAFFIC TREND
1144
+ # --------------------------------------------------------
1145
+
1146
+ elif selected_tool == "TRAFFIC_TREND":
1147
+
1148
+ records = get_traffic_trend()
1149
+
1150
+ if not records:
1151
+
1152
+ ax.text(
1153
+ 0.5,
1154
+ 0.5,
1155
+ "No traffic trend data available",
1156
+ ha="center",
1157
+ va="center"
1158
+ )
1159
+
1160
+ ax.axis("off")
1161
+
1162
+ else:
1163
+
1164
+ dates = [
1165
+ item["date"]
1166
+ for item in records
1167
+ ]
1168
+
1169
+ vehicles = [
1170
+ item["vehicles"]
1171
+ for item in records
1172
+ ]
1173
+
1174
+ ax.plot(
1175
+ dates,
1176
+ vehicles,
1177
+ marker="o"
1178
+ )
1179
+
1180
+ ax.set_title(
1181
+ "Traffic Trend"
1182
+ )
1183
+
1184
+ ax.set_xlabel(
1185
+ "Date"
1186
+ )
1187
+
1188
+ ax.set_ylabel(
1189
+ "Vehicles"
1190
+ )
1191
+
1192
+ ax.tick_params(
1193
+ axis="x",
1194
+ rotation=45
1195
+ )
1196
+
1197
+
1198
+ # --------------------------------------------------------
1199
+ # EV TREND
1200
+ # --------------------------------------------------------
1201
+
1202
+ elif selected_tool == "EV_TREND":
1203
+
1204
+ records = get_ev_trend()
1205
+
1206
+ if not records:
1207
+
1208
+ ax.text(
1209
+ 0.5,
1210
+ 0.5,
1211
+ "No EV trend data available",
1212
+ ha="center",
1213
+ va="center"
1214
+ )
1215
+
1216
+ ax.axis("off")
1217
+
1218
+ else:
1219
+
1220
+ dates = [
1221
+ item["date"]
1222
+ for item in records
1223
+ ]
1224
+
1225
+ ev_values = [
1226
+ item["ev_vehicles"]
1227
+ for item in records
1228
+ ]
1229
+
1230
+ ax.plot(
1231
+ dates,
1232
+ ev_values,
1233
+ marker="o"
1234
+ )
1235
+
1236
+ ax.set_title(
1237
+ "EV Adoption Trend"
1238
+ )
1239
+
1240
+ ax.set_xlabel(
1241
+ "Date"
1242
+ )
1243
+
1244
+ ax.set_ylabel(
1245
+ "EV Vehicles"
1246
+ )
1247
+
1248
+ ax.tick_params(
1249
+ axis="x",
1250
+ rotation=45
1251
+ )
1252
+
1253
+
1254
+ # --------------------------------------------------------
1255
+ # RECORDS
1256
+ # --------------------------------------------------------
1257
+
1258
+ elif selected_tool == "RECORDS":
1259
+
1260
+ result = get_database_summary()
1261
+
1262
+ labels = [
1263
+ "EV",
1264
+ "Non-EV"
1265
+ ]
1266
+
1267
+ values = [
1268
+
1269
+ result["ev_vehicles"],
1270
+
1271
+ result["non_ev_vehicles"]
1272
+
1273
+ ]
1274
+
1275
+ ax.bar(
1276
+ labels,
1277
+ values
1278
+ )
1279
+
1280
+ ax.set_title(
1281
+ "Vehicle Records"
1282
+ )
1283
+
1284
+ ax.set_ylabel(
1285
+ "Number of Records"
1286
+ )
1287
+
1288
+
1289
+ else:
1290
+
1291
+ ax.text(
1292
+ 0.5,
1293
+ 0.5,
1294
+ "No visualization available",
1295
+ ha="center",
1296
+ va="center"
1297
+ )
1298
+
1299
+ ax.axis("off")
1300
+
1301
+
1302
+ plt.tight_layout()
1303
+
1304
+ return fig
1305
+
1306
+
1307
+ # ============================================================
1308
+ # RUN AGENTIC DASHBOARD
1309
+ # ============================================================
1310
+
1311
+ def run_agentic_dashboard(
1312
+ user_query
1313
+ ):
1314
+
1315
+ if not user_query:
1316
+
1317
+ return (
1318
+
1319
+ "### Please enter a question\n\n"
1320
+ "Ask the Traffic AI Agent a question.",
1321
+
1322
+ None
1323
+
1324
+ )
1325
+
1326
+
1327
+ user_query = user_query.strip()
1328
+
1329
+
1330
+ # --------------------------------------------------------
1331
+ # STEP 1: LLM PLANNER
1332
+ # --------------------------------------------------------
1333
+
1334
+ selected_tool = choose_agent_tool(
1335
+ user_query
1336
+ )
1337
+
1338
+ print(
1339
+ "Agent selected:",
1340
+ selected_tool
1341
+ )
1342
+
1343
+
1344
+ # --------------------------------------------------------
1345
+ # STEP 2: EXECUTE ANALYTICS TOOL
1346
+ # --------------------------------------------------------
1347
+
1348
+ tool_result = execute_agent_tool(
1349
+ selected_tool
1350
+ )
1351
+
1352
+
1353
+ # --------------------------------------------------------
1354
+ # STEP 3: LLM ANALYST
1355
+ # --------------------------------------------------------
1356
+
1357
+ answer = generate_agent_response(
1358
+
1359
+ user_query,
1360
+
1361
+ selected_tool,
1362
+
1363
+ tool_result
1364
+
1365
+ )
1366
+
1367
+
1368
+ # --------------------------------------------------------
1369
+ # STEP 4: GENERATE DYNAMIC GRAPH
1370
+ # --------------------------------------------------------
1371
+
1372
+ graph = generate_agent_graph(
1373
+ selected_tool
1374
+ )
1375
+
1376
+
1377
+ return answer, graph
1378
+
1379
+
1380
+ # ============================================================
1381
+ # MAIN VEHICLE PROCESSING PIPELINE
1382
+ # ============================================================
1383
+
1384
+ def process_image(img):
1385
+
1386
+ if img is None:
1387
+
1388
+ return (
1389
+
1390
+ None,
1391
+
1392
+ "Please upload an image.",
1393
+
1394
+ "0",
1395
+
1396
+ "0",
1397
+
1398
+ "₹0"
1399
+
1400
+ )
1401
+
1402
+
1403
+ try:
1404
+
1405
+ image = Image.fromarray(
1406
+ img
1407
+ ).convert("RGB")
1408
+
1409
+
1410
+ # ----------------------------------------------------
1411
+ # YOLOS PROCESSING
1412
+ # ----------------------------------------------------
1413
+
1414
+ inputs = processor(
1415
+ images=image,
1416
+ return_tensors="pt"
1417
+ )
1418
+
1419
+
1420
+ with torch.no_grad():
1421
+
1422
+ outputs = model(
1423
+ **inputs
1424
+ )
1425
+
1426
+
1427
+ target_sizes = torch.tensor(
1428
+ [
1429
+ [
1430
+ image.size[1],
1431
+ image.size[0]
1432
+ ]
1433
+ ]
1434
+ )
1435
+
1436
+
1437
+ results = (
1438
+ processor
1439
+ .post_process_object_detection(
1440
+ outputs,
1441
+ threshold=0.3,
1442
+ target_sizes=target_sizes
1443
+ )[0]
1444
+ )
1445
+
1446
+
1447
+ draw = ImageDraw.Draw(
1448
+ image
1449
+ )
1450
+
1451
+
1452
+ ev_count = 0
1453
+
1454
+ non_ev_count = 0
1455
+
1456
+ discount_total = 0
1457
+
1458
+ output_text = ""
1459
+
1460
+
1461
+ # ----------------------------------------------------
1462
+ # NO DETECTION
1463
+ # ----------------------------------------------------
1464
+
1465
+ if len(results["boxes"]) == 0:
1466
+
1467
+ return (
1468
+
1469
+ image,
1470
+
1471
+ "No license plate detected.",
1472
+
1473
+ "0",
1474
+
1475
+ "0",
1476
+
1477
+ "₹0"
1478
+
1479
+ )
1480
+
1481
+
1482
+ # ----------------------------------------------------
1483
+ # PROCESS DETECTED PLATES
1484
+ # ----------------------------------------------------
1485
+
1486
+ for i, box in enumerate(
1487
+ results["boxes"]
1488
+ ):
1489
+
1490
+
1491
+ x1, y1, x2, y2 = map(
1492
+ int,
1493
+ box.tolist()
1494
+ )
1495
+
1496
+
1497
+ # Prevent invalid coordinates
1498
+
1499
+ x1 = max(
1500
+ 0,
1501
+ x1
1502
+ )
1503
+
1504
+ y1 = max(
1505
+ 0,
1506
+ y1
1507
+ )
1508
+
1509
+ x2 = min(
1510
+ image.width,
1511
+ x2
1512
+ )
1513
+
1514
+ y2 = min(
1515
+ image.height,
1516
+ y2
1517
+ )
1518
+
1519
+
1520
+ if x2 <= x1 or y2 <= y1:
1521
+
1522
+ continue
1523
+
1524
+
1525
+ # Crop license plate
1526
+
1527
+ plate = image.crop(
1528
+ (
1529
+ x1,
1530
+ y1,
1531
+ x2,
1532
+ y2
1533
+ )
1534
+ )
1535
+
1536
+
1537
+ # ------------------------------------------------
1538
+ # EV / NON-EV CLASSIFICATION
1539
+ # ------------------------------------------------
1540
+
1541
+ status = classify_plate_color(
1542
+ plate
1543
+ )
1544
+
1545
+
1546
+ # ------------------------------------------------
1547
+ # TEMPORARY PLATE NUMBER
1548
+ #
1549
+ # Replace this section with OCR later.
1550
+ # ------------------------------------------------
1551
+
1552
+ plate_number = (
1553
+ f"Vehicle_"
1554
+ f"{datetime.now().strftime('%H%M%S%f')}_"
1555
+ f"{i}"
1556
+ )
1557
+
1558
+
1559
+ # ------------------------------------------------
1560
+ # SAVE DATABASE RECORD
1561
+ # ------------------------------------------------
1562
+
1563
+ saved = save_vehicle(
1564
+ plate_number,
1565
+ status
1566
+ )
1567
+
1568
+
1569
+ if saved == "Duplicate":
1570
+
1571
+ continue
1572
+
1573
+
1574
+ # ------------------------------------------------
1575
+ # EV
1576
+ # ------------------------------------------------
1577
+
1578
+ if status == "EV":
1579
+
1580
+ ev_count += 1
1581
+
1582
+ discount = EV_DISCOUNT
1583
+
1584
+ discount_total += (
1585
+ discount
1586
+ )
1587
+
1588
+ box_color = "green"
1589
+
1590
+ label = (
1591
+ f"{plate_number}\n"
1592
+ f"EV | ₹{discount}"
1593
+ )
1594
+
1595
+
1596
+ # ------------------------------------------------
1597
+ # NON-EV
1598
+ # ------------------------------------------------
1599
+
1600
+ else:
1601
+
1602
+ non_ev_count += 1
1603
+
1604
+ discount = 0
1605
+
1606
+ box_color = "red"
1607
+
1608
+ label = (
1609
+ f"{plate_number}\n"
1610
+ f"Non-EV"
1611
+ )
1612
+
1613
+
1614
+ # ------------------------------------------------
1615
+ # DRAW BOUNDING BOX
1616
+ # ------------------------------------------------
1617
+
1618
+ draw.rectangle(
1619
+
1620
+ [
1621
+ x1,
1622
+ y1,
1623
+ x2,
1624
+ y2
1625
+ ],
1626
+
1627
+ outline=box_color,
1628
+
1629
+ width=3
1630
+
1631
+ )
1632
+
1633
+
1634
+ # ------------------------------------------------
1635
+ # DRAW LABEL
1636
+ # ------------------------------------------------
1637
+
1638
+ draw.text(
1639
+
1640
+ (
1641
+ x1,
1642
+ max(
1643
+ 0,
1644
+ y1 - 35
1645
+ )
1646
+ ),
1647
+
1648
+ label,
1649
+
1650
+ fill=box_color
1651
+
1652
+ )
1653
+
1654
+
1655
+ # ------------------------------------------------
1656
+ # TEXT SUMMARY
1657
+ # ------------------------------------------------
1658
+
1659
+ output_text += (
1660
+
1661
+ f"Vehicle {i + 1}\n"
1662
+
1663
+ f"Plate : "
1664
+ f"{plate_number}\n"
1665
+
1666
+ f"Status : "
1667
+ f"{status}\n"
1668
+
1669
+ f"Discount : "
1670
+ f"₹{discount}\n\n"
1671
+
1672
+ )
1673
+
1674
+
1675
+ # ----------------------------------------------------
1676
+ # DATABASE COMMIT
1677
+ # ----------------------------------------------------
1678
+
1679
+ conn.commit()
1680
+
1681
+
1682
+ # ----------------------------------------------------
1683
+ # IF NO NEW VEHICLES
1684
+ # ----------------------------------------------------
1685
+
1686
+ if (
1687
+ ev_count == 0
1688
+ and non_ev_count == 0
1689
+ ):
1690
+
1691
+ output_text = (
1692
+ "All detected vehicles "
1693
+ "were duplicate records "
1694
+ "within the 5-minute window."
1695
+ )
1696
+
1697
+
1698
+ return (
1699
+
1700
+ image,
1701
+
1702
+ output_text,
1703
+
1704
+ str(ev_count),
1705
+
1706
+ str(non_ev_count),
1707
+
1708
+ f"₹{discount_total}"
1709
+
1710
+ )
1711
+
1712
+
1713
+ except Exception as e:
1714
+
1715
+ print(
1716
+ "Image processing error:",
1717
+ e
1718
+ )
1719
+
1720
+ return (
1721
+
1722
+ img,
1723
+
1724
+ f"Processing error:\n{str(e)}",
1725
+
1726
+ "0",
1727
+
1728
+ "0",
1729
+
1730
+ "₹0"
1731
+
1732
+ )
1733
+
1734
+
1735
+ # ============================================================
1736
+ # CUSTOM CSS
1737
+ # ============================================================
1738
+
1739
+ css = """
1740
+
1741
+ .gradio-container {
1742
+ max-width: 98% !important;
1743
+ margin: auto;
1744
+ }
1745
+
1746
+ textarea {
1747
+ font-size: 15px !important;
1748
+ }
1749
+
1750
+ h1 {
1751
+ text-align: center;
1752
+ }
1753
+
1754
+ .block {
1755
+ border-radius: 12px;
1756
+ }
1757
+
1758
+ .gr-image {
1759
+ min-height: 350px;
1760
+ }
1761
+
1762
+ """
1763
+
1764
+
1765
+ # ============================================================
1766
+ # GRADIO USER INTERFACE
1767
+ # ============================================================
1768
+
1769
+ with gr.Blocks(
1770
+ css=css,
1771
+ title="Smart Traffic & EV Analytics"
1772
+ ) as demo:
1773
+
1774
+
1775
+ # ========================================================
1776
+ # TITLE
1777
+ # ========================================================
1778
+
1779
+ gr.Markdown(
1780
+ """
1781
+ # 🚗 Smart Traffic & EV Analytics System
1782
+
1783
+ ### YOLOS License Plate Detection • OpenCV EV Classification •
1784
+ SQLite Analytics • EV Incentives • Agentic AI Dashboard
1785
+ """
1786
+ )
1787
+
1788
+
1789
+ # ========================================================
1790
+ # IMAGE PROCESSING SECTION
1791
+ # ========================================================
1792
+
1793
+ with gr.Row(
1794
+ equal_height=True
1795
+ ):
1796
+
1797
+
1798
+ # ----------------------------------------------------
1799
+ # INPUT
1800
+ # ----------------------------------------------------
1801
+
1802
+ with gr.Column(
1803
+ scale=1
1804
+ ):
1805
+
1806
+ input_img = gr.Image(
1807
+
1808
+ type="numpy",
1809
+
1810
+ label="Input Image",
1811
+
1812
+ sources=[
1813
+ "upload",
1814
+ "webcam"
1815
+ ],
1816
+
1817
+ height=350
1818
+
1819
+ )
1820
+
1821
+
1822
+ btn = gr.Button(
1823
+
1824
+ " Scan Vehicle",
1825
+
1826
+ variant="primary",
1827
+
1828
+ size="lg"
1829
+
1830
+ )
1831
+
1832
+
1833
+ # ----------------------------------------------------
1834
+ # OUTPUT IMAGE
1835
+ # ----------------------------------------------------
1836
+
1837
+ with gr.Column(
1838
+ scale=1
1839
+ ):
1840
+
1841
+ output_img = gr.Image(
1842
+
1843
+ label="Detection Result",
1844
+
1845
+ height=350
1846
+
1847
+ )
1848
+
1849
+
1850
+ # ----------------------------------------------------
1851
+ # SUMMARY
1852
+ # ----------------------------------------------------
1853
+
1854
+ with gr.Column(
1855
+ scale=1
1856
+ ):
1857
+
1858
+ summary_box = gr.Textbox(
1859
+
1860
+ label="Detection Summary",
1861
+
1862
+ lines=16
1863
+
1864
+ )
1865
+
1866
+
1867
+ # ========================================================
1868
+ # VEHICLE STATISTICS
1869
+ # ========================================================
1870
+
1871
+ gr.Markdown(
1872
+ "## Detection Statistics"
1873
+ )
1874
+
1875
+
1876
+ with gr.Row():
1877
+
1878
+
1879
+ ev_box = gr.Textbox(
1880
+
1881
+ label="EV Vehicles",
1882
+
1883
+ value="0"
1884
+
1885
+ )
1886
+
1887
+
1888
+ non_ev_box = gr.Textbox(
1889
+
1890
+ label="Non-EV Vehicles",
1891
+
1892
+ value="0"
1893
+
1894
+ )
1895
+
1896
+
1897
+ discount_box = gr.Textbox(
1898
+
1899
+ label="EV Discount",
1900
+
1901
+ value="₹0"
1902
+
1903
+ )
1904
+
1905
+
1906
+ # ========================================================
1907
+ # AGENTIC AI DASHBOARD
1908
+ # ========================================================
1909
+
1910
+ gr.Markdown(
1911
+ """
1912
+ ## Agentic AI Traffic Dashboard
1913
+
1914
+ Ask questions in natural language. The AI agent
1915
+ will select the appropriate analytics tool, retrieve
1916
+ data from the SQLite database, generate an analytical
1917
+ response, and create a relevant visualization.
1918
+ """
1919
+ )
1920
+
1921
+
1922
+ # --------------------------------------------------------
1923
+ # SAMPLE QUESTIONS
1924
+ # --------------------------------------------------------
1925
+
1926
+ gr.Markdown(
1927
+ """
1928
+ **Example questions:**
1929
+
1930
+ - How many EV vehicles were detected?
1931
+ - What percentage of vehicles are EVs?
1932
+ - What is the total discount?
1933
+ - How many vehicles were detected today?
1934
+ - Show today's traffic.
1935
+ - Show the traffic trend.
1936
+ - Show the EV adoption trend.
1937
+ - Give me an overall traffic report.
1938
+ - Show the vehicle records.
1939
+ """
1940
+ )
1941
+
1942
+
1943
+ # --------------------------------------------------------
1944
+ # QUERY BOX
1945
+ # --------------------------------------------------------
1946
+
1947
+ agent_query = gr.Textbox(
1948
+
1949
+ label="Ask the Traffic AI Agent",
1950
+
1951
+ placeholder=(
1952
+ "Example: "
1953
+ "What percentage of vehicles are EVs?"
1954
+ ),
1955
+
1956
+ lines=3
1957
+
1958
+ )
1959
+
1960
+
1961
+ # --------------------------------------------------------
1962
+ # ASK BUTTON
1963
+ # --------------------------------------------------------
1964
+
1965
+ agent_button = gr.Button(
1966
+
1967
+ "Ask AI Agent",
1968
+
1969
+ variant="primary",
1970
+
1971
+ size="lg"
1972
+
1973
+ )
1974
+
1975
+
1976
+ # ========================================================
1977
+ # AI RESPONSE
1978
+ # ========================================================
1979
+
1980
+ gr.Markdown(
1981
+ "### AI Generated Analysis"
1982
+ )
1983
+
1984
+
1985
+ agent_response = gr.Markdown(
1986
+
1987
+ "Ask a question to generate "
1988
+ "an AI-powered traffic report."
1989
+
1990
+ )
1991
+
1992
+
1993
+ # ========================================================
1994
+ # DYNAMIC VISUALIZATION
1995
+ # ========================================================
1996
+
1997
+ gr.Markdown(
1998
+ "### 📈 Dynamic Visualization"
1999
+ )
2000
+
2001
+
2002
+ agent_graph = gr.Plot(
2003
+
2004
+ label="AI Dynamic Analytics"
2005
+
2006
+ )
2007
+
2008
+
2009
+ # ========================================================
2010
+ # SCAN BUTTON EVENT
2011
+ # ========================================================
2012
+
2013
+ btn.click(
2014
+
2015
+ fn=process_image,
2016
+
2017
+ inputs=input_img,
2018
+
2019
+ outputs=[
2020
+
2021
+ output_img,
2022
+
2023
+ summary_box,
2024
+
2025
+ ev_box,
2026
+
2027
+ non_ev_box,
2028
+
2029
+ discount_box
2030
+
2031
+ ]
2032
+
2033
+ )
2034
+
2035
+
2036
+ # ========================================================
2037
+ # AGENT BUTTON EVENT
2038
+ # ========================================================
2039
+
2040
+ agent_button.click(
2041
+
2042
+ fn=run_agentic_dashboard,
2043
+
2044
+ inputs=agent_query,
2045
+
2046
+ outputs=[
2047
+
2048
+ agent_response,
2049
+
2050
+ agent_graph
2051
+
2052
+ ]
2053
+
2054
+ )
2055
+
2056
+
2057
+ # ============================================================
2058
+ # LAUNCH
2059
+ # ============================================================
2060
+
2061
+ if __name__ == "__main__":
2062
+
2063
+ demo.queue()
2064
+
2065
+ demo.launch(
2066
+ ssr_mode=False
2067
+ )