File size: 56,740 Bytes
db126ec
 
 
 
 
 
 
 
 
ffc0163
a2140b7
db126ec
 
 
a2140b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3e0c92
a2140b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3e0c92
a2140b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f2ed30
86cdbc1
a2140b7
 
3f2ed30
 
 
a2140b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d62b6e
a2140b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db126ec
 
536eb35
db126ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4b5be8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db126ec
d4b5be8
 
 
 
 
 
 
 
 
 
 
 
 
db126ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
import gradio as gr
import pandas as pd
import numpy as np
import joblib
import plotly.graph_objects as go
import plotly.express as px
from huggingface_hub import hf_hub_download
import os
from pathlib import Path
import warnings
import os
warnings.filterwarnings('ignore')
import re
from groq import Groq
import folium
from folium.plugins import MarkerCluster
import io
from fastapi import FastAPI, HTTPException

app = FastAPI()

# Initialize Groq client

groq_api_key = os.getenv("GROQ_API_KEY")
if groq_api_key:
    #client = Groq(api_key=groq_api_key)
    client = Groq(api_key=groq_api_key) if groq_api_key else None
else:
    print("โš ๏ธ  GROQ_API_KEY not found. Chat functionality will be limited.")
    client = None


@app.post("/chat")
async def chat(prompt: str):
    if client is None:
        raise HTTPException(
            status_code=503,
            detail="โš ๏ธ Chat service is unavailable because GROQ_API_KEY is missing."
        )

    try:
        response = client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[{"role": "user", "content": prompt}]
        )
        return {"reply": response.choices[0].message["content"]}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Try to import xgboost, but fallback to scikit-learn
try:
    import xgboost as xgb
    XGB_AVAILABLE = True
    print("โœ… XGBoost is available")
except ImportError:
    XGB_AVAILABLE = False
    print("โš ๏ธ  XGBoost not available, using scikit-learn models")
    from sklearn.ensemble import RandomForestRegressor

# Load map data
try:
    hf_raw_url = 'https://huggingface.co/spaces/Lesterchia174/FPOC_HDB_Price_Predictor_AI_chat_Assistant/resolve/main/Based_Resale_Prices_2025_with_coords.csv'
    map_df = pd.read_csv(hf_raw_url)
    
    # Convert 'remaining_lease' to a numeric type, converting non-numeric values to NaN
    map_df['remaining_lease'] = pd.to_numeric(map_df['remaining_lease'], errors='coerce')
    
    # Drop rows where the conversion resulted in NaN
    map_df.dropna(subset=['remaining_lease'], inplace=True)

    # Pre-calculate min/max for Gradio sliders using the 'resale_price' column
    min_lease_val = int(map_df['remaining_lease'].min())
    max_lease_val = int(map_df['remaining_lease'].max())
    min_price_val = int(map_df['resale_price'].min())
    max_price_val = int(map_df['resale_price'].max())

    # Get unique values for dropdowns
    town_options = ['ALL'] + sorted(list(map_df['town'].unique()))
    flat_type_options = ['ALL'] + sorted(list(map_df['flat_type'].unique()))
    flat_model_options = ['ALL'] + sorted(list(map_df['flat_model'].unique()))
except Exception as e:
    print(f"Error loading the map dataset: {e}")
    map_df = None

def create_dummy_model(model_type):
    """Create a realistic dummy model that has all required methods"""
    class RealisticDummyModel:
        def __init__(self, model_type):
            self.model_type = model_type
            self.n_features_in_ = 9
            self.feature_names_in_ = [
                'floor_area_sqm', 'storey_level', 'flat_age', 'remaining_lease',
                'transaction_year', 'flat_type_encoded', 'town_encoded',
                'flat_model_encoded', 'dummy_feature'
            ]
            # Add methods that might be called by joblib or other code
            self.get_params = lambda deep=True: {}
            self.set_params = lambda **params: self

        def predict(self, X):
            # Realistic prediction logic
            if isinstance(X, np.ndarray) and len(X.shape) == 2:
                X = X[0]  # Take first row if it's a 2D array

            floor_area = X[0]
            storey_level = X[1]
            flat_age = X[2]
            town_encoded = X[6]
            flat_type_encoded = X[5]

            base_price = floor_area * (4800 + town_encoded * 200)
            storey_bonus = storey_level * 2500
            age_discount = flat_age * 1800

            price = base_price + storey_bonus - age_discount + 35000
            if storey_level > 20: price += 15000
            if flat_age < 10: price += 20000

            return np.array([max(300000, price)])

    return RealisticDummyModel(model_type)()

def safe_joblib_load(filepath):
    """Safely load joblib file with error handling"""
    try:
        model = joblib.load(filepath)
        print(f"โœ… Successfully loaded model from {filepath}")

        # Check if model has required methods
        if not hasattr(model, 'predict'):
            print("โŒ Loaded object doesn't have predict method")
            return None

        # Add missing methods if needed
        if not hasattr(model, 'get_params'):
            model.get_params = lambda deep=True: {}
        if not hasattr(model, 'set_params'):
            model.set_params = lambda **params: model

        return model

    except Exception as e:
        print(f"โŒ Error loading model from {filepath}: {e}")
        return None

def load_models():
    """Load models with robust error handling"""
    models = {}

    # Try to load XGBoost model
    try:
        xgboost_path = hf_hub_download(
            repo_id="Lesterchia174/FPOC_HDB_Price_Predictor_AI_chat_Assistant",         
            filename="best_model_xgboost.joblib",
            repo_type="space"
        )
        models['xgboost'] = safe_joblib_load(xgboost_path)
        if models['xgboost'] is None:
            print("โš ๏ธ  Creating dummy model for XGBoost")
            models['xgboost'] = create_dummy_model("xgboost")
        else:
            print("โœ… XGBoost model loaded and validated")

    except Exception as e:
        print(f"โŒ Error downloading XGBoost model: {e}")
        print("โš ๏ธ  Creating dummy model for XGBoost")
        models['xgboost'] = create_dummy_model("xgboost")

    return models

def load_data():
    """Load data using Hugging Face Hub"""
    try:
        data_path = hf_hub_download(
            repo_id="Lesterchia174/FPOC_HDB_Price_Predictor_AI_chat_Assistant",
            filename="base_hdb_resale_prices_2015Jan-2025Jun_processed.csv",
            repo_type="space"
        )
        df = pd.read_csv(data_path)
        print("โœ… Data loaded successfully via Hugging Face Hub")
        return df
    except Exception as e:
        print(f"โŒ Error loading data: {e}")
        return create_sample_data()

def create_sample_data():
    """Create sample data if real data isn't available"""
    np.random.seed(42)
    towns = ['ANG MO KIO', 'BEDOK', 'TAMPINES', 'WOODLANDS', 'JURONG WEST']
    flat_types = ['4 ROOM', '5 ROOM', 'EXECUTIVE']
    flat_models = ['Improved', 'Model A', 'New Generation']

    data = []
    for _ in range(100):
        town = np.random.choice(towns)
        flat_type = np.random.choice(flat_types)
        flat_model = np.random.choice(flat_models)
        floor_area = np.random.randint(85, 150)
        storey = np.random.randint(1, 25)
        age = np.random.randint(0, 40)

        base_price = floor_area * 5000
        town_bonus = towns.index(town) * 20000
        storey_bonus = storey * 2000
        age_discount = age * 1500
        flat_type_bonus = flat_types.index(flat_type) * 30000

        resale_price = base_price + town_bonus + storey_bonus - age_discount + flat_type_bonus
        resale_price = max(300000, resale_price + np.random.randint(-20000, 20000))

        data.append({
            'town': town, 'flat_type': flat_type, 'flat_model': flat_model,
            'floor_area_sqm': floor_area, 'storey_level': storey,
            'flat_age': age, 'resale_price': resale_price
        })

    return pd.DataFrame(data)

def preprocess_input(user_input, model_type='xgboost'):
    """Preprocess user input for prediction with correct feature mapping"""
    # Flat type mapping
    flat_type_mapping = {'1 ROOM': 1, '2 ROOM': 2, '3 ROOM': 3, '4 ROOM': 4,
                         '5 ROOM': 5, 'EXECUTIVE': 6, 'MULTI-GENERATION': 7}

    # Town mapping
    town_mapping = {
        'SENGKANG': 0, 'WOODLANDS': 1, 'TAMPINES': 2, 'PUNGGOL': 3,
        'JURONG WEST': 4, 'YISHUN': 5, 'BEDOK': 6, 'HOUGANG': 7,
        'CHOA CHU KANG': 8, 'ANG MO KIO': 9
    }

    # Flat model mapping
    flat_model_mapping = {
        'Model A': 0, 'Improved': 1, 'New Generation': 2,
        'Standard': 3, 'Premium': 4
    }

    # Create input array with features
    input_features = [
        user_input['floor_area_sqm'],           # Feature 1
        user_input['storey_level'],             # Feature 2
        user_input['flat_age'],                 # Feature 3
        99 - user_input['flat_age'],            # Feature 4: remaining_lease
        2025,                                   # Feature 5: transaction_year
        flat_type_mapping.get(user_input['flat_type'], 4),  # Feature 6: flat_type_ordinal
        town_mapping.get(user_input['town'], 0),           # Feature 7: town_encoded
        flat_model_mapping.get(user_input['flat_model'], 0), # Feature 8: flat_model_encoded
        1                                       # Feature 9: (placeholder)
    ]

    return np.array([input_features])

def create_market_insights_chart(data, user_input, predicted_price):
    """Create market insights visualization"""
    if data is None or len(data) == 0:
        return None

    similar_properties = data[
        (data['flat_type'] == user_input['flat_type']) &
        (data['town'] == user_input['town'])
    ]

    if len(similar_properties) < 5:
        similar_properties = data[data['flat_type'] == user_input['flat_type']]

    if len(similar_properties) > 0:
        fig = px.scatter(similar_properties, x='floor_area_sqm', y='resale_price',
                         color='flat_model',
                         title=f"Market Position: {user_input['flat_type']} in {user_input['town']}",
                         labels={'floor_area_sqm': 'Floor Area (sqm)', 'resale_price': 'Resale Price (SGD)'})

        # Add model prediction
        fig.add_trace(go.Scatter(x=[user_input['floor_area_sqm']], y=[predicted_price],
                                 mode='markers',
                                 marker=dict(symbol='star', size=20, color='red',
                                             line=dict(width=2, color='darkred')),
                                 name='XGBoost Prediction'))

        fig.update_layout(template="plotly_white", height=400, showlegend=True)
        return fig
    return None

def predict_hdb_price(town, flat_type, flat_model, floor_area_sqm, storey_level, flat_age):
    """Main prediction function for Gradio with robust error handling"""
    user_input = {
        'town': town,
        'flat_type': flat_type,
        'flat_model': flat_model,
        'floor_area_sqm': floor_area_sqm,
        'storey_level': storey_level,
        'flat_age': flat_age
    }

    try:
        processed_input = preprocess_input(user_input)

        # Get prediction with error handling
        try:
            #predicted_price = max(0, float(models['xgboost'].predict(processed_input)[0]))
            predicted_price = max(100000, float(models['xgboost'].predict(processed_input)))
        except Exception as e:
            print(f"โŒ XGBoost prediction error: {e}")
            # Smarter fallback based on area
            predicted_price = max(100000, floor_area_sqm * 5000)  # Better fallback calculatio
            #predicted_price = 420000  # Fallback value

        # Create insights
        remaining_lease = 99 - flat_age
        price_per_sqm = predicted_price / floor_area_sqm

        insights = f"""
        **Property Summary:**
        - Location: {town}
        - Type: {flat_type}
        - Model: {flat_model}
        - Area: {floor_area_sqm} sqm
        - Floor: Level {storey_level}
        - Age: {flat_age} years
        - Remaining Lease: {remaining_lease} years
        - Price per sqm: ${price_per_sqm:,.0f}

        **Predicted Price: ${predicted_price:,.0f}**

        **Financing Eligibility:**
        """

        if remaining_lease >= 60:
            insights += "โœ… Bank loan eligible"
        elif remaining_lease >= 20:
            insights += "โš ๏ธ HDB loan eligible only"
        else:
            insights += "โŒ Limited financing options"

        # Create chart
        chart = create_market_insights_chart(data, user_input, predicted_price)

        return f"${predicted_price:,.0f}", chart, insights

    except Exception as e:
        error_msg = f"Prediction failed. Error: {str(e)}"
        print(error_msg)
        return "Error: Prediction failed", None, error_msg

def extract_parameters_from_query(query):
    """Extract HDB parameters from natural language query using LLM"""
    if not groq_api_key or client is None:
        return {"error": "Please set GROQ_API_KEY environment variable to use chat functionality."}

    try:
        # System prompt to guide the LLM
        system_prompt = """You are an expert at extracting parameters for HDB price prediction from natural language queries.
        Extract the following parameters if mentioned in the query:
        - town (e.g., Ang Mo Kio, Bedok, Tampines)
        - flat_type (e.g., 3 ROOM, 4 ROOM, 5 ROOM, EXECUTIVE)
        - flat_model (e.g., Improved, Model A, New Generation, Standard, Premium)
        - floor_area_sqm (floor area in square meters)
        - storey_level (floor level)
        - flat_age (age of flat in years)

        Return only a JSON object with the extracted parameters. If a parameter is not mentioned, set it to null.
        Example: {"town": "ANG MO KIO", "flat_type": "4 ROOM", "flat_model": "Improved", "floor_area_sqm": 95, "storey_level": 8, "flat_age": 15}"""

        # Query the LLM
        completion = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": query}
            ],
            temperature=0.5,
            max_tokens=200
        )

        # Extract and parse the JSON response
        response = completion.choices[0].message.content
        # Clean the response to extract just the JSON
        json_match = re.search(r'\{.*\}', response, re.DOTALL)
        if json_match:
            import json
            params = json.loads(json_match.group())
            return params
        else:
            return {"error": "Could not extract parameters from query"}

    except Exception as e:
        return {"error": f"Error processing query: {str(e)}"}

def is_small_talk(query):
    """Check if the query is small talk/casual conversation"""
    small_talk_keywords = [
        'hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening',
        'how are you', 'how are things', "what's up", 'how do you do',
        'thank you', 'thanks', 'bye', 'goodbye', 'see you', 'nice to meet you',
        'who are you', 'what can you do', 'help', 'tell me about yourself'
    ]
    
    query_lower = query.lower()
    return any(keyword in query_lower for keyword in small_talk_keywords)

def handle_small_talk(query):
    """Handle small talk queries with appropriate responses"""
    query_lower = query.lower()
    
    if any(greeting in query_lower for greeting in ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening']):
        return "Hello! ๐Ÿ‘‹ I'm your HDB price assistant. How can I help you today?"
    
    elif any(how_are_you in query_lower for how_are_you in ['how are you', 'how are things', "what's up", 'how do you do']):
        return "I'm doing great, thanks for asking! I'm here to help you with HDB price predictions and information. What can I assist you with today?"
    
    elif any(thanks in query_lower for thanks in ['thank you', 'thanks']):
        return "You're welcome! ๐Ÿ˜Š Is there anything else you'd like to know about HDB prices?"
    
    elif any(bye in query_lower for bye in ['bye', 'goodbye', 'see you']):
        return "Goodbye! ๐Ÿ‘‹ Feel free to come back if you have more questions about HDB prices!"
    
    elif 'who are you' in query_lower:
        return "I'm an AI assistant specialized in helping with HDB resale price predictions and information. I can estimate property values based on various factors like location, flat type, size, and age."
    
    elif 'what can you do' in query_lower or 'help' in query_lower:
        return "I can help you with:\n- Predicting HDB resale prices\n- Answering questions about HDB properties\n- Providing market insights\n\nJust tell me about the property you're interested in (location, type, size, etc.) and I'll give you an estimate!"
    
    elif 'tell me about yourself' in query_lower:
        return "I'm an AI assistant powered by machine learning models trained on HDB resale data. I can provide price estimates and insights about public housing in Singapore. My goal is to help you make informed decisions about HDB properties!"
    
    else:
        return "I'm here to help with HDB price predictions and information. How can I assist you today?"

def answer_general_hdb_question(query, chat_history):
    """Answer general HDB questions using the LLM"""
    if not groq_api_key or client is None:
        return "Please set GROQ_API_KEY environment variable to use chat functionality.", chat_history

    try:
        completion = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {
                    "role": "system", 
                    "content": "You are a helpful assistant specialized in HDB (Housing & Development Board) properties in Singapore. Provide accurate, helpful information about HDB prices, policies, and market trends."
                },
                {
                    "role": "user", 
                    "content": f"Answer this question about HDB: {query}"
                }
            ],
            temperature=0.3,
            max_tokens=500
        )
        response = completion.choices[0].message.content
        chat_history.append((query, response))
        return response, chat_history
    except Exception as e:
        error_msg = f"I encountered an error. Please try again later."
        chat_history.append((query, error_msg))
        return error_msg, chat_history

def chat_with_llm(query, chat_history):
    """Handle chat queries about HDB pricing and small talk"""
    if not groq_api_key or client is None:
        return "Please set GROQ_API_KEY...", chat_history

    # 1. First, check for small talk
    if is_small_talk(query):
        response = handle_small_talk(query)
        chat_history.append((query, response))
        return response, chat_history

    # 2. Check if the query is a clear request for a general explanation/trend (not a specific price)
    is_general_query = any(keyword in query.lower() for keyword in [
        'trend', 'overview', 'how are', 'what are', 'like in', 'average', 
        'over the years', 'market', 'compare'
    ])
    
    # 3. If it's a general query, use the LLM to answer it directly
    if is_general_query:
        try:
            completion = client.chat.completions.create(
                model="llama-3.3-70b-versatile",
                messages=[
                    {
                        "role": "system", 
                        "content": "You are a helpful assistant specialized in HDB (Housing & Development Board) properties in Singapore. Provide accurate, helpful information about HDB prices, policies, and market trends. Use the provided context if available."
                    },
                    {
                        "role": "user", 
                        "content": f"Based on general HDB market knowledge, answer this question: {query}"
                    }
                ],
                temperature=0.3,
                max_tokens=500
            )
            response = completion.choices[0].message.content
            chat_history.append((query, response))
            return response, chat_history
        except Exception as e:
            error_msg = f"I encountered an error. Please try again later."
            chat_history.append((query, error_msg))
            return error_msg, chat_history

    # 4. If it's not clearly general, try to extract parameters for a specific prediction
    params = extract_parameters_from_query(query)

    if "error" in params:
        # If extraction failed, fall back to general Q&A
        return answer_general_hdb_question(query, chat_history)

    # 5. Check what we got back from parameter extraction
    extracted_params = {k: v for k, v in params.items() if v is not None}
    required_for_prediction = ['town', 'flat_type', 'floor_area_sqm', 'storey_level', 'flat_age']

    # 6. If the user only provided a town or one other parameter, it's likely a general question.
    if len(extracted_params) < 3: # e.g., if only 'town' and 'flat_type' are provided
        # Ask a clarifying question or provide a general overview
        if 'town' in extracted_params:
            town = extracted_params['town']
            # You could add a pre-generated fact here, e.g., average price for that town from the dataset
            response = f"You asked about {town}. HDB prices can vary widely based on flat type, size, age, and specific location within the town. "
            response += f"For example, are you interested in 4-Room or 5-Room flats? What's your budget or preferred size? "
            response += "Alternatively, I can give you a prediction if you provide more details like flat type, size, and age."
        else:
            response = "I specialize in HDB price predictions and information. Could you provide more details about the property you're interested in (e.g., town, flat type, size) so I can give you a accurate estimate or information?"
        chat_history.append((query, response))
        return response, chat_history

    # 7. If we have most parameters, ask for the missing ones specifically
    missing_params = [param for param in required_for_prediction if params.get(param) is None]
    if missing_params:
        missing_list = ", ".join(missing_params)
        response = f"I'd be happy to predict a price for you. I just need a few more details: {missing_list}."
        chat_history.append((query, response))
        return response, chat_history

    # 8. If we have all parameters, make a prediction!
    try:
        # Convert string numbers to appropriate types
        if isinstance(params['floor_area_sqm'], str):
            params['floor_area_sqm'] = float(params['floor_area_sqm'])
        if isinstance(params['storey_level'], str):
            params['storey_level'] = int(params['storey_level'])
        if isinstance(params['flat_age'], str):
            params['flat_age'] = int(params['flat_age'])

        # Make prediction
        price, chart, insights = predict_hdb_price(
            params['town'], params['flat_type'], params['flat_model'],
            params['floor_area_sqm'], params['storey_level'], params['flat_age']
        )

        # Format response
        response = f"Based on your query:\n\n"
        response += f"๐Ÿ“ Town: {params['town']}\n"
        response += f"๐Ÿ  Flat Type: {params['flat_type']}\n"
        response += f"๐Ÿ“ Floor Area: {params['floor_area_sqm']} sqm\n"
        response += f"๐Ÿข Storey Level: {params['storey_level']}\n"
        response += f"๐Ÿ“… Flat Age: {params['flat_age']} years\n\n"
        response += f"๐Ÿ’ฐ Predicted Price: {price}\n\n"
        response += insights

        chat_history.append((query, response))
        return response, chat_history

    except Exception as e:
        error_msg = f"Error making prediction: {str(e)}"
        chat_history.append((query, error_msg))
        return error_msg, chat_history

def generate_map_and_stats(filter_town, filter_flat_type, filter_flat_model,
                          min_lease, max_lease, min_price, max_price):
    """Create the Singapore map and generate summary stats"""
    if map_df is None:
        return "<p align='center'>Dataset not found. Please ensure the URL is correct and the file exists.</p>", ""

    # Apply filters
    filtered_df = map_df.copy()
    
    if filter_town and filter_town != 'ALL':
        filtered_df = filtered_df[filtered_df['town'] == filter_town]
    
    if filter_flat_type and filter_flat_type != 'ALL':
        filtered_df = filtered_df[filtered_df['flat_type'] == filter_flat_type]
    
    if filter_flat_model and filter_flat_model != 'ALL':
        filtered_df = filtered_df[filtered_df['flat_model'] == filter_flat_model]
    
    # Filter based on lease and price sliders using 'resale_price'
    filtered_df = filtered_df[(filtered_df['remaining_lease'] >= min_lease) &
                             (filtered_df['remaining_lease'] <= max_lease)]
    filtered_df = filtered_df[(filtered_df['resale_price'] >= min_price) &
                             (filtered_df['resale_price'] <= max_price)]

    # Handle case with no matching records
    if len(filtered_df) == 0:
        return "<p align='center'>No data available with the selected filters.</p>", "No data available with the selected filters."

    # Create base map centered on Singapore
    singapore_coords = [1.3521, 103.8198]  # Approximate center of Singapore
    m = folium.Map(location=singapore_coords, zoom_start=11, tiles='OpenStreetMap')
    
    # Create marker cluster
    marker_cluster = MarkerCluster().add_to(m)
    
    # Create a Folium linear colormap using 'resale_price'
    folium_colormap = folium.LinearColormap(['green', 'yellow', 'red'], 
                                             vmin=filtered_df['resale_price'].min(), 
                                             vmax=filtered_df['resale_price'].max())
    folium_colormap.caption = 'Resale Price (SGD)'
    m.add_child(folium_colormap)
    
    # Add markers for each property
    for idx, row in filtered_df.iterrows():
        # Get color based on 'resale_price'
        color = folium_colormap(row['resale_price'])
        
        popup_content = f"""
        <b>Town:</b> {row['town']}<br>
        <b>Flat Type:</b> {row['flat_type']}<br>
        <b>Flat Model:</b> {row['flat_model']}<br>
        <b>Address:</b> {row['full_address']}<br>
        <b>Floor Area:</b> {row['floor_area_sqm']} sqm<br>
        <b>Remaining Lease:</b> {row['remaining_lease']} years<br>
        <b>Storey:</b> {row['storey_range']}<br>
        <b>Resale Price:</b> ${row['resale_price']:,.0f}<br>
        <b>Transaction Date:</b> {row['month']}
        """
        
        folium.CircleMarker(
            location=[row['latitude'], row['longitude']],
            radius=5,
            popup=folium.Popup(popup_content, max_width=300),
            color=color,
            fill=True,
            fillColor=color,
            fillOpacity=0.7,
            weight=1
        ).add_to(marker_cluster)
    
    # Convert map to HTML string
    map_html = m._repr_html_()

    # Generate summary statistics as a markdown string using 'resale_price'
    stats_string = f"""
    ### Summary Statistics
    - **Total Records:** {len(filtered_df):,}
    - **Average Price [inc Outlier]:** ${filtered_df['resale_price'].mean():,.0f}
    - **Median Price [exc Outlier]:** ${filtered_df['resale_price'].median():,.0f}
    - **Minimum Price:** ${filtered_df['resale_price'].min():,.0f}
    - **Maximum Price:** ${filtered_df['resale_price'].max():,.0f}
    - **Average Remaining Lease:** {filtered_df['remaining_lease'].mean():.1f} years
    - **Median Remaining Lease:** {filtered_df['remaining_lease'].median():.1f} years
    """
    
    return map_html, stats_string

# Preload models and data
print("Loading models and data...")
models = load_models()
data = load_data()

# Define Gradio interface
towns_list = [
    'SENGKANG', 'WOODLANDS', 'TAMPINES', 'PUNGGOL', 'JURONG WEST',
    'YISHUN', 'BEDOK', 'HOUGANG', 'CHOA CHU KANG', 'ANG MO KIO'
]

flat_types = ['3 ROOM', '4 ROOM', '5 ROOM', 'EXECUTIVE', '2 ROOM', '1 ROOM']
flat_models = ['Model A', 'Improved', 'New Generation', 'Standard', 'Premium']

# Create Gradio interface with chatbot
with gr.Blocks(title="๐Ÿ  HDB Price Predictor + Chat + Map", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# ๐Ÿ  HDB Price Predictor + AI Chat + Interactive Map")
    gr.Markdown("Predict HDB resale prices using XGBoost model, chat with our AI assistant, or explore properties on an interactive map")

    with gr.Tab("Traditional Interface"):
        with gr.Row():
            with gr.Column():
                town = gr.Dropdown(label="Town", choices=sorted(towns_list), value="ANG MO KIO")
                flat_type = gr.Dropdown(label="Flat Type", choices=sorted(flat_types), value="4 ROOM")
                flat_model = gr.Dropdown(label="Flat Model", choices=sorted(flat_models), value="Improved")
                floor_area_sqm = gr.Slider(label="Floor Area (sqm)", minimum=30, maximum=200, value=95, step=5)
                storey_level = gr.Slider(label="Storey Level", minimum=1, maximum=50, value=8, step=1)
                flat_age = gr.Slider(label="Flat Age (years)", minimum=0, maximum=99, value=15, step=1)

                predict_btn = gr.Button("๐Ÿ”ฎ Predict Price", variant="primary")

            with gr.Column():
                predicted_price = gr.Label(label="๐Ÿ’ฐ Predicted Price")
                insights = gr.Markdown(label="๐Ÿ“‹ Property Summary")

        with gr.Row():
            chart_output = gr.Plot(label="๐Ÿ“ˆ Market Insights")

        # Connect button to function
        predict_btn.click(
            fn=predict_hdb_price,
            inputs=[town, flat_type, flat_model, floor_area_sqm, storey_level, flat_age],
            outputs=[predicted_price, chart_output, insights]
        )

    with gr.Tab("AI Chat Assistant"):
        gr.Markdown("๐Ÿ’ฌ Chat with our AI assistant to get HDB price predictions using natural language!")
        gr.Markdown("Example: 'What would be the price of a 4-room model A flat in Ang Mo Kio with 95 sqm, on the 8th floor, that's 15 years old?'")
        gr.Markdown("You can also say hello, ask how I am, or ask general questions about HDB!")

        chatbot = gr.Chatbot(label="HDB Price Chatbot", height=500)
        msg = gr.Textbox(label="Your question", placeholder="Type your message here...")
        clear = gr.Button("Clear Chat")

        def respond(message, chat_history):
            response, updated_history = chat_with_llm(message, chat_history)
            return updated_history

        msg.submit(respond, [msg, chatbot], [chatbot])
        clear.click(lambda: None, None, [chatbot], queue=False)
        
    with gr.Tab("Interactive Map"):
        gr.Markdown("# ๐Ÿ—บ๏ธ Singapore HDB Resale Prices Map")
        gr.Markdown("An interactive map to visualize and filter HDB flat prices across Singapore.")
        
        with gr.Row():
            with gr.Column(scale=1):
                town_input = gr.Dropdown(choices=town_options, label="Select Town", value="ALL")
                flat_type_input = gr.Dropdown(choices=flat_type_options, label="Select Flat Type", value="ALL")
                flat_model_input = gr.Dropdown(choices=flat_model_options, label="Select Flat Model", value="ALL")
                
                gr.Markdown("### Filter by Lease and Price")
                min_lease_input = gr.Slider(minimum=min_lease_val, maximum=max_lease_val, 
                                            value=min_lease_val, step=1, label="Min Remaining Lease (years)")
                max_lease_input = gr.Slider(minimum=min_lease_val, maximum=max_lease_val, 
                                            value=max_lease_val, step=1, label="Max Remaining Lease (years)")
                min_price_input = gr.Slider(minimum=min_price_val, maximum=max_price_val, 
                                            value=min_price_val, step=1000, label="Min Price (SGD)")
                max_price_input = gr.Slider(minimum=min_price_val, maximum=max_price_val, 
                                            value=max_price_val, step=1000, label="Max Price (SGD)")
                
                # Add a button to generate the result
                generate_button = gr.Button("Generate Results", variant="primary")

            with gr.Column(scale=2):
                map_output = gr.HTML(label="Interactive Map")
                stats_output = gr.Markdown(label="Summary Statistics")
                gr.Markdown("""
                ---
                ### Map Color Legend
                The colors of the markers on the map represent the resale price of the HDB flats:

                - **<span style='color:green;'>Green</span>:** Indicates a lower resale price.
                - **<span style='color:yellow;'>Yellow</span>:** Indicates a mid-range resale price.
                - **<span style='color:red;'>Red</span>:** Indicates a higher resale price.
                """)
                
        # Link the button click to the function
        inputs = [town_input, flat_type_input, flat_model_input,
                  min_lease_input, max_lease_input, min_price_input, max_price_input]
        
        generate_button.click(
            fn=generate_map_and_stats,
            inputs=inputs,
            outputs=[map_output, stats_output]
        )

# To run in Colab
if __name__ == "__main__":
    demo.launch()
warnings.filterwarnings('ignore')
import re
from groq import Groq

# Initialize Groq client
groq_api_key = os.getenv("GROQ_API_KEY")
if groq_api_key:
    client = Groq(api_key=groq_api_key)
else:
    print("โš ๏ธ  GROQ_API_KEY not found. Chat functionality will be limited.")
    client = None

# Try to import xgboost, but fallback to scikit-learn
try:
    import xgboost as xgb
    XGB_AVAILABLE = True
    print("โœ… XGBoost is available")
except ImportError:
    XGB_AVAILABLE = False
    print("โš ๏ธ  XGBoost not available, using scikit-learn models")
    from sklearn.ensemble import RandomForestRegressor

def create_dummy_model(model_type):
    """Create a realistic dummy model that has all required methods"""
    class RealisticDummyModel:
        def __init__(self, model_type):
            self.model_type = model_type
            self.n_features_in_ = 9
            self.feature_names_in_ = [
                'floor_area_sqm', 'storey_level', 'flat_age', 'remaining_lease',
                'transaction_year', 'flat_type_encoded', 'town_encoded',
                'flat_model_encoded', 'dummy_feature'
            ]
            # Add methods that might be called by joblib or other code
            self.get_params = lambda deep=True: {}
            self.set_params = lambda **params: self

        def predict(self, X):
            # Realistic prediction logic
            if isinstance(X, np.ndarray) and len(X.shape) == 2:
                X = X[0]  # Take first row if it's a 2D array

            floor_area = X[0]
            storey_level = X[1]
            flat_age = X[2]
            town_encoded = X[6]
            flat_type_encoded = X[5]

            base_price = floor_area * (4800 + town_encoded * 200)
            storey_bonus = storey_level * 2500
            age_discount = flat_age * 1800

            price = base_price + storey_bonus - age_discount + 35000
            if storey_level > 20: price += 15000
            if flat_age < 10: price += 20000

            return np.array([max(300000, price)])

    return RealisticDummyModel(model_type)()

def safe_joblib_load(filepath):
    """Safely load joblib file with error handling"""
    try:
        model = joblib.load(filepath)
        print(f"โœ… Successfully loaded model from {filepath}")

        # Check if model has required methods
        if not hasattr(model, 'predict'):
            print("โŒ Loaded object doesn't have predict method")
            return None

        # Add missing methods if needed
        if not hasattr(model, 'get_params'):
            model.get_params = lambda deep=True: {}
        if not hasattr(model, 'set_params'):
            model.set_params = lambda **params: model

        return model

    except Exception as e:
        print(f"โŒ Error loading model from {filepath}: {e}")
        return None

def load_models():
    """Load models with robust error handling"""
    models = {}

    # Try to load XGBoost model
    try:
        xgboost_path = hf_hub_download(
            repo_id="Lesterchia174/HDB_Price_Predictor",
            filename="best_model_xgboost.joblib",
            repo_type="space"
        )
        models['xgboost'] = safe_joblib_load(xgboost_path)
        if models['xgboost'] is None:
            print("โš ๏ธ  Creating dummy model for XGBoost")
            models['xgboost'] = create_dummy_model("xgboost")
        else:
            print("โœ… XGBoost model loaded and validated")

    except Exception as e:
        print(f"โŒ Error downloading XGBoost model: {e}")
        print("โš ๏ธ  Creating dummy model for XGBoost")
        models['xgboost'] = create_dummy_model("xgboost")

    return models

def load_data():
    """Load data using Hugging Face Hub"""
    try:
        data_path = hf_hub_download(
            repo_id="Lesterchia174/HDB_Price_Predictor",
            filename="base_hdb_resale_prices_2015Jan-2025Jun_processed.csv",
            repo_type="space"
        )
        df = pd.read_csv(data_path)
        print("โœ… Data loaded successfully via Hugging Face Hub")
        return df
    except Exception as e:
        print(f"โŒ Error loading data: {e}")
        return create_sample_data()

def create_sample_data():
    """Create sample data if real data isn't available"""
    np.random.seed(42)
    towns = ['ANG MO KIO', 'BEDOK', 'TAMPINES', 'WOODLANDS', 'JURONG WEST']
    flat_types = ['4 ROOM', '5 ROOM', 'EXECUTIVE']
    flat_models = ['Improved', 'Model A', 'New Generation']

    data = []
    for _ in range(100):
        town = np.random.choice(towns)
        flat_type = np.random.choice(flat_types)
        flat_model = np.random.choice(flat_models)
        floor_area = np.random.randint(85, 150)
        storey = np.random.randint(1, 25)
        age = np.random.randint(0, 40)

        base_price = floor_area * 5000
        town_bonus = towns.index(town) * 20000
        storey_bonus = storey * 2000
        age_discount = age * 1500
        flat_type_bonus = flat_types.index(flat_type) * 30000

        resale_price = base_price + town_bonus + storey_bonus - age_discount + flat_type_bonus
        resale_price = max(300000, resale_price + np.random.randint(-20000, 20000))

        data.append({
            'town': town, 'flat_type': flat_type, 'flat_model': flat_model,
            'floor_area_sqm': floor_area, 'storey_level': storey,
            'flat_age': age, 'resale_price': resale_price
        })

    return pd.DataFrame(data)

def preprocess_input(user_input, model_type='xgboost'):
    """Preprocess user input for prediction with correct feature mapping"""
    # Flat type mapping
    flat_type_mapping = {'1 ROOM': 1, '2 ROOM': 2, '3 ROOM': 3, '4 ROOM': 4,
                         '5 ROOM': 5, 'EXECUTIVE': 6, 'MULTI-GENERATION': 7}

    # Town mapping
    town_mapping = {
        'SENGKANG': 0, 'WOODLANDS': 1, 'TAMPINES': 2, 'PUNGGOL': 3,
        'JURONG WEST': 4, 'YISHUN': 5, 'BEDOK': 6, 'HOUGANG': 7,
        'CHOA CHU KANG': 8, 'ANG MO KIO': 9
    }

    # Flat model mapping
    flat_model_mapping = {
        'Model A': 0, 'Improved': 1, 'New Generation': 2,
        'Standard': 3, 'Premium': 4
    }

    # Create input array with features
    input_features = [
        user_input['floor_area_sqm'],           # Feature 1
        user_input['storey_level'],             # Feature 2
        user_input['flat_age'],                 # Feature 3
        99 - user_input['flat_age'],            # Feature 4: remaining_lease
        2025,                                   # Feature 5: transaction_year
        flat_type_mapping.get(user_input['flat_type'], 4),  # Feature 6: flat_type_ordinal
        town_mapping.get(user_input['town'], 0),           # Feature 7: town_encoded
        flat_model_mapping.get(user_input['flat_model'], 0), # Feature 8: flat_model_encoded
        1                                       # Feature 9: (placeholder)
    ]

    return np.array([input_features])

def create_market_insights_chart(data, user_input, predicted_price):
    """Create market insights visualization"""
    if data is None or len(data) == 0:
        return None

    similar_properties = data[
        (data['flat_type'] == user_input['flat_type']) &
        (data['town'] == user_input['town'])
    ]

    if len(similar_properties) < 5:
        similar_properties = data[data['flat_type'] == user_input['flat_type']]

    if len(similar_properties) > 0:
        fig = px.scatter(similar_properties, x='floor_area_sqm', y='resale_price',
                         color='flat_model',
                         title=f"Market Position: {user_input['flat_type']} in {user_input['town']}",
                         labels={'floor_area_sqm': 'Floor Area (sqm)', 'resale_price': 'Resale Price (SGD)'})

        # Add model prediction
        fig.add_trace(go.Scatter(x=[user_input['floor_area_sqm']], y=[predicted_price],
                                 mode='markers',
                                 marker=dict(symbol='star', size=20, color='red',
                                             line=dict(width=2, color='darkred')),
                                 name='XGBoost Prediction'))

        fig.update_layout(template="plotly_white", height=400, showlegend=True)
        return fig
    return None

def predict_hdb_price(town, flat_type, flat_model, floor_area_sqm, storey_level, flat_age):
    """Main prediction function for Gradio with robust error handling"""
    user_input = {
        'town': town,
        'flat_type': flat_type,
        'flat_model': flat_model,
        'floor_area_sqm': floor_area_sqm,
        'storey_level': storey_level,
        'flat_age': flat_age
    }

    try:
        processed_input = preprocess_input(user_input)

        # Get prediction with error handling
        try:
            predicted_price = max(0, float(models['xgboost'].predict(processed_input)[0]))
        except Exception as e:
            print(f"โŒ XGBoost prediction error: {e}")
            predicted_price = 400000  # Fallback value

        # Create insights
        remaining_lease = 99 - flat_age
        price_per_sqm = predicted_price / floor_area_sqm

        insights = f"""
        **Property Summary:**
        - Location: {town}
        - Type: {flat_type}
        - Model: {flat_model}
        - Area: {floor_area_sqm} sqm
        - Floor: Level {storey_level}
        - Age: {flat_age} years
        - Remaining Lease: {remaining_lease} years
        - Price per sqm: ${price_per_sqm:,.0f}

        **Predicted Price: ${predicted_price:,.0f}**

        **Financing Eligibility:**
        """

        if remaining_lease >= 60:
            insights += "โœ… Bank loan eligible"
        elif remaining_lease >= 20:
            insights += "โš ๏ธ HDB loan eligible only"
        else:
            insights += "โŒ Limited financing options"

        # Create chart
        chart = create_market_insights_chart(data, user_input, predicted_price)

        return f"${predicted_price:,.0f}", chart, insights

    except Exception as e:
        error_msg = f"Prediction failed. Error: {str(e)}"
        print(error_msg)
        return "Error: Prediction failed", None, error_msg

def extract_parameters_from_query(query):
    """Extract HDB parameters from natural language query using LLM"""
    if not groq_api_key or client is None:
        return {"error": "Please set GROQ_API_KEY environment variable to use chat functionality."}

    try:
        # System prompt to guide the LLM
        system_prompt = """You are an expert at extracting parameters for HDB price prediction from natural language queries.
        Extract the following parameters if mentioned in the query:
        - town (e.g., Ang Mo Kio, Bedok, Tampines)
        - flat_type (e.g., 3 ROOM, 4 ROOM, 5 ROOM, EXECUTIVE)
        - flat_model (e.g., Improved, Model A, New Generation, Standard, Premium)
        - floor_area_sqm (floor area in square meters)
        - storey_level (floor level)
        - flat_age (age of flat in years)

        Return only a JSON object with the extracted parameters. If a parameter is not mentioned, set it to null.
        Example: {"town": "ANG MO KIO", "flat_type": "4 ROOM", "flat_model": "Improved", "floor_area_sqm": 95, "storey_level": 8, "flat_age": 15}"""

        # Query the LLM
        completion = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": query}
            ],
            temperature=0.1,
            max_tokens=200
        )

        # Extract and parse the JSON response
        response = completion.choices[0].message.content
        # Clean the response to extract just the JSON
        json_match = re.search(r'\{.*\}', response, re.DOTALL)
        if json_match:
            import json
            params = json.loads(json_match.group())
            return params
        else:
            return {"error": "Could not extract parameters from query"}

    except Exception as e:
        return {"error": f"Error processing query: {str(e)}"}

def is_small_talk(query):
    """Check if the query is small talk/casual conversation"""
    small_talk_keywords = [
        'hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening',
        'how are you', 'how are things', "what's up", 'how do you do',
        'thank you', 'thanks', 'bye', 'goodbye', 'see you', 'nice to meet you',
        'who are you', 'what can you do', 'help', 'tell me about yourself'
    ]
    
    query_lower = query.lower()
    return any(keyword in query_lower for keyword in small_talk_keywords)

def handle_small_talk(query):
    """Handle small talk queries with appropriate responses"""
    query_lower = query.lower()
    
    if any(greeting in query_lower for greeting in ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening']):
        return "Hello! ๐Ÿ‘‹ I'm your HDB price assistant. How can I help you today?"
    
    elif any(how_are_you in query_lower for how_are_you in ['how are you', 'how are things', "what's up", 'how do you do']):
        return "I'm doing great, thanks for asking! I'm here to help you with HDB price predictions and information. What can I assist you with today?"
    
    elif any(thanks in query_lower for thanks in ['thank you', 'thanks']):
        return "You're welcome! ๐Ÿ˜Š Is there anything else you'd like to know about HDB prices?"
    
    elif any(bye in query_lower for bye in ['bye', 'goodbye', 'see you']):
        return "Goodbye! ๐Ÿ‘‹ Feel free to come back if you have more questions about HDB prices!"
    
    elif 'who are you' in query_lower:
        return "I'm an AI assistant specialized in helping with HDB resale price predictions and information. I can estimate property values based on various factors like location, flat type, size, and age."
    
    elif 'what can you do' in query_lower or 'help' in query_lower:
        return "I can help you with:\n- Predicting HDB resale prices\n- Answering questions about HDB properties\n- Providing market insights\n\nJust tell me about the property you're interested in (location, type, size, etc.) and I'll give you an estimate!"
    
    elif 'tell me about yourself' in query_lower:
        return "I'm an AI assistant powered by machine learning models trained on HDB resale data. I can provide price estimates and insights about public housing in Singapore. My goal is to help you make informed decisions about HDB properties!"
    
    else:
        return "I'm here to help with HDB price predictions and information. How can I assist you today?"


def chat_with_llm(query, chat_history):
    """Handle chat queries about HDB pricing and small talk"""
    if not groq_api_key or client is None:
        return "Please set GROQ_API_KEY...", chat_history

    # 1. First, check for small talk
    if is_small_talk(query):
        response = handle_small_talk(query)
        chat_history.append((query, response))
        return response, chat_history

    # 2. Check if the query is a clear request for a general explanation/trend (not a specific price)
    is_general_query = any(keyword in query.lower() for keyword in [
        'trend', 'overview', 'how are', 'what are', 'like in', 'average', 
        'over the years', 'market', 'compare'
    ])
    
    # 3. If it's a general query, use the LLM to answer it directly
    if is_general_query:
        try:
            completion = client.chat.completions.create(
                model="llama-3.3-70b-versatile",
                messages=[
                    {
                        "role": "system", 
                        "content": "You are a helpful assistant specialized in HDB (Housing & Development Board) properties in Singapore. Provide accurate, helpful information about HDB prices, policies, and market trends. Use the provided context if available."
                    },
                    {
                        "role": "user", 
                        "content": f"Based on general HDB market knowledge, answer this question: {query}"
                    }
                ],
                temperature=0.3,
                max_tokens=500
            )
            response = completion.choices[0].message.content
            chat_history.append((query, response))
            return response, chat_history
        except Exception as e:
            error_msg = f"I encountered an error. Please try again later."
            chat_history.append((query, error_msg))
            return error_msg, chat_history

    # 4. If it's not clearly general, try to extract parameters for a specific prediction
    params = extract_parameters_from_query(query)

    if "error" in params:
        # If extraction failed, fall back to general Q&A
        return answer_general_hdb_question(query, chat_history)

    # 5. Check what we got back from parameter extraction
    extracted_params = {k: v for k, v in params.items() if v is not None}
    required_for_prediction = ['town', 'flat_type', 'floor_area_sqm', 'storey_level', 'flat_age']

    # 6. If the user only provided a town or one other parameter, it's likely a general question.
    if len(extracted_params) < 3: # e.g., if only 'town' and 'flat_type' are provided
        # Ask a clarifying question or provide a general overview
        if 'town' in extracted_params:
            town = extracted_params['town']
            # You could add a pre-generated fact here, e.g., average price for that town from the dataset
            response = f"You asked about {town}. HDB prices can vary widely based on flat type, size, age, and specific location within the town. "
            response += f"For example, are you interested in 4-Room or 5-Room flats? What's your budget or preferred size? "
            response += "Alternatively, I can give you a prediction if you provide more details like flat type, size, and age."
        else:
            response = "I specialize in HDB price predictions and information. Could you provide more details about the property you're interested in (e.g., town, flat type, size) so I can give you a accurate estimate or information?"
        chat_history.append((query, response))
        return response, chat_history

    # 7. If we have most parameters, ask for the missing ones specifically
    missing_params = [param for param in required_for_prediction if params.get(param) is None]
    if missing_params:
        missing_list = ", ".join(missing_params)
        response = f"I'd be happy to predict a price for you. I just need a few more details: {missing_list}."
        chat_history.append((query, response))
        return response, chat_history

    # 8. If we have all parameters, make the prediction!
    # ... (rest of the prediction code remains the same)


    
    # If we have all parameters, make a prediction
    try:
        # Convert string numbers to appropriate types
        if isinstance(params['floor_area_sqm'], str):
            params['floor_area_sqm'] = float(params['floor_area_sqm'])
        if isinstance(params['storey_level'], str):
            params['storey_level'] = int(params['storey_level'])
        if isinstance(params['flat_age'], str):
            params['flat_age'] = int(params['flat_age'])

        # Make prediction
        price, chart, insights = predict_hdb_price(
            params['town'], params['flat_type'], params['flat_model'],
            params['floor_area_sqm'], params['storey_level'], params['flat_age']
        )

        # Format response
        response = f"Based on your query:\n\n"
        response += f"๐Ÿ“ Town: {params['town']}\n"
        response += f"๐Ÿ  Flat Type: {params['flat_type']}\n"
        response += f"๐Ÿ“ Floor Area: {params['floor_area_sqm']} sqm\n"
        response += f"๐Ÿข Storey Level: {params['storey_level']}\n"
        response += f"๐Ÿ“… Flat Age: {params['flat_age']} years\n\n"
        response += f"๐Ÿ’ฐ Predicted Price: {price}\n\n"
        response += insights

        chat_history.append((query, response))
        return response, chat_history

    except Exception as e:
        error_msg = f"Error making prediction: {str(e)}"
        chat_history.append((query, error_msg))
        return error_msg, chat_history

# Preload models and data
print("Loading models and data...")
models = load_models()
data = load_data()

# Define Gradio interface
towns_list = [
    'SENGKANG', 'WOODLANDS', 'TAMPINES', 'PUNGGOL', 'JURONG WEST',
    'YISHUN', 'BEDOK', 'HOUGANG', 'CHOA CHU KANG', 'ANG MO KIO'
]

flat_types = ['3 ROOM', '4 ROOM', '5 ROOM', 'EXECUTIVE', '2 ROOM', '1 ROOM']
flat_models = ['Model A', 'Improved', 'New Generation', 'Standard', 'Premium']

# Create Gradio interface with chatbot
with gr.Blocks(title="๐Ÿ  HDB Price Predictor + Chat", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# ๐Ÿ  HDB Price Predictor + AI Chat")
    gr.Markdown("Predict HDB resale prices using XGBoost model or chat with our AI assistant")

    with gr.Tab("Traditional Interface"):
        with gr.Row():
            with gr.Column():
                town = gr.Dropdown(label="Town", choices=sorted(towns_list), value="ANG MO KIO")
                flat_type = gr.Dropdown(label="Flat Type", choices=sorted(flat_types), value="4 ROOM")
                flat_model = gr.Dropdown(label="Flat Model", choices=sorted(flat_models), value="Improved")
                floor_area_sqm = gr.Slider(label="Floor Area (sqm)", minimum=30, maximum=200, value=95, step=5)
                storey_level = gr.Slider(label="Storey Level", minimum=1, maximum=50, value=8, step=1)
                flat_age = gr.Slider(label="Flat Age (years)", minimum=0, maximum=99, value=15, step=1)

                predict_btn = gr.Button("๐Ÿ”ฎ Predict Price", variant="primary")

            with gr.Column():
                predicted_price = gr.Label(label="๐Ÿ’ฐ Predicted Price")
                insights = gr.Markdown(label="๐Ÿ“‹ Property Summary")

        with gr.Row():
            chart_output = gr.Plot(label="๐Ÿ“ˆ Market Insights")

        # Connect button to function
        predict_btn.click(
            fn=predict_hdb_price,
            inputs=[town, flat_type, flat_model, floor_area_sqm, storey_level, flat_age],
            outputs=[predicted_price, chart_output, insights]
        )

    with gr.Tab("AI Chat Assistant"):
        gr.Markdown("๐Ÿ’ฌ Chat with our AI assistant to get HDB price predictions using natural language!")
        gr.Markdown("Example: 'What would be the price of a 4-room model A flat in Ang Mo Kio with 95 sqm, on the 8th floor, that's 15 years old?'")
        gr.Markdown("You can also say hello, ask how I am, or ask general questions about HDB!")

        chatbot = gr.Chatbot(label="HDB Price Chatbot", height=500)
        msg = gr.Textbox(label="Your question", placeholder="Type your message here...")
        clear = gr.Button("Clear Chat")

        def respond(message, chat_history):
            response, updated_history = chat_with_llm(message, chat_history)
            return updated_history

        msg.submit(respond, [msg, chatbot], [chatbot])
        clear.click(lambda: None, None, [chatbot], queue=False)

# To run in Colab
if __name__ == "__main__":
    # Let Gradio automatically find an available port
    demo.launch(server_name="0.0.0.0", share=True)