File size: 47,380 Bytes
178409a
 
4ae1a41
178409a
021c88f
178409a
 
4c70761
 
021c88f
 
178409a
021c88f
178409a
 
 
 
 
 
f46de2f
1535672
4ae1a41
178409a
 
 
021c88f
 
 
 
 
 
 
 
4deeabd
178409a
f46de2f
 
fdd933e
4deeabd
f46de2f
4c70761
 
 
021c88f
 
 
2003108
 
 
 
 
 
 
 
 
4deeabd
2003108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4deeabd
2003108
 
 
 
 
 
4deeabd
2003108
4deeabd
 
 
2003108
4deeabd
4ae1a41
2003108
 
 
178409a
4deeabd
4ae1a41
178409a
4ae1a41
021c88f
178409a
4deeabd
 
4c70761
021c88f
4deeabd
4ae1a41
4deeabd
 
 
f46de2f
fdd933e
f46de2f
76e2003
2003108
 
 
4deeabd
021c88f
 
 
 
 
 
 
 
 
4deeabd
 
76e2003
4deeabd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dacfb8a
b4e25a1
 
dacfb8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4deeabd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdd933e
f46de2f
 
 
 
 
 
 
 
 
 
 
2003108
f46de2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e2003
021c88f
 
 
 
 
 
4c70761
021c88f
 
 
 
4ae1a41
021c88f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22ce35a
021c88f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7940c3
 
 
 
 
 
 
4c70761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7940c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178409a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
import streamlit as st
import requests
import google.generativeai as genai
import firebase_admin
from firebase_admin import credentials, db
from PIL import Image
import numpy as np
import base64
from io import BytesIO
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input

# Initialize Firebase
if not firebase_admin._apps:
    cred = credentials.Certificate("firebase_credentials.json")  
    firebase_admin.initialize_app(cred, {
        'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
    })

# Configure Gemini 2.0 Flash (gemini-1.5-flash)
genai.configure(api_key="AIzaSyBREh8Uei7uDCbzPaYW2WdalOdjVWcQLAM")  # Replace with actual API key

# Load MobileNetV2 pre-trained model
mobilenet_model = MobileNetV2(weights="imagenet")

# Function to classify image
def classify_image(image):
    img = image.resize((224, 224))
    img_array = np.array(img)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = preprocess_input(img_array)
    predictions = mobilenet_model.predict(img_array)
    labels = decode_predictions(predictions, top=5)[0]
    return {label[1]: round(float(label[2]) * 100, 2) for label in labels}

# Function to check if image is a dustbin
def is_dustbin_image(classification_results):
    dustbin_keywords = ["trash", "bin", "garbage", "waste", "dustbin", "ashcan", "recycle", "rubbish"]
    return any(any(keyword in label.lower() for keyword in dustbin_keywords) for label in classification_results.keys())

# Function to convert image to Base64
def convert_image_to_base64(image):
    buffered = BytesIO()
    image.save(buffered, format="PNG")
    return base64.b64encode(buffered.getvalue()).decode()

# Function to generate AI recommendations using Gemini 2.0 Flash
def get_genai_response(classification_results, location):
    try:
        classification_summary = "\n".join([f"- **{label}:** {score}%" for label, score in classification_results.items()])
        location_summary = f"""
        - **Latitude:** {location[0] if location[0] else 'N/A'}
        - **Longitude:** {location[1] if location[1] else 'N/A'}
        - **Address:** {location[2] if location[2] else 'N/A'}
        """
        
        prompt = f"""
        ### You are an environmental expert. Analyze the following waste classification:
        
        **1. Image Classification Results:**
        {classification_summary}
        
        **2. Location Details:**
        {location_summary}
        ### Required Analysis:
        - Describe the waste detected in the image.
        - Potential health & environmental risks.
        - Recommended disposal methods & precautions.
        - Eco-friendly alternatives.
        """

        model = genai.GenerativeModel("gemini-1.5-flash")
        response = model.generate_content(prompt)
        return response.text if response else "⚠️ No response received."
    except Exception as e:
        st.error(f"⚠️ Error using Generative AI: {e}")
        return None

# Extract query parameters
query_params = st.experimental_get_query_params()
latitude = query_params.get("lat", [""])[0]
longitude = query_params.get("lon", [""])[0]
address = query_params.get("addr", [""])[0]

# Display detected location
st.header("📍 Detected Location")
st.success(f"**Latitude:** {latitude}")
st.success(f"**Longitude:** {longitude}")
st.success(f"**Address:** {address}")

# Streamlit UI
st.title("🗑️ BinSight: Upload Dustbin Image")

uploaded_file = st.file_uploader("📷 Upload a dustbin image", type=["jpg", "jpeg", "png"])
if uploaded_file:
    image = Image.open(uploaded_file)
    st.image(image, caption="📸 Uploaded Image", use_column_width=True)
    
    image_base64 = convert_image_to_base64(image)
    classification_results = classify_image(image)
    
    st.header("🧪 Classification Results")
    for label, confidence in classification_results.items():
        st.write(f"✅ **{label}:** {confidence}%")
    
    if not is_dustbin_image(classification_results):
        st.error("⚠️ Please upload a valid dustbin image. No dustbin detected in the image.")
        st.stop()

    st.header("🧠 AI Analysis & Recommendations")
    gemini_response = get_genai_response(classification_results, (latitude, longitude, address))
    st.write(gemini_response)
    
    dustbin_data = {
        "latitude": latitude,
        "longitude": longitude,
        "address": address,
        "classification": classification_results,
        "allocated_truck": None,
        "status": "Pending",
        "image": image_base64
    }
    
    db.reference("dustbins").push(dustbin_data)
    st.success("✅ Dustbin data uploaded successfully!")
    
    # Thank You Message with Styling
    st.markdown(
        """
        <div style="
            background-color: #DFF2BF;
            color: #4F8A10;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            font-size: 18px;
            margin-top: 20px;">
            🎉 <b>Thank You for Your Contribution!</b> 🎉<br><br>
            Your effort in uploading this image helps keep our environment clean and green. 🌱♻️<br>
            Together, we make a difference! 🙌
        </div>
        """, unsafe_allow_html=True
    )

# Back button to redirect to dashboard
# st.markdown("<br>", unsafe_allow_html=True)
# st.markdown("<a href='https://binsight.onrender.com/dashboard.html' target='_self' style='text-decoration:none;'><button style='padding: 10px 20px; font-size: 16px;'>⬅ Back to Dashboard</button></a>", unsafe_allow_html=True)










# Best version without back button


# import streamlit as st
# import requests
# import google.generativeai as genai
# import firebase_admin
# from firebase_admin import credentials, db
# from PIL import Image
# import numpy as np
# import base64
# from io import BytesIO
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input

# # Initialize Firebase
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Configure Gemini 2.0 Flash (gemini-1.5-flash)
# genai.configure(api_key="AIzaSyBREh8Uei7uDCbzPaYW2WdalOdjVWcQLAM")  # Replace with actual API key

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify image
# def classify_image(image):
#     img = image.resize((224, 224))
#     img_array = np.array(img)
#     img_array = np.expand_dims(img_array, axis=0)
#     img_array = preprocess_input(img_array)
#     predictions = mobilenet_model.predict(img_array)
#     labels = decode_predictions(predictions, top=5)[0]
#     return {label[1]: round(float(label[2]) * 100, 2) for label in labels}

# # Function to check if image is a dustbin
# def is_dustbin_image(classification_results):
#     dustbin_keywords = ["trash", "bin", "garbage", "waste", "dustbin", "ashcan", "recycle", "rubbish"]
#     return any(any(keyword in label.lower() for keyword in dustbin_keywords) for label in classification_results.keys())

# # Function to convert image to Base64
# def convert_image_to_base64(image):
#     buffered = BytesIO()
#     image.save(buffered, format="PNG")
#     return base64.b64encode(buffered.getvalue()).decode()

# # Function to generate AI recommendations using Gemini 2.0 Flash
# def get_genai_response(classification_results, location):
#     try:
#         classification_summary = "\n".join([f"- **{label}:** {score}%" for label, score in classification_results.items()])
#         location_summary = f"""
#         - **Latitude:** {location[0] if location[0] else 'N/A'}
#         - **Longitude:** {location[1] if location[1] else 'N/A'}
#         - **Address:** {location[2] if location[2] else 'N/A'}
#         """
        
#         prompt = f"""
#         ### You are an environmental expert. Analyze the following waste classification:
        
#         **1. Image Classification Results:**
#         {classification_summary}
        
#         **2. Location Details:**
#         {location_summary}

#         ### Required Analysis:
#         - Describe the waste detected in the image.
#         - Potential health & environmental risks.
#         - Recommended disposal methods & precautions.
#         - Eco-friendly alternatives.
#         """

#         model = genai.GenerativeModel("gemini-1.5-flash")
#         response = model.generate_content(prompt)
#         return response.text if response else "⚠️ No response received."
#     except Exception as e:
#         st.error(f"⚠️ Error using Generative AI: {e}")
#         return None

# # Extract query parameters
# query_params = st.experimental_get_query_params()
# latitude = query_params.get("lat", [""])[0]
# longitude = query_params.get("lon", [""])[0]
# address = query_params.get("addr", [""])[0]

# # Display detected location
# st.header("📍 Detected Location")
# st.success(f"**Latitude:** {latitude}")
# st.success(f"**Longitude:** {longitude}")
# st.success(f"**Address:** {address}")

# # Streamlit UI
# st.title("🗑️ BinSight: Upload Dustbin Image")

# uploaded_file = st.file_uploader("📷 Upload a dustbin image", type=["jpg", "jpeg", "png"])
# if uploaded_file:
#     image = Image.open(uploaded_file)
#     st.image(image, caption="📸 Uploaded Image", use_column_width=True)
    
#     image_base64 = convert_image_to_base64(image)
#     classification_results = classify_image(image)
    
#     st.header("🧪 Classification Results")
#     for label, confidence in classification_results.items():
#         st.write(f"✅ **{label}:** {confidence}%")
    
#     if not is_dustbin_image(classification_results):
#         st.error("⚠️ Please upload a valid dustbin image. No dustbin detected in the image.")
#         st.stop()

#     st.header("🧠 AI Analysis & Recommendations")
#     gemini_response = get_genai_response(classification_results, (latitude, longitude, address))
#     st.write(gemini_response)
    
#     dustbin_data = {
#         "latitude": latitude,
#         "longitude": longitude,
#         "address": address,
#         "classification": classification_results,
#         "allocated_truck": None,
#         "status": "Pending",
#         "image": image_base64
#     }
    
#     db.reference("dustbins").push(dustbin_data)
#     st.success("✅ Dustbin data uploaded successfully!")
    
#     # Thank You Message with Styling
#     st.markdown(
#         """
#         <div style="
#             background-color: #DFF2BF;
#             color: #4F8A10;
#             padding: 20px;
#             border-radius: 10px;
#             text-align: center;
#             font-size: 18px;
#             margin-top: 20px;">
#             🎉 <b>Thank You for Your Contribution!</b> 🎉<br><br>
#             Your effort in uploading this image helps keep our environment clean and green. 🌱♻️<br>
#             Together, we make a difference! 🙌
#         </div>
#         """, unsafe_allow_html=True
#     )











# BEST version till now
# import streamlit as st
# import requests
# import google.generativeai as genai
# import firebase_admin
# from firebase_admin import credentials, db
# from PIL import Image
# import numpy as np
# import base64
# from io import BytesIO
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input

# # Initialize Firebase
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Configure Gemini 2.0 Flash (gemini-1.5-flash)
# genai.configure(api_key="AIzaSyBREh8Uei7uDCbzPaYW2WdalOdjVWcQLAM")  # Replace with actual API key

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify image
# def classify_image(image):
#     img = image.resize((224, 224))
#     img_array = np.array(img)
#     img_array = np.expand_dims(img_array, axis=0)
#     img_array = preprocess_input(img_array)
#     predictions = mobilenet_model.predict(img_array)
#     labels = decode_predictions(predictions, top=5)[0]
#     return {label[1]: round(float(label[2]) * 100, 2) for label in labels}  # Convert confidence to percentage

# # Function to check if image is a dustbin
# def is_dustbin_image(classification_results):
#     dustbin_keywords = ["trash", "bin", "garbage", "waste", "dustbin", "ashcan", "recycle", "rubbish"]
#     for label, confidence in classification_results.items():
#         if any(keyword in label.lower() for keyword in dustbin_keywords):
#             return True
#     return False

# # Function to convert image to Base64
# def convert_image_to_base64(image):
#     buffered = BytesIO()
#     image.save(buffered, format="PNG")
#     return base64.b64encode(buffered.getvalue()).decode()

# # Function to generate AI recommendations using Gemini 2.0 Flash
# def get_genai_response(classification_results, location):
#     try:
#         classification_summary = "\n".join([f"- **{label}:** {score}%" for label, score in classification_results.items()])
#         location_summary = f"""
#         - **Latitude:** {location[0] if location[0] else 'N/A'}
#         - **Longitude:** {location[1] if location[1] else 'N/A'}
#         - **Address:** {location[2] if location[2] else 'N/A'}
#         """

#         prompt = f"""
#         ### You are an environmental expert. Analyze the following waste classification:
        
#         **1. Image Classification Results:**
#         {classification_summary}
        
#         **2. Location Details:**
#         {location_summary}

#         ### Required Analysis:
#         - Describe the waste detected in the image.
#         - Potential health & environmental risks.
#         - Recommended disposal methods & precautions.
#         - Eco-friendly alternatives.
#         """

#         model = genai.GenerativeModel("gemini-1.5-flash")  # Using Gemini 2.0 Flash
#         response = model.generate_content(prompt)
#         return response.text if response else "⚠️ No response received."
#     except Exception as e:
#         st.error(f"⚠️ Error using Generative AI: {e}")
#         return None

# # **Fix: Revert to `st.experimental_get_query_params()` for full location display**
# query_params = st.experimental_get_query_params()

# latitude = query_params.get("lat", [""])[0]  # Extract full latitude
# longitude = query_params.get("lon", [""])[0]  # Extract full longitude
# address = query_params.get("addr", [""])[0]  # Extract full address

# # **Ensure full location values are displayed correctly**
# st.header("📍 Detected Location")
# st.success(f"**Latitude:** {latitude}")
# st.success(f"**Longitude:** {longitude}")
# st.success(f"**Address:** {address}")

# # Streamlit App UI
# st.title("🗑️ BinSight: Upload Dustbin Image")

# uploaded_file = st.file_uploader("📷 Upload a dustbin image", type=["jpg", "jpeg", "png"])
# if uploaded_file:
#     image = Image.open(uploaded_file)
#     st.image(image, caption="📸 Uploaded Image", use_container_width=True)

#     # Convert image to Base64
#     image_base64 = convert_image_to_base64(image)

#     # Classify Image
#     classification_results = classify_image(image)

#     # Display classification results
#     st.header("🧪 Classification Results")
#     if classification_results:
#         for label, confidence in classification_results.items():
#             st.write(f"✅ **{label}:** {confidence}%")
#     else:
#         st.error("⚠️ No classification results found.")
#         st.stop()

#     # **NEW CONDITION**: Ensure image is a dustbin before proceeding
#     if not is_dustbin_image(classification_results):
#         st.error("⚠️ Please upload a valid dustbin image. No dustbin detected in the image.")
#         st.stop()

#     # **Generate AI insights (Only Display, Not Store)**
#     st.header("🧠 AI Analysis & Recommendations")
#     gemini_response = get_genai_response(classification_results, (latitude, longitude, address))
#     st.write(gemini_response)

#     # Save only location, classification, and image in Firebase
#     dustbin_data = {
#         "latitude": latitude,
#         "longitude": longitude,
#         "address": address,
#         "classification": classification_results,
#         "allocated_truck": None,
#         "status": "Pending",
#         "image": image_base64
#     }

#     db.reference("dustbins").push(dustbin_data)  # Save data to Firebase
#     st.success("✅ Dustbin data uploaded successfully!")













## working well for embedded in html page but it is not taking full location

#import streamlit as st
# import requests
# import google.generativeai as genai
# import firebase_admin
# from firebase_admin import credentials, db
# from PIL import Image
# import numpy as np
# import base64
# from io import BytesIO
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input

# # Initialize Firebase
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Configure Gemini AI
# genai.configure(api_key="AIzaSyBREh8Uei7uDCbzPaYW2WdalOdjVWcQLAM")  # Replace with your actual API key

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify image
# def classify_image(image):
#     img = image.resize((224, 224))
#     img_array = np.array(img)
#     img_array = np.expand_dims(img_array, axis=0)
#     img_array = preprocess_input(img_array)
#     predictions = mobilenet_model.predict(img_array)
#     labels = decode_predictions(predictions, top=5)[0]
#     return {label[1]: round(float(label[2]) * 100, 2) for label in labels}  # Convert confidence to percentage

# # Function to convert image to Base64
# def convert_image_to_base64(image):
#     buffered = BytesIO()
#     image.save(buffered, format="PNG")
#     return base64.b64encode(buffered.getvalue()).decode()

# # Function to interact with Gemini AI (Only Show Results, Do NOT Save to Firebase)
# def get_genai_response(classification_results, location):
#     try:
#         classification_summary = "\n".join([f"- **{label}:** {score}%" for label, score in classification_results.items()])
#         location_summary = f"""
#         - **Latitude:** {location[0] if location[0] else 'N/A'}
#         - **Longitude:** {location[1] if location[1] else 'N/A'}
#         - **Address:** {location[2] if location[2] else 'N/A'}
#         """

#         prompt = f"""
#         ### You are an environmental expert. Analyze the following waste classification:
        
#         **1. Image Classification Results:**
#         {classification_summary}
        
#         **2. Location Details:**
#         {location_summary}

#         ### Required Analysis:
#         - Describe the waste detected in the image.
#         - Potential health & environmental risks.
#         - Recommended disposal methods & precautions.
#         - Eco-friendly alternatives.
#         """

#         model = genai.GenerativeModel("gemini-1.5-flash")
#         response = model.generate_content(prompt)
#         return response.text if response else "⚠️ No response received."
#     except Exception as e:
#         st.error(f"⚠️ Error using Generative AI: {e}")
#         return None

# # Extract location data from URL parameters
# query_params = st.query_params
# latitude = str(query_params.get("lat", [None])[0])  # Convert to string
# longitude = str(query_params.get("lon", [None])[0])  # Convert to string
# address = str(query_params.get("addr", [""])[0])  # Convert to full address

# # Display user location
# st.header("📍 Detected Location")
# if latitude and longitude:
#     st.success(f"**Latitude:** {latitude}, **Longitude:** {longitude}")
#     st.success(f"**Address:** {address}")
# else:
#     st.error("⚠️ Location data not received. Enable location detection in the main page.")

# # Streamlit App UI
# st.title("🗑️ BinSight: Upload Dustbin Image")

# uploaded_file = st.file_uploader("📷 Upload a dustbin image", type=["jpg", "jpeg", "png"])
# if uploaded_file:
#     image = Image.open(uploaded_file)
#     st.image(image, caption="📸 Uploaded Image", use_container_width=True)

#     # Convert image to Base64
#     image_base64 = convert_image_to_base64(image)

#     # Classify Image
#     classification_results = classify_image(image)

#     # Display classification results
#     st.header("🧪 Classification Results")
#     if classification_results:
#         for label, confidence in classification_results.items():
#             st.write(f"✅ **{label}:** {confidence}%")
#     else:
#         st.error("⚠️ No classification results found.")

#     # Get AI insights but DO NOT save to Firebase
#     st.header("🧠 AI Analysis & Recommendations")
#     gemini_response = get_genai_response(classification_results, (latitude, longitude, address))
#     st.write(gemini_response)

#     # Save only location, classification, and image in Firebase
#     dustbin_data = {
#         "latitude": latitude,
#         "longitude": longitude,
#         "address": address,
#         "classification": classification_results,
#         "allocated_truck": None,
#         "status": "Pending",
#         "image": image_base64
#     }

#     db.reference("dustbins").push(dustbin_data)  # Save data to Firebase
#     st.success("✅ Dustbin data uploaded successfully!")













## Best but not working location proper

# import streamlit as st
# import requests
# import firebase_admin
# from firebase_admin import credentials, db, auth
# from PIL import Image
# import numpy as np
# from geopy.geocoders import Nominatim
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
# import json
# import base64
# from io import BytesIO

# # Initialize Firebase (Check if already initialized)
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify the uploaded image using MobileNetV2
# def classify_image_with_mobilenet(image):
#     try:
#         img = image.resize((224, 224))
#         img_array = np.array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array = preprocess_input(img_array)
#         predictions = mobilenet_model.predict(img_array)
#         labels = decode_predictions(predictions, top=5)[0]
#         return {label[1]: float(label[2]) for label in labels}
#     except Exception as e:
#         st.error(f"Error during image classification: {e}")
#         return {}

# # Function to get user's location
# def get_user_location():
#     st.write("Fetching location, please allow location access in your browser.")
#     geolocator = Nominatim(user_agent="binsight")
#     try:
#         ip_info = requests.get("https://ipinfo.io/json").json()
#         loc = ip_info.get("loc", "").split(",")
#         latitude, longitude = loc[0], loc[1] if len(loc) == 2 else (None, None)
#         if latitude and longitude:
#             address = geolocator.reverse(f"{latitude}, {longitude}").address
#             return latitude, longitude, address
#     except Exception as e:
#         st.error(f"Error retrieving location: {e}")
#     return None, None, None

# # Function to convert image to Base64
# def convert_image_to_base64(image):
#     buffered = BytesIO()
#     image.save(buffered, format="PNG")  # Convert to PNG format
#     img_str = base64.b64encode(buffered.getvalue()).decode()  # Encode as Base64
#     return img_str

# # User Login
# st.sidebar.header("User Login")
# user_email = st.sidebar.text_input("Enter your email")
# login_button = st.sidebar.button("Login")

# if login_button:
#     if user_email:
#         st.session_state["user_email"] = user_email
#         st.sidebar.success(f"Logged in as {user_email}")

# if "user_email" not in st.session_state:
#     st.warning("Please log in first.")
#     st.stop()

# # Get user location
# latitude, longitude, address = get_user_location()
# if latitude and longitude:
#     st.success(f"Location detected: {address}")
# else:
#     st.warning("Unable to fetch location, please enable location access.")
#     st.stop()

# # Streamlit App
# st.title("BinSight: Upload Dustbin Image")

# uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"])
# submit_button = st.button("Analyze and Upload")

# if submit_button and uploaded_file:
#     image = Image.open(uploaded_file)
#     st.image(image, caption="Uploaded Image", use_container_width=True)

#     # Convert image to Base64
#     image_base64 = convert_image_to_base64(image)

#     # Classify Image
#     classification_results = classify_image_with_mobilenet(image)
    
#     if classification_results:
#         db_ref = db.reference("dustbins")
#         dustbin_data = {
#             "user_email": st.session_state["user_email"],
#             "latitude": latitude,
#             "longitude": longitude,
#             "address": address,
#             "classification": classification_results,
#             "allocated_truck": None,
#             "status": "Pending",
#             "image": image_base64  # Store image as Base64 string
#         }
#         db_ref.push(dustbin_data)
#         st.success("Dustbin data uploaded successfully!")
#         st.write(f"**Location:** {address}")
#         st.write(f"**Latitude:** {latitude}, **Longitude:** {longitude}")
#     else:
#         st.error("Missing classification details. Cannot upload.")








# best without image

# import streamlit as st
# import requests
# import firebase_admin
# from firebase_admin import credentials, db, auth
# from PIL import Image
# import numpy as np
# from geopy.geocoders import Nominatim
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
# import json

# # Initialize Firebase
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify the uploaded image using MobileNetV2
# def classify_image_with_mobilenet(image):
#     try:
#         img = image.resize((224, 224))
#         img_array = np.array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array = preprocess_input(img_array)
#         predictions = mobilenet_model.predict(img_array)
#         labels = decode_predictions(predictions, top=5)[0]
#         return {label[1]: float(label[2]) for label in labels}
#     except Exception as e:
#         st.error(f"Error during image classification: {e}")
#         return {}

# # Function to get user's location using geolocation API
# def get_user_location():
#     st.write("Fetching location, please allow location access in your browser.")
#     geolocator = Nominatim(user_agent="binsight")
#     try:
#         ip_info = requests.get("https://ipinfo.io/json").json()
#         loc = ip_info.get("loc", "").split(",")
#         latitude, longitude = loc[0], loc[1] if len(loc) == 2 else (None, None)
#         if latitude and longitude:
#             address = geolocator.reverse(f"{latitude}, {longitude}").address
#             return latitude, longitude, address
#     except Exception as e:
#         st.error(f"Error retrieving location: {e}")
#     return None, None, None

# # User Login
# st.sidebar.header("User Login")
# user_email = st.sidebar.text_input("Enter your email")
# login_button = st.sidebar.button("Login")

# if login_button:
#     if user_email:
#         st.session_state["user_email"] = user_email
#         st.sidebar.success(f"Logged in as {user_email}")

# if "user_email" not in st.session_state:
#     st.warning("Please log in first.")
#     st.stop()

# # Get user location and display details
# latitude, longitude, address = get_user_location()
# if latitude and longitude:
#     st.success(f"Location detected: {address}")
# else:
#     st.warning("Unable to fetch location, please ensure location access is enabled.")
#     st.stop()

# # Streamlit App
# st.title("BinSight: Upload Dustbin Image")

# uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"])
# submit_button = st.button("Analyze and Upload")

# if submit_button and uploaded_file:
#     image = Image.open(uploaded_file)
#     st.image(image, caption="Uploaded Image", use_container_width=True)

#     classification_results = classify_image_with_mobilenet(image)
    
#     if classification_results:
#         db_ref = db.reference("dustbins")
#         dustbin_data = {
#             "user_email": st.session_state["user_email"],
#             "latitude": latitude,
#             "longitude": longitude,
#             "address": address,
#             "classification": classification_results,
#             "allocated_truck": None,
#             "status": "Pending"
#         }
#         db_ref.push(dustbin_data)
#         st.success("Dustbin data uploaded successfully!")
#         st.write(f"**Location:** {address}")
#         st.write(f"**Latitude:** {latitude}, **Longitude:** {longitude}")
#     else:
#         st.error("Missing classification details. Cannot upload.")







# best with firebase but below code is not giving correct location of user.

# import streamlit as st
# import requests
# import firebase_admin
# from firebase_admin import credentials, db, auth
# from PIL import Image
# import numpy as np
# from geopy.geocoders import Nominatim
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input

# # Initialize Firebase
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify the uploaded image using MobileNetV2
# def classify_image_with_mobilenet(image):
#     try:
#         img = image.resize((224, 224))
#         img_array = np.array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array = preprocess_input(img_array)
#         predictions = mobilenet_model.predict(img_array)
#         labels = decode_predictions(predictions, top=5)[0]
#         return {label[1]: float(label[2]) for label in labels}
#     except Exception as e:
#         st.error(f"Error during image classification: {e}")
#         return {}

# # Function to get user's location
# def get_user_location():
#     try:
#         ip_info = requests.get("https://ipinfo.io/json").json()
#         location = ip_info.get("loc", "").split(",")
#         latitude = location[0] if len(location) > 0 else None
#         longitude = location[1] if len(location) > 1 else None

#         if latitude and longitude:
#             geolocator = Nominatim(user_agent="binsight")
#             address = geolocator.reverse(f"{latitude}, {longitude}").address
#             return latitude, longitude, address
#         return None, None, None
#     except Exception as e:
#         st.error(f"Unable to get location: {e}")
#         return None, None, None

# # User Login
# st.sidebar.header("User Login")
# user_email = st.sidebar.text_input("Enter your email")
# login_button = st.sidebar.button("Login")

# if login_button:
#     if user_email:
#         st.session_state["user_email"] = user_email
#         st.sidebar.success(f"Logged in as {user_email}")

# if "user_email" not in st.session_state:
#     st.warning("Please log in first.")
#     st.stop()

# # Streamlit App
# st.title("BinSight: Upload Dustbin Image")

# uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"])
# submit_button = st.button("Analyze and Upload")

# if submit_button and uploaded_file:
#     image = Image.open(uploaded_file)
#     st.image(image, caption="Uploaded Image", use_container_width=True)

#     classification_results = classify_image_with_mobilenet(image)
#     latitude, longitude, address = get_user_location()

#     if latitude and longitude and classification_results:
#         db_ref = db.reference("dustbins")
#         dustbin_data = {
#             "user_email": st.session_state["user_email"],
#             "latitude": latitude,
#             "longitude": longitude,
#             "address": address,
#             "classification": classification_results,
#             "allocated_truck": None,
#             "status": "Pending"
#         }
#         db_ref.push(dustbin_data)
#         st.success("Dustbin data uploaded successfully!")
#     else:
#         st.error("Missing classification or location details. Cannot upload.")











# Below is the old version but it is without of firebase and here is the addition of gemini.

# import streamlit as st
# import os
# from PIL import Image
# import numpy as np
# from io import BytesIO
# from dotenv import load_dotenv
# from geopy.geocoders import Nominatim
# from tensorflow.keras.applications import MobileNetV2
# from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
# import requests
# import google.generativeai as genai

# # Load environment variables
# load_dotenv()

# # Configure Generative AI
# genai.configure(api_key='AIzaSyBREh8Uei7uDCbzPaYW2WdalOdjVWcQLAM')

# # Load MobileNetV2 pre-trained model
# mobilenet_model = MobileNetV2(weights="imagenet")

# # Function to classify the uploaded image using MobileNetV2
# def classify_image_with_mobilenet(image):
#     try:
#         img = image.resize((224, 224))
#         img_array = np.array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array = preprocess_input(img_array)
#         predictions = mobilenet_model.predict(img_array)
#         labels = decode_predictions(predictions, top=5)[0]
#         return {label[1]: float(label[2]) for label in labels}
#     except Exception as e:
#         st.error(f"Error during image classification: {e}")
#         return {}

# # Function to get user's location
# def get_user_location():
#     try:
#         ip_info = requests.get("https://ipinfo.io/json").json()
#         location = ip_info.get("loc", "").split(",")
#         latitude = location[0] if len(location) > 0 else None
#         longitude = location[1] if len(location) > 1 else None

#         if latitude and longitude:
#             geolocator = Nominatim(user_agent="binsight")
#             address = geolocator.reverse(f"{latitude}, {longitude}").address
#             return latitude, longitude, address
#         return None, None, None
#     except Exception as e:
#         st.error(f"Unable to get location: {e}")
#         return None, None, None

# # Function to get nearest municipal details with contact info
# def get_nearest_municipal_details(latitude, longitude):
#     try:
#         if latitude and longitude:
#             # Simulating municipal service retrieval
#             municipal_services = [
#                 {"latitude": "12.9716", "longitude": "77.5946", "office": "Bangalore Municipal Office", "phone": "+91-80-12345678"},
#                 {"latitude": "28.7041", "longitude": "77.1025", "office": "Delhi Municipal Office", "phone": "+91-11-98765432"},
#                 {"latitude": "19.0760", "longitude": "72.8777", "office": "Mumbai Municipal Office", "phone": "+91-22-22334455"},
#             ]

#             # Find the nearest municipal service (mock logic: matching first two decimal points)
#             for service in municipal_services:
#                 if str(latitude).startswith(service["latitude"][:5]) and str(longitude).startswith(service["longitude"][:5]):
#                     return f"""
#                     **Office**: {service['office']}  
#                     **Phone**: {service['phone']}  
#                     """
#             return "No nearby municipal office found. Please check manually."
#         else:
#             return "Location not available. Unable to fetch municipal details."
#     except Exception as e:
#         st.error(f"Unable to fetch municipal details: {e}")
#         return None

# # Function to interact with Generative AI
# def get_genai_response(classification_results, location):
#     try:
#         classification_summary = "\n".join([f"{label}: {score:.2f}" for label, score in classification_results.items()])
#         location_summary = f"""
#         Latitude: {location[0] if location[0] else 'N/A'}
#         Longitude: {location[1] if location[1] else 'N/A'}
#         Address: {location[2] if location[2] else 'N/A'}
#         """
#         prompt = f"""
#         ### You are an environmental expert. Analyze the following:
#         1. **Image Classification**:
#            - {classification_summary}
#         2. **Location**:
#            - {location_summary}

#         ### Output Required:
#         1. Detailed insights about the waste detected in the image.
#         2. Specific health risks associated with the detected waste type.
#         3. Precautions to mitigate these health risks.
#         4. Recommendations for proper disposal.
#         """
#         model = genai.GenerativeModel('gemini-pro')
#         response = model.generate_content(prompt)
#         return response
#     except Exception as e:
#         st.error(f"Error using Generative AI: {e}")
#         return None

# # Function to display Generative AI response
# def display_genai_response(response):
#     st.subheader("Detailed Analysis and Recommendations")
#     if response and response.candidates:
#         response_content = response.candidates[0].content.parts[0].text if response.candidates[0].content.parts else ""
#         st.write(response_content)
#     else:
#         st.write("No response received from Generative AI or quota exceeded.")

# # Streamlit App
# st.title("BinSight: AI-Powered Dustbin and Waste Analysis System")
# st.text("Upload a dustbin image and get AI-powered analysis of the waste and associated health recommendations.")

# uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"], help="Upload a clear image of a dustbin for analysis.")
# submit_button = st.button("Analyze Dustbin")

# if submit_button:
#     if uploaded_file is not None:
#         image = Image.open(uploaded_file)
#         st.image(image, caption="Uploaded Image", use_container_width =True)

#         # Classify the image using MobileNetV2
#         st.subheader("Image Classification")
#         classification_results = classify_image_with_mobilenet(image)
#         for label, score in classification_results.items():
#             st.write(f"- **{label}**: {score:.2f}")

#         # Get user location
#         location = get_user_location()
#         latitude, longitude, address = location

#         st.subheader("User Location")
#         st.write(f"Latitude: {latitude if latitude else 'N/A'}")
#         st.write(f"Longitude: {longitude if longitude else 'N/A'}")
#         st.write(f"Address: {address if address else 'N/A'}")

#         # Get nearest municipal details with contact info
#         st.subheader("Nearest Municipal Details")
#         municipal_details = get_nearest_municipal_details(latitude, longitude)
#         st.write(municipal_details)

#         # Generate detailed analysis with Generative AI
#         if classification_results:
#             response = get_genai_response(classification_results, location)
#             display_genai_response(response)
#     else:
#         st.write("Please upload an image for analysis.")











# # import streamlit as st
# # import os
# # from PIL import Image
# # import numpy as np
# # from io import BytesIO
# # from dotenv import load_dotenv
# # from geopy.geocoders import Nominatim
# # from tensorflow.keras.applications import MobileNetV2
# # from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
# # import requests
# # import google.generativeai as genai

# # # Load environment variables
# # load_dotenv()

# # # Configure Generative AI
# # genai.configure(api_key='AIzaSyBREh8Uei7uDCbzPaYW2WdalOdjVWcQLAM')

# # # Load MobileNetV2 pre-trained model
# # mobilenet_model = MobileNetV2(weights="imagenet")

# # # Function to classify the uploaded image using MobileNetV2
# # def classify_image_with_mobilenet(image):
# #     try:
# #         # Resize the image to the input size of MobileNetV2
# #         img = image.resize((224, 224))
# #         img_array = np.array(img)
# #         img_array = np.expand_dims(img_array, axis=0)
# #         img_array = preprocess_input(img_array)

# #         # Predict using the MobileNetV2 model
# #         predictions = mobilenet_model.predict(img_array)
# #         labels = decode_predictions(predictions, top=5)[0]
# #         return {label[1]: float(label[2]) for label in labels}
# #     except Exception as e:
# #         st.error(f"Error during image classification: {e}")
# #         return {}

# # # Function to get user's location
# # def get_user_location():
# #     try:
# #         # Fetch location using the IPInfo API
# #         ip_info = requests.get("https://ipinfo.io/json").json()
# #         location = ip_info.get("loc", "").split(",")
# #         latitude = location[0] if len(location) > 0 else None
# #         longitude = location[1] if len(location) > 1 else None

# #         if latitude and longitude:
# #             geolocator = Nominatim(user_agent="binsight")
# #             address = geolocator.reverse(f"{latitude}, {longitude}").address
# #             return latitude, longitude, address
# #         return None, None, None
# #     except Exception as e:
# #         st.error(f"Unable to get location: {e}")
# #         return None, None, None

# # # Function to get nearest municipal details
# # def get_nearest_municipal_details(latitude, longitude):
# #     try:
# #         if latitude and longitude:
# #             # Simulating municipal service retrieval
# #             return f"The nearest municipal office is at ({latitude}, {longitude}). Please contact your local authority for waste management services."
# #         else:
# #             return "Location not available. Unable to fetch municipal details."
# #     except Exception as e:
# #         st.error(f"Unable to fetch municipal details: {e}")
# #         return None

# # # Function to interact with Generative AI
# # def get_genai_response(classification_results, location):
# #     try:
# #         # Construct prompt for Generative AI
# #         classification_summary = "\n".join([f"{label}: {score:.2f}" for label, score in classification_results.items()])
# #         location_summary = f"""
# #         Latitude: {location[0] if location[0] else 'N/A'}
# #         Longitude: {location[1] if location[1] else 'N/A'}
# #         Address: {location[2] if location[2] else 'N/A'}
# #         """
# #         prompt = f"""
# #         ### You are an environmental expert. Analyze the following:
# #         1. **Image Classification**:
# #            - {classification_summary}
# #         2. **Location**:
# #            - {location_summary}

# #         ### Output Required:
# #         1. Detailed insights about the waste detected in the image.
# #         2. Specific health risks associated with the detected waste type.
# #         3. Precautions to mitigate these health risks.
# #         4. Recommendations for proper disposal.
# #         """

# #         model = genai.GenerativeModel('gemini-pro')
# #         response = model.generate_content(prompt)
# #         return response
# #     except Exception as e:
# #         st.error(f"Error using Generative AI: {e}")
# #         return None

# # # Function to display Generative AI response
# # def display_genai_response(response):
# #     st.subheader("Detailed Analysis and Recommendations")
# #     if response and response.candidates:
# #         response_content = response.candidates[0].content.parts[0].text if response.candidates[0].content.parts else ""
# #         st.write(response_content)
# #     else:
# #         st.write("No response received from Generative AI or quota exceeded.")

# # # Streamlit App
# # st.title("BinSight: AI-Powered Dustbin and Waste Analysis System")
# # st.text("Upload a dustbin image and get AI-powered analysis of the waste and associated health recommendations.")

# # uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"], help="Upload a clear image of a dustbin for analysis.")
# # submit_button = st.button("Analyze Dustbin")

# # if submit_button:
# #     if uploaded_file is not None:
# #         image = Image.open(uploaded_file)
# #         st.image(image, caption="Uploaded Image", use_column_width=True)

# #         # Classify the image using MobileNetV2
# #         st.subheader("Image Classification")
# #         classification_results = classify_image_with_mobilenet(image)
# #         for label, score in classification_results.items():
# #             st.write(f"- **{label}**: {score:.2f}")

# #         # Get user location
# #         location = get_user_location()
# #         latitude, longitude, address = location

# #         st.subheader("User Location")
# #         st.write(f"Latitude: {latitude if latitude else 'N/A'}")
# #         st.write(f"Longitude: {longitude if longitude else 'N/A'}")
# #         st.write(f"Address: {address if address else 'N/A'}")

# #         # Get nearest municipal details
# #         st.subheader("Nearest Municipal Details")
# #         municipal_details = get_nearest_municipal_details(latitude, longitude)
# #         st.write(municipal_details)

# #         # Generate detailed analysis with Generative AI
# #         if classification_results:
# #             response = get_genai_response(classification_results, location)
# #             display_genai_response(response)
# #     else:
# #         st.write("Please upload an image for analysis.")