File size: 37,897 Bytes
367b063
af30bc6
367b063
0231137
 
 
 
 
af30bc6
b5ec393
88c2b59
93f8de0
1cdb670
af30bc6
3de8d8f
2b6c3ab
a7e10c9
d497a90
 
71f10e7
 
 
 
 
5e5e961
fb7f78e
a4acadb
fb7f78e
 
 
 
 
 
 
88c2b59
 
 
 
 
fb7f78e
2b6c3ab
d497a90
3c3ad7c
 
 
d497a90
 
1cdb670
279c530
1cdb670
 
 
a4acadb
93f8de0
a4acadb
3226068
01077ea
72f433c
0231137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5e961
1cdb670
 
 
 
279c530
 
57c13aa
 
279c530
 
 
 
57c13aa
279c530
 
 
 
 
57c13aa
 
279c530
 
 
1cdb670
 
a4acadb
 
 
fadf3f5
fb7f78e
af30bc6
fb7f78e
a4acadb
 
07cff00
 
a4acadb
af30bc6
07cff00
af30bc6
07cff00
af30bc6
07cff00
 
af30bc6
fb7f78e
af30bc6
fb7f78e
a4acadb
af30bc6
 
 
 
 
 
 
 
 
a4acadb
07cff00
a4acadb
07cff00
 
a4acadb
07cff00
 
 
a4acadb
07cff00
 
a4acadb
af30bc6
fb7f78e
5e5e961
 
fb7f78e
 
af30bc6
07cff00
 
5e5e961
af30bc6
fb7f78e
af30bc6
6b8e938
 
a4acadb
07cff00
 
a4acadb
af30bc6
a4acadb
07cff00
a4acadb
6b8e938
fb7f78e
af30bc6
07cff00
af30bc6
756ce21
 
07cff00
af30bc6
756ce21
07cff00
 
 
88c2b59
 
 
 
756ce21
88c2b59
 
 
 
 
 
 
756ce21
88c2b59
 
 
 
07cff00
af30bc6
756ce21
a4acadb
af30bc6
756ce21
 
a4acadb
 
88c2b59
 
 
756ce21
88c2b59
 
 
 
 
a4acadb
07cff00
a4acadb
756ce21
a4acadb
 
07cff00
a4acadb
756ce21
a4acadb
 
 
 
88c2b59
a4acadb
 
 
 
756ce21
 
 
 
a4acadb
 
88c2b59
756ce21
a4acadb
 
 
 
 
 
 
 
 
 
756ce21
 
 
88c2b59
756ce21
 
 
4dcd2f3
 
88c2b59
 
756ce21
 
 
4dcd2f3
88c2b59
 
756ce21
 
 
4dcd2f3
88c2b59
756ce21
a4acadb
756ce21
a4acadb
 
 
88c2b59
a4acadb
 
756ce21
 
 
88c2b59
756ce21
88c2b59
 
8d9a055
756ce21
 
a4acadb
88c2b59
 
a4acadb
88c2b59
a4acadb
88c2b59
a4acadb
 
4dcd2f3
 
a4acadb
756ce21
a4acadb
 
 
 
756ce21
 
 
 
 
 
 
8d9a055
3de8d8f
a4acadb
6b8e938
a4acadb
 
 
af30bc6
71f10e7
 
 
 
 
 
 
 
 
 
667c692
 
 
 
 
 
 
71f10e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667c692
 
 
 
 
 
 
71f10e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667c692
 
 
 
 
 
 
71f10e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667c692
 
 
 
 
 
 
71f10e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af30bc6
 
a4acadb
 
756ce21
a4acadb
756ce21
 
 
71f10e7
a4acadb
756ce21
 
 
a4acadb
756ce21
 
 
 
 
 
 
 
 
 
 
 
 
a4acadb
71f10e7
 
 
 
 
 
 
a4acadb
71f10e7
 
 
 
07cff00
 
 
 
a4acadb
 
 
 
756ce21
 
 
 
 
a4acadb
 
af30bc6
756ce21
71f10e7
 
 
 
756ce21
 
 
 
 
af30bc6
a4acadb
07cff00
a4acadb
af30bc6
a4acadb
af30bc6
d497a90
88c2b59
 
 
 
 
 
 
 
 
 
 
 
 
 
a4acadb
 
 
af30bc6
5b46e11
a4acadb
5b46e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4acadb
2b6c3ab
a4acadb
5b46e11
35c6090
5b46e11
 
35c6090
5b46e11
 
538c788
5b46e11
538c788
 
5b46e11
 
 
 
 
3b72a1f
538c788
5b46e11
 
 
 
 
3b72a1f
5b46e11
 
538c788
 
5b46e11
 
 
 
 
 
 
3b72a1f
538c788
5b46e11
 
 
 
 
3b72a1f
5b46e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07cff00
35c6090
5b46e11
a4acadb
5b46e11
a4acadb
af30bc6
5b46e11
 
a4acadb
fb7f78e
5b46e11
fb7f78e
 
5b46e11
 
fb7f78e
af30bc6
5b46e11
 
 
af30bc6
 
5b46e11
af30bc6
a4acadb
5b46e11
 
af30bc6
 
5b46e11
af30bc6
 
fb7f78e
 
 
af30bc6
 
 
07cff00
af30bc6
 
5b46e11
a4acadb
5b46e11
a4acadb
af30bc6
5b46e11
 
af30bc6
6b8e938
5b46e11
 
 
6b8e938
af30bc6
5b46e11
 
 
 
 
 
af30bc6
07cff00
 
5b46e11
 
a4acadb
 
 
5b46e11
 
a4acadb
af30bc6
 
5b46e11
af30bc6
 
fb7f78e
 
6b8e938
af30bc6
 
 
 
07cff00
af30bc6
 
5b46e11
a4acadb
16cdcbe
a4acadb
af30bc6
1cdb670
 
16cdcbe
 
279c530
16cdcbe
 
 
 
 
 
 
 
 
7c0ff10
16cdcbe
 
 
 
 
 
 
 
 
 
279c530
 
16cdcbe
 
57c13aa
279c530
 
1cdb670
279c530
 
16cdcbe
 
 
 
 
 
 
 
1cdb670
16cdcbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fced10e
16cdcbe
 
71f10e7
734c3b3
f0a026f
734c3b3
719ba4c
734c3b3
fd53ef0
 
 
 
57c13aa
f385408
 
734c3b3
4dcd2f3
 
f385408
fd53ef0
f385408
71f10e7
fced10e
f385408
 
 
 
 
 
71f10e7
 
fced10e
 
f385408
 
71f10e7
734c3b3
 
 
fd53ef0
734c3b3
 
71f10e7
f0a026f
734c3b3
71f10e7
16cdcbe
f0a026f
71f10e7
f0a026f
71f10e7
f0a026f
 
fced10e
71f10e7
f0a026f
734c3b3
 
 
f0a026f
fced10e
01077ea
fced10e
fd53ef0
 
734c3b3
 
fd53ef0
16cdcbe
71f10e7
084c5ef
16cdcbe
084c5ef
16cdcbe
0231137
 
71f10e7
0231137
084c5ef
 
0231137
084c5ef
fced10e
084c5ef
0231137
084c5ef
0231137
fced10e
 
084c5ef
fced10e
 
 
 
084c5ef
 
fced10e
 
 
 
084c5ef
57c13aa
71f10e7
279c530
71f10e7
16cdcbe
 
f385408
71f10e7
 
f385408
16cdcbe
71f10e7
16cdcbe
 
 
71f10e7
16cdcbe
 
 
71f10e7
16cdcbe
 
 
 
 
279c530
af30bc6
a4acadb
5b46e11
a4acadb
 
5b46e11
71f10e7
 
af30bc6
fb7f78e
5b46e11
 
 
71f10e7
af30bc6
 
71f10e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b46e11
 
 
 
 
 
af30bc6
5b46e11
 
 
 
 
af30bc6
5b46e11
 
 
 
 
 
af30bc6
5b46e11
 
 
 
 
af30bc6
fb7f78e
 
af30bc6
71f10e7
 
 
 
af30bc6
 
 
 
 
6b8e938
fb7f78e
5fa73f8
ce822b4
5fa73f8
a4acadb
5fa73f8
d497a90
ce822b4
 
 
3c3ad7c
5fa73f8
ce822b4
5fa73f8
ce822b4
3deba18
 
 
5fa73f8
3c3ad7c
630f1b6
3deba18
630f1b6
3deba18
630f1b6
5fa73f8
 
630f1b6
3deba18
630f1b6
3deba18
630f1b6
5fa73f8
3c3ad7c
5fa73f8
3deba18
ce822b4
 
5fa73f8
3c3ad7c
5fa73f8
ce822b4
5fa73f8
3deba18
5fa73f8
 
3c3ad7c
5fa73f8
3deba18
5fa73f8
 
 
ce822b4
5fa73f8
 
 
 
 
 
 
 
 
 
 
a4acadb
5b46e11
a4acadb
 
5b46e11
fb7f78e
 
 
 
5b46e11
93f8de0
 
5b46e11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
import os
os.environ["OMP_NUM_THREADS"] = "1"

# Suppress all warnings BEFORE importing anything else
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')

import asyncio
from datetime import datetime
import sys
import platform
import json

import pandas as pd
import gradio as gr
import folium
import base64
from datetime import timedelta
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
import io
from PIL import Image

from detector import detect_plate

from database import (
    save_detection,
    run_query,
    health_check,
    get_vehicles_by_state,
    get_hourly_traffic,
    get_top_plates,
    get_suspicious_vehicles,
    HF_TOKEN,
    DATABASE_URL,
    client,
    engine
)

from vehicle_map import (
    search_vehicle_route,
    default_vehicle_map,
    map_to_html
)

from ai_investigation import (
    ask_investigation_question,
    format_investigation_output
)

# =========================================================
# ASYNC FIX & EVENT LOOP MANAGEMENT
# =========================================================

# Suppress all warnings to prevent asyncio event loop cleanup messages
warnings.filterwarnings('ignore')
warnings.filterwarnings('ignore', category=ResourceWarning)
warnings.filterwarnings('ignore', category=RuntimeWarning)
warnings.filterwarnings('ignore', category=DeprecationWarning)

# Suppress asyncio event loop cleanup errors on Linux
import sys
_original_excepthook = sys.excepthook
def _suppress_asyncio_errors(exc_type, exc_value, traceback):
    """Suppress asyncio cleanup errors but show real errors"""
    if exc_type and 'Invalid file descriptor' in str(exc_value):
        return  # Silently ignore asyncio cleanup errors
    if exc_type and 'BaseEventLoop' in str(traceback):
        return  # Silently ignore event loop cleanup
    _original_excepthook(exc_type, exc_value, traceback)

sys.excepthook = _suppress_asyncio_errors

# =========================================================
# INVESTIGATION ASSISTANT WRAPPERS
# =========================================================

def ask_question_wrapper(question):
    """Unified AI Investigation Agent - handles any natural language question"""
    if not question or len(question.strip()) < 2:
        return ("Please ask a valid question", "", "", None, "")
    
    result = ask_investigation_question(question)
    if result.get("status") == "error":
        error_msg = result.get("message", "Investigation failed")
        return (f"Error: {error_msg}", "", "", None, "")
    
    return (
        result.get("answer", ""),
        "\n".join(result.get("findings", [])),
        result.get("analysis", {}),
        None,
        result.get("data_summary", "")
    )




# =========================================================
# DETECTION
# =========================================================

def detect_and_save(image):

    if image is None:

        return (
            "No image uploaded",
            {"error": "No image uploaded"}
        )

    try:

        now = datetime.now()

        date = now.strftime("%Y-%m-%d")
        time = now.strftime("%H:%M:%S")

        plate, state, vehicle_type, vehicle_conf, success = detect_plate(image)

        if success and plate:

            save_detection(
                plate,
                state,
                vehicle_type,
                vehicle_conf,
                date,
                time
            )

        result_text = f"""
Detection Success

Date: {date}
Time: {time}

Vehicle Type: {vehicle_type}
Plate: {plate}
State: {state}

Confidence: {round(vehicle_conf, 3)}
Saved: {success}
"""

        result_json = {
            "date": date,
            "time": time,
            "plate": plate,
            "state": state,
            "vehicle_type": vehicle_type,
            "confidence": round(vehicle_conf, 3),
            "saved": success
        }

        return result_text, result_json

    except Exception as e:

        return (
            f"Error: {str(e)}",
            {"error": str(e)}
        )

# =========================================================
# NLP QUERY
# =========================================================

def query_database(user_query):

    try:

        print(f"\nπŸ” NLP Query: {user_query}")

        if not user_query.strip():

            print("❌ Empty query")
            return (
                "",
                pd.DataFrame(),
                {"error": "❌ Empty query - Please enter something"}
            )

        if not HF_TOKEN:
            print("❌ HF_TOKEN missing")
            return (
                "",
                pd.DataFrame(),
                {"error": "❌ HF_TOKEN not set - NLP features disabled"}
            )

        if not DATABASE_URL:
            print("❌ DATABASE_URL missing")
            return (
                "",
                pd.DataFrame(),
                {"error": "❌ DATABASE_URL not set - Database features disabled"}
            )

        print(f"Calling run_query...")
        response = run_query(user_query)

        print(f"Response: {response}")

        sql = response.get("sql", "")
        results = response.get("result", [])
        error = response.get("error", "")

        if error:
            print(f"❌ Query error: {error}")
            return (
                sql,
                pd.DataFrame(),
                {"error": f"❌ Query Error: {error}"}
            )

        if len(results) > 0:
            df = pd.DataFrame(results)
            print(f"βœ… Found {len(results)} records")
        else:
            df = pd.DataFrame({
                "message": ["No results found"]
            })
            print("ℹ️ No results found")

        return (
            sql,
            df,
            {"success": f"βœ… Found {len(results)} records"}
        )

    except Exception as e:

        error_msg = f"❌ Error: {str(e)}"
        print(error_msg)
        import traceback
        traceback.print_exc()
        return (
            "",
            pd.DataFrame(),
            {"error": error_msg}
        )

# =========================================================
# CHATBOT
# =========================================================

def chatbot_query(message, history):

    try:

        print(f"\nπŸ’¬ Chatbot message: {message}")
        print(f"History type: {type(history)}, Length: {len(history) if history else 0}")

        if not message.strip():
            print("❌ Empty message")
            if not history:
                history = []
            # Gradio 6.14.0+: Format MUST be {"role": "user/assistant", "content": "text"}
            return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "❌ Empty message"}], ""

        if not HF_TOKEN:
            print("❌ HF_TOKEN not configured")
            if not history:
                history = []
            return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "❌ HF_TOKEN not configured - NLP disabled"}], ""

        if not DATABASE_URL:
            print("❌ DATABASE_URL not configured")
            if not history:
                history = []
            return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "❌ DATABASE_URL not configured - Database disabled"}], ""

        print("Calling run_query...")
        response = run_query(message)
        print(f"Response: {response}")

        sql = response.get("sql", "")
        results = response.get("result", [])
        error = response.get("error", "")
        count = response.get("count", 0)

        if not history:
            history = []

        if error:
            print(f"❌ Query error: {error}")
            bot_reply = f"❌ Error: {error}"
        else:
            preview = str(results[:3]) if results else "No results"
            print(f"βœ… Found {count} records")
            bot_reply = f"""βœ… Query processed

**SQL Generated:**
```sql
{sql}
```

**Results:** {count} records found
"""

        # Gradio 6.14.0+: Append dict format {"role", "content"}
        history = history + [{"role": "user", "content": message}, {"role": "assistant", "content": bot_reply}]

        print(f"Returning history with {len(history)} messages")
        return history, ""

    except Exception as e:

        print(f"❌ Exception: {str(e)}")
        import traceback
        traceback.print_exc()

        if not history:
            history = []

        history = history + [[message, f"❌ Error: {str(e)}"]]

        return history, ""

# =========================================================
# ANALYTICS
# =========================================================

# ========== CHARTING FUNCTIONS ==========

def create_state_chart(state_df):
    """Create pie chart for vehicles by state"""
    try:
        if state_df.empty or len(state_df) == 0:
            return None
        
        plt.figure(figsize=(10, 6))
        
        # Get state and count columns by name
        if 'state' in state_df.columns and 'count' in state_df.columns:
            states = state_df['state'].tolist()
            counts = state_df['count'].tolist()
        else:
            states = state_df.iloc[:, 0].tolist() if len(state_df.columns) > 0 else []
            counts = state_df.iloc[:, 1].tolist() if len(state_df.columns) > 1 else []
        
        if not states or not counts:
            return None
        
        # Create pie chart
        colors = plt.cm.Set3(range(len(states)))
        plt.pie(counts, labels=states, autopct='%1.1f%%', colors=colors, startangle=90)
        plt.title('πŸš— Vehicles by State Distribution', fontsize=14, fontweight='bold', pad=20)
        plt.tight_layout()
        
        # Convert to PIL Image
        buf = io.BytesIO()
        plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
        buf.seek(0)
        img = Image.open(buf)
        img_copy = img.copy()
        plt.close()
        return img_copy
    except Exception as e:
        print(f"State chart error: {e}")
        plt.close()
        return None


def create_hourly_chart(hourly_df):
    """Create line chart for hourly traffic"""
    try:
        if hourly_df.empty or len(hourly_df) == 0:
            return None
        
        plt.figure(figsize=(12, 5))
        
        # Get hour and traffic columns by name
        if 'hour' in hourly_df.columns and 'traffic' in hourly_df.columns:
            hours = hourly_df['hour'].tolist()
            counts = hourly_df['traffic'].tolist()
        else:
            hours = hourly_df.iloc[:, 0].tolist() if len(hourly_df.columns) > 0 else []
            counts = hourly_df.iloc[:, 1].tolist() if len(hourly_df.columns) > 1 else []
        
        if not hours or not counts:
            return None
        
        # Create line chart
        plt.plot(hours, counts, marker='o', linewidth=2, markersize=8, color='#FF6B6B')
        plt.fill_between(range(len(hours)), counts, alpha=0.3, color='#FF6B6B')
        plt.xlabel('Hour of Day', fontsize=11, fontweight='bold')
        plt.ylabel('Detection Count', fontsize=11, fontweight='bold')
        plt.title('πŸ“Š Traffic by Hour', fontsize=14, fontweight='bold', pad=20)
        plt.grid(True, alpha=0.3)
        plt.xticks(range(0, len(hours), max(1, len(hours)//12)))
        plt.tight_layout()
        
        # Convert to PIL Image
        buf = io.BytesIO()
        plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
        buf.seek(0)
        img = Image.open(buf)
        img_copy = img.copy()
        plt.close()
        return img_copy
    except Exception as e:
        print(f"Hourly chart error: {e}")
        plt.close()
        return None


def create_top_plates_chart(top_df):
    """Create horizontal bar chart for top plates"""
    try:
        if top_df.empty or len(top_df) == 0:
            return None
        
        plt.figure(figsize=(10, 6))
        
        # Get plate and detections columns (limit to top 10)
        if 'plate' in top_df.columns and 'detections' in top_df.columns:
            plates = top_df.head(10)['plate'].tolist()
            counts = top_df.head(10)['detections'].tolist()
        else:
            plates = top_df.iloc[:10, 0].tolist() if len(top_df.columns) > 0 else []
            counts = top_df.iloc[:10, 1].tolist() if len(top_df.columns) > 1 else []
        
        if not plates or not counts:
            return None
        
        # Create horizontal bar chart
        colors = plt.cm.viridis(range(len(plates)))
        bars = plt.barh(plates, counts, color=colors)
        
        # Add value labels on bars
        for i, (bar, count) in enumerate(zip(bars, counts)):
            plt.text(count + 0.1, i, str(int(count)), va='center', fontsize=9)
        
        plt.xlabel('Detection Count', fontsize=11, fontweight='bold')
        plt.title('πŸ† Top Detected License Plates', fontsize=14, fontweight='bold', pad=20)
        plt.tight_layout()
        
        # Convert to PIL Image
        buf = io.BytesIO()
        plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
        buf.seek(0)
        img = Image.open(buf)
        img_copy = img.copy()
        plt.close()
        return img_copy
    except Exception as e:
        print(f"Top plates chart error: {e}")
        plt.close()
        return None


def create_suspicious_chart(suspicious_df):
    """Create donut chart for suspicious vehicles"""
    try:
        if suspicious_df.empty or len(suspicious_df) == 0:
            return None
        
        plt.figure(figsize=(10, 6))
        
        # Get data by column name (limit to top 8)
        if 'plate' in suspicious_df.columns and 'detections' in suspicious_df.columns:
            labels = suspicious_df.head(8)['plate'].tolist()
            sizes = suspicious_df.head(8)['detections'].tolist()
        else:
            labels = suspicious_df.iloc[:8, 0].tolist() if len(suspicious_df.columns) > 0 else []
            sizes = suspicious_df.iloc[:8, 1].tolist() if len(suspicious_df.columns) > 1 else []
        
        if not labels or not sizes:
            return None
        
        # Create donut chart
        colors = plt.cm.Reds(range(len(labels)))
        wedges, texts, autotexts = plt.pie(sizes, labels=labels, autopct='%1.1f%%', 
                                           colors=colors, startangle=90, pctdistance=0.85)
        
        # Draw donut hole
        centre_circle = plt.Circle((0, 0), 0.70, fc='white')
        plt.gca().add_artist(centre_circle)
        
        plt.title('⚠️ Suspicious Vehicle Alerts', fontsize=14, fontweight='bold', pad=20)
        plt.tight_layout()
        
        # Convert to PIL Image
        buf = io.BytesIO()
        plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
        buf.seek(0)
        img = Image.open(buf)
        img_copy = img.copy()
        plt.close()
        return img_copy
    except Exception as e:
        print(f"Suspicious chart error: {e}")
        plt.close()
        return None


def refresh_analytics():

    try:

        print("\nπŸ“Š Refreshing analytics...")

        if not DATABASE_URL or not engine:
            print("❌ Database not configured")
            err = pd.DataFrame({"error": ["Database not configured"]})
            return err, err, err, err, err, err, err, err

        print("Getting vehicles by state...")
        state_data = get_vehicles_by_state()
        state_df = pd.DataFrame(state_data) if state_data else pd.DataFrame()

        print("Getting hourly traffic...")
        hourly_data = get_hourly_traffic()
        hourly_df = pd.DataFrame(hourly_data) if hourly_data else pd.DataFrame()

        print("Getting top plates...")
        top_data = get_top_plates()
        top_df = pd.DataFrame(top_data) if top_data else pd.DataFrame()

        print("Getting suspicious vehicles...")
        suspicious_data = get_suspicious_vehicles()
        suspicious_df = pd.DataFrame(suspicious_data) if suspicious_data else pd.DataFrame()

        print(f"βœ… Analytics refreshed: {len(state_df)} states, {len(hourly_df)} hours, {len(top_df)} top plates, {len(suspicious_df)} suspicious")

        # Generate charts
        print("🎨 Generating charts...")
        state_chart = create_state_chart(state_df)
        hourly_chart = create_hourly_chart(hourly_df)
        top_chart = create_top_plates_chart(top_df)
        suspicious_chart = create_suspicious_chart(suspicious_df)

        return (
            state_chart,
            hourly_chart,
            top_chart,
            suspicious_chart,
            state_df,
            hourly_df,
            top_df,
            suspicious_df
        )

    except Exception as e:

        print(f"❌ Analytics error: {str(e)}")
        import traceback
        traceback.print_exc()

        err_df = pd.DataFrame({
            "error": [str(e)]
        })

        return (
            None,
            None,
            None,
            None,
            err_df,
            err_df,
            err_df,
            err_df
        )

# =========================================================
# HEALTH
# =========================================================

status, msg = health_check()


# =========================================================
# CONFIGURATION DEBUG
# =========================================================

print("\n" + "="*60)
print("πŸ”§ CONFIGURATION STATUS")
print("="*60)
print(f"HF_TOKEN: {'βœ… SET' if HF_TOKEN else '❌ NOT SET'}")
print(f"DATABASE_URL: {'βœ… SET' if DATABASE_URL else '❌ NOT SET'}")
print(f"Mistral Client: {'βœ… READY' if client else '❌ FAILED'}")
print(f"Database Engine: {'βœ… READY' if engine else '❌ FAILED'}")
print(f"Database Health: {msg}")
print("="*60 + "\n")

# =========================================================
# UI
# =========================================================


with gr.Blocks(
    title="ActionSync β€” Vehicle Intelligence Platform",
    theme=gr.themes.Soft(
        text_size="lg",
    ),
    css="""
    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.5em;
        padding: 0.4em 0.8em;
        border-radius: 999px;
        font-size: 0.9em;
        font-weight: 500;
    }
    .status-success {
        background-color: #16a34a;
        color: white;
        border: 1px solid #15803d;
    }
    .status-error {
        background-color: #b91c1c;
        color: white;
        border: 1px solid #991b1b;
    }
    .status-warn {
        background-color: #ca8a04;
        color: white;
        border: 1px solid #a16207;
    }
    .status-label {
        display: inline-block;
        margin-left: 0.5em;
    }
    """
) as demo:

    gr.Markdown("""
    # 🚦 ActionSync β€” Vehicle Intelligence Platform

    AI‑powered vehicle detection and analytics with NLP‑to‑SQL querying.
    """, elem_classes=["text-center"])

    # Status panel
    with gr.Accordion("πŸ”§ System Status", open=True):
        with gr.Row():
            # LLM / NLP status
            with gr.Column():
                if HF_TOKEN and client:
                    gr.Markdown("""
                    <div class="status-badge status-success">
                        βœ… NLP Engine
                        <span class="status-label">Mistral LLM enabled</span>
                    </div>
                    """, elem_classes=["status-success"])
                else:
                    gr.Markdown("""
                    <div class="status-badge status-warn">
                        ⚠️ NLP Engine
                        <span class="status-label">HF_TOKEN missing</span>
                    </div>
                    """, elem_classes=["status-warn"])

            # Database status
            with gr.Column():
                if DATABASE_URL and engine:
                    # Example record count (you can replace with actual count later)
                    record_count = 20633  # ← replace with a real count query if you want
                    gr.Markdown(f"""
                    <div class="status-badge status-success">
                        βœ… Database
                        <span class="status-label">Connected β€” {record_count:,} records</span>
                    </div>
                    """, elem_classes=["status-success"])
                else:
                    gr.Markdown("""
                    <div class="status-badge status-error">
                        ❌ Database
                        <span class="status-label">Not configured</span>
                    </div>
                    """, elem_classes=["status-error"])

        # Setup note if anything is missing
        if not (HF_TOKEN and client) or not (DATABASE_URL and engine):
            gr.Markdown("""
            ### ⚠️ Setup Required

            To enable all features, please configure your Hugging Face and database settings:

            1. Go to **Space Settings β†’ Repository secrets**
            2. Add:
               - `HF_TOKEN` β€” from [Hugging Face Tokens](https://huggingface.co/settings/tokens)
               - `DATABASE_URL` β€” PostgreSQL URL: `postgresql://user:pass@host:5432/db`
            3. **Restart the Space**

            After configuration, NLP queries and database features will be enabled.
            """)

    gr.Markdown(f"### {msg}")


    # =====================================================
    # TAB 1: Detection
    # =====================================================

    with gr.Tab("Detection", id="tab_detection"):
        gr.Markdown("### Vehicle Detection")

        with gr.Row():
            with gr.Column(scale=1):
                input_img = gr.Image(
                    type="numpy",
                    label="Upload Image",
                    height=360,
                )
                detect_btn = gr.Button(
                    "πŸ” Detect Vehicle",
                    variant="primary",
                    size="lg",
                )

            with gr.Column(scale=1):
                output_text = gr.Textbox(
                    label="Detection Result",
                    lines=8,
                    show_label=True,
                )
                output_json = gr.JSON(
                    label="Raw JSON Output",
                )

        detect_btn.click(
            fn=detect_and_save,
            inputs=input_img,
            outputs=[
                output_text,
                output_json
            ]
        )


    # =====================================================
    # TAB 2: NLP Query
    # =====================================================

    with gr.Tab("NLP Query", id="tab_nlp"):
        gr.Markdown("### Natural Language Database Query")

        query_input = gr.Textbox(
            label="Enter your question",
            placeholder="Show vehicles from Tamil Nadu last 24 hours",
            lines=2,
        )

        with gr.Row():
            search_btn = gr.Button(
                "πŸ“ Generate & Execute SQL",
                variant="primary",
                size="lg",
            )

        sql_output = gr.Code(
            language="sql",
            label="Generated SQL",
            lines=6,
        )

        results_output = gr.Dataframe(
            label="Query Results",
            interactive=False,
        )

        json_output = gr.JSON(
            label="Full Response",
        )

        search_btn.click(
            fn=query_database,
            inputs=query_input,
            outputs=[
                sql_output,
                results_output,
                json_output
            ]
        )


    # =====================================================
    # TAB 3: AI Investigation Agent (CHAT INTERFACE)
    # =====================================================

    with gr.Tab("πŸ” AI Investigation", id="tab_investigation"):
        
        gr.Markdown("## πŸ€– AI Investigation ChatBot")
        gr.Markdown("*Ask questions about vehicles, locations, patterns. Follow-ups appear naturally in chat.*")
        
        # Conversation state to track history
        conversation_state = gr.State([])
        investigation_results = gr.State({})
        
        with gr.Row():
            with gr.Column(scale=5):
                # Chat display area
                chatbot = gr.Chatbot(
                    label="πŸ’¬ Investigation Conversation",
                    height=500
                )
            
            with gr.Column(scale=2):
                # Quick stats panel
                stats_display = gr.Markdown(
                    value="**πŸ“Š Investigation Stats**\n\n*Results will appear here*",
                    label="Quick Stats"
                )
        
        # Input area with follow-up suggestions
        with gr.Row():
            question_input = gr.Textbox(
                placeholder="e.g., show bikes in adyar or TN57GR8753 or midnight detections",
                label="Your Question",
                lines=2,
                scale=5
            )
            
            investigate_btn = gr.Button("πŸ”Ž Investigate", variant="primary", scale=1, size="lg")
        
        # Suggested follow-ups (appears dynamically)
        suggested_follow_ups = gr.Markdown(
            value="",
            label="πŸ’‘ Suggested Questions"
        )
        
        # Detailed investigation tabs (collapsible section)
        with gr.Accordion("πŸ“‹ Detailed Investigation Results", open=True):
            
            with gr.Tabs():
                
                # Data collected tab
                with gr.Tab("πŸ“Š Data Summary"):
                    data_structure = gr.Markdown(
                        value="*Investigation details will appear here*"
                    )
                
                # Key findings tab
                with gr.Tab("🚨 Key Findings & Patterns"):
                    findings_display = gr.Markdown(
                        value="*Key findings from analysis*"
                    )
                
                # Relevant data table
                with gr.Tab("πŸ“‹ All Records"):
                    data_table = gr.Dataframe(
                        label="Retrieved Data",
                        interactive=False
                    )
                
                # Analysis metrics
                with gr.Tab("πŸ“ˆ Analysis Metrics"):
                    metrics_display = gr.Markdown(
                        value="*Metrics and statistics*"
                    )
        
        # =====================================================
        # Chat Interface Logic - FIXED MESSAGE FORMAT
        # =====================================================
        
        def investigate_fast(message, chat_history, conv_state, inv_results):
            """Fast response - append user message only"""
            if not message or len(str(message).strip()) < 2:
                return (chat_history or []), (conv_state or []), (inv_results or {})
            
            # Ensure chat_history is a list
            if not chat_history:
                history = []
            else:
                history = list(chat_history) if isinstance(chat_history, list) else []
            
            msg_str = str(message).strip()
            
            # SIMPLE: Only append user message dict, assistant will be added in next step
            user_msg_dict = {"role": "user", "content": msg_str}
            history.append(user_msg_dict)
            
            return history, (conv_state or []) + [msg_str], (inv_results or {})
        
        def investigate_complete(message):
            """Get investigation results"""
            try:
                result = ask_investigation_question(message)
                return result
            except Exception as e:
                return {
                    "status": "error",
                    "message": f"Error: {str(e)[:80]}",
                    "analysis": {},
                    "data_preview": [],
                    "total_records": 0
                }
        
        def update_chat_final(message, chat_history, inv_results):
            """Add assistant response to chat"""
            if not message or not chat_history:
                return (chat_history or []), (inv_results or {})
            
            # Ensure chat_history is a list
            history = list(chat_history) if isinstance(chat_history, list) else []
            
            try:
                # Get investigation result - FAST (uses fallback, no LLM)
                result = investigate_complete(message)
                
                if result.get("status") == "error":
                    ai_response = result.get("message", "Investigation failed")
                else:
                    ai_response = result.get("answer", "Investigation complete")
                    analysis = result.get("analysis", {})
                    
                    # Add quick summary
                    ai_response += f"\n\n**Summary:** {result.get('total_records', 0)} records | {analysis.get('unique_vehicles', 0)} vehicles | {analysis.get('unique_locations', 0)} locations"
                
                # SIMPLE: Just append assistant message dict
                assistant_msg_dict = {"role": "assistant", "content": ai_response}
                history.append(assistant_msg_dict)
                
                return history, result
            except Exception as e:
                print(f"Chat update error: {e}")
                import traceback
                traceback.print_exc()
                # Append error message
                history.append({"role": "assistant", "content": f"⚠️ Error: {str(e)[:100]}"})
                return history, (inv_results or {})
        
        def update_detailed_tabs_lightweight(inv_results):
            """Update detailed analysis tabs"""
            if not inv_results or inv_results.get("status") == "error":
                return ("No data available", "No findings yet", None, "No metrics")
            
            try:
                analysis = inv_results.get("analysis", {})
                total = inv_results.get('total_records', 0)
                
                # Summary
                data_info = f"πŸ“Š **{total} records** | πŸš— **{analysis.get('unique_vehicles', 0)} vehicles** | πŸ“ **{analysis.get('unique_locations', 0)} locations**"
                
                # Findings
                findings_list = analysis.get("key_findings", [])
                findings = "**Key Findings:**\n" + "\n".join([f"β€’ {f}" for f in findings_list[:3]]) if findings_list else "No key findings"
                
                # Data table (limit to 20 rows)
                df_data = None
                try:
                    preview = inv_results.get("data_preview", [])[:20]
                    if preview:
                        df_data = pd.DataFrame(preview)
                except Exception as e:
                    print(f"DataFrame error: {e}")
                
                # Metrics
                metrics = f"**Confidence:** {analysis.get('confidence_score', 0):.0%}\n**Records:** {total}"
                
                return (data_info, findings, df_data, metrics)
            except Exception as e:
                print(f"Tab update error: {e}")
                return ("Error processing data", "Error", None, "Error")
        
        # OPTIMIZED CLICK HANDLER - Fast first update, then background refresh
        investigate_btn.click(
            fn=investigate_fast,
            inputs=[question_input, chatbot, conversation_state, investigation_results],
            outputs=[chatbot, conversation_state, investigation_results]
        ).then(
            fn=update_chat_final,
            inputs=[question_input, chatbot, investigation_results],
            outputs=[chatbot, investigation_results]
        ).then(
            fn=update_detailed_tabs_lightweight,
            inputs=[investigation_results],
            outputs=[data_structure, findings_display, data_table, metrics_display]
        ).then(
            fn=lambda inv: f"**πŸ“Š Stats**\n\n**Records:** {inv.get('total_records', 0)}\n**Vehicles:** {inv.get('analysis', {}).get('unique_vehicles', 0)}\n**Locations:** {inv.get('analysis', {}).get('unique_locations', 0)}" if inv.get("status") != "error" else "**Stats**\n\nAnalysis pending...",
            inputs=[investigation_results],
            outputs=[stats_display]
        ).then(
            fn=lambda inv: "\n".join([f"β†’ {q}" for q in inv.get("follow_ups", [])[:3]]) if inv.get("follow_ups") and inv.get("status") != "error" else "",
            inputs=[investigation_results],
            outputs=[suggested_follow_ups]
        ).then(
            fn=lambda: "",
            outputs=[question_input]
        )

    # =====================================================
    # TAB 4: Analytics
    # =====================================================

    with gr.Tab("Analytics", id="tab_analytics"):
        gr.Markdown("### πŸ“Š Analytics Dashboard - Visual Intelligence")
        gr.Markdown("*Advanced analytics with real-time visualizations and data breakdown*")

        with gr.Row():
            refresh_btn = gr.Button(
                "πŸ”„ Refresh Analytics",
                variant="primary",
                size="lg",
            )

        # ===== CHARTS ROW 1 =====
        with gr.Row(equal_height=True):
            with gr.Column(scale=1):
                gr.Markdown("**πŸš— Vehicles by State (Pie Chart)**")
                state_chart = gr.Image(
                    label="State Distribution",
                    type="pil"
                )

            with gr.Column(scale=1):
                gr.Markdown("**πŸ“Š Hourly Traffic Trends (Line Chart)**")
                hourly_chart = gr.Image(
                    label="Hourly Traffic",
                    type="pil"
                )

        # ===== CHARTS ROW 2 =====
        with gr.Row(equal_height=True):
            with gr.Column(scale=1):
                gr.Markdown("**πŸ† Top Detected Plates (Bar Chart)**")
                top_chart = gr.Image(
                    label="Top Plates",
                    type="pil"
                )

            with gr.Column(scale=1):
                gr.Markdown("**⚠️ Suspicious Vehicles (Donut Chart)**")
                suspicious_chart = gr.Image(
                    label="Suspicious Alerts",
                    type="pil"
                )

        # ===== DATA TABLES =====
        gr.Markdown("### πŸ“‹ Detailed Data Tables")

        with gr.Row(equal_height=True):
            with gr.Column(scale=1):
                state_table = gr.Dataframe(
                    label="Vehicles by State",
                    interactive=False,
                )

            with gr.Column(scale=1):
                hourly_table = gr.Dataframe(
                    label="Traffic by Hour",
                    interactive=False,
                )

        with gr.Row(equal_height=True):
            with gr.Column(scale=1):
                top_table = gr.Dataframe(
                    label="Top License Plates",
                    interactive=False,
                )

            with gr.Column(scale=1):
                suspicious_table = gr.Dataframe(
                    label="Suspicious Vehicles",
                    interactive=False,
                )

        refresh_btn.click(
            fn=refresh_analytics,
            outputs=[
                state_chart,
                hourly_chart,
                top_chart,
                suspicious_chart,
                state_table,
                hourly_table,
                top_table,
                suspicious_table
            ]
        )

    # =====================================================
    # VEHICLE INTELLIGENCE
    # =====================================================

    with gr.Tab("πŸ—ΊοΈ Vehicle Intelligence"):

        vehicle_map = gr.HTML(
            value=default_vehicle_map()
        )

        with gr.Row():

            vehicle_plate = gr.Textbox(
                placeholder="TN57GR8753",
                label="License Plate (Required)",
                scale=2,
                info="Enter vehicle number plate"
            )

            date_from = gr.Textbox(
                label="Start Date (Optional)",
                placeholder="YYYY-MM-DD",
                scale=2,
                info="Format: YYYY-MM-DD or leave empty"
            )

            date_to = gr.Textbox(
                label="End Date (Optional)",
                placeholder="YYYY-MM-DD",
                scale=2,
                info="Format: YYYY-MM-DD or leave empty"
            )

            search_vehicle_btn = gr.Button(
                "πŸ” Search Route",
                variant="primary",
                scale=1
            )

        with gr.Row():

            vehicle_table = gr.Dataframe(
                label="Detection Timeline",
                interactive=False
            )

            vehicle_info = gr.JSON(
                label="Route Analytics"
            )

        search_vehicle_btn.click(
            fn=search_vehicle_route,
            inputs=[
                vehicle_plate,
                date_from,
                date_to
            ],
            outputs=[
                vehicle_map,
                vehicle_table,
                vehicle_info
            ]
        )
# =========================================================
# QUEUE & LAUNCH
# =========================================================

demo.queue(max_size=20)

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        ssr_mode=False,
        show_error=True,
    )