File size: 42,447 Bytes
61a1e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690700c
61a1e05
 
690700c
 
 
 
61a1e05
 
 
 
 
 
690700c
1d1d310
690700c
 
1d1d310
690700c
1d1d310
 
690700c
1d1d310
690700c
 
 
 
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
 
 
 
61a1e05
690700c
 
61a1e05
 
 
 
 
 
 
 
 
 
 
690700c
 
61a1e05
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
61a1e05
 
 
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
690700c
61a1e05
690700c
 
 
61a1e05
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d1d310
690700c
 
 
61a1e05
 
 
 
 
690700c
 
 
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
 
 
 
 
 
 
 
 
 
690700c
 
61a1e05
690700c
 
 
 
 
 
 
61a1e05
 
 
690700c
 
 
 
 
 
 
61a1e05
 
 
 
690700c
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
1d1d310
690700c
 
 
 
 
 
 
 
 
 
 
 
61a1e05
690700c
61a1e05
690700c
 
 
 
61a1e05
 
 
 
 
 
 
 
 
 
 
1d1d310
61a1e05
690700c
61a1e05
690700c
 
 
 
 
61a1e05
690700c
 
 
61a1e05
690700c
61a1e05
690700c
 
 
61a1e05
1d1d310
61a1e05
 
690700c
 
 
 
 
61a1e05
690700c
 
 
 
 
61a1e05
 
690700c
 
 
 
 
 
 
 
61a1e05
 
 
 
1d1d310
 
 
61a1e05
690700c
 
 
 
 
 
 
 
61a1e05
690700c
61a1e05
 
 
690700c
61a1e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# # ======================================================================================================
# # CLAUDE ORIGINAL VERSION 
# # ======================================================================================================

# """
# Build FAISS Index from Scratch - FIXED VERSION
# Creates faiss_index.pkl with proper serialization

# Run this ONCE before starting the backend:
#     python build_faiss_index.py

# Author: Banking RAG Chatbot
# Date: November 2025
# """

# # Suppress warnings
# import os
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
# import warnings
# warnings.filterwarnings('ignore')

# import pickle
# import json
# import torch
# import torch.nn as nn
# import torch.nn.functional as F
# import faiss
# import numpy as np
# from pathlib import Path
# from transformers import AutoTokenizer, AutoModel
# from typing import List

# # ============================================================================
# # CONFIGURATION - UPDATE THESE PATHS!
# # ============================================================================

# # Where is your knowledge base JSONL file?
# KB_JSONL_FILE = "data/final_knowledge_base.jsonl"

# # Where is your trained retriever model?
# RETRIEVER_MODEL_PATH = "app/models/best_retriever_model.pth"

# # Where to save the output FAISS pickle?
# OUTPUT_PKL_FILE = "app/models/faiss_index.pkl"

# # Device (auto-detect GPU/CPU)
# DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# # Batch size for encoding (reduce if you get OOM errors)
# BATCH_SIZE = 32

# # ============================================================================
# # CUSTOM SENTENCE TRANSFORMER (Same as retriever.py)
# # ============================================================================

# class CustomSentenceTransformer(nn.Module):
#     """
#     Custom SentenceTransformer - exact copy from retriever.py
#     Uses e5-base-v2 with mean pooling and L2 normalization
#     """
    
#     def __init__(self, model_name: str = "intfloat/e5-base-v2"):
#         super().__init__()
#         print(f"   Loading base model: {model_name}...")
#         self.encoder = AutoModel.from_pretrained(model_name)
#         self.tokenizer = AutoTokenizer.from_pretrained(model_name)
#         self.config = self.encoder.config
#         print(f"   โœ… Base model loaded")
    
#     def forward(self, input_ids, attention_mask):
#         """Forward pass through BERT encoder"""
#         outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        
#         # Mean pooling
#         token_embeddings = outputs.last_hidden_state
#         input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
#         embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
#             input_mask_expanded.sum(1), min=1e-9
#         )
        
#         # L2 normalize
#         embeddings = F.normalize(embeddings, p=2, dim=1)
#         return embeddings
    
#     def encode(self, sentences: List[str], batch_size: int = 32) -> np.ndarray:
#         """Encode sentences - same as training"""
#         self.eval()
#         if isinstance(sentences, str):
#             sentences = [sentences]
        
#         # Add 'query: ' prefix for e5-base-v2
#         processed_sentences = [f"query: {s.strip()}" for s in sentences]
        
#         all_embeddings = []
#         with torch.no_grad():
#             for i in range(0, len(processed_sentences), batch_size):
#                 batch_sentences = processed_sentences[i:i + batch_size]
                
#                 # Tokenize
#                 tokens = self.tokenizer(
#                     batch_sentences,
#                     truncation=True,
#                     padding=True,
#                     max_length=128,
#                     return_tensors='pt'
#                 ).to(self.encoder.device)
                
#                 # Get embeddings
#                 embeddings = self.forward(tokens['input_ids'], tokens['attention_mask'])
#                 all_embeddings.append(embeddings.cpu().numpy())
        
#         return np.vstack(all_embeddings)

# # ============================================================================
# # RETRIEVER MODEL (Wrapper)
# # ============================================================================

# class RetrieverModel:
#     """Wrapper for trained retriever model"""
    
#     def __init__(self, model_path: str, device: str = "cpu"):
#         print(f"\n๐Ÿค– Loading retriever model...")
#         print(f"   Device: {device}")
#         self.device = device
#         self.model = CustomSentenceTransformer("intfloat/e5-base-v2").to(device)
        
#         # Load trained weights
#         print(f"   Loading weights from: {model_path}")
#         try:
#             state_dict = torch.load(model_path, map_location=device)
#             self.model.load_state_dict(state_dict)
#             print(f"   โœ… Trained weights loaded")
#         except Exception as e:
#             print(f"   โš ๏ธ Warning: Could not load trained weights: {e}")
#             print(f"   Using base e5-base-v2 model instead")
        
#         self.model.eval()
    
#     def encode_documents(self, documents: List[str], batch_size: int = 32) -> np.ndarray:
#         """Encode documents"""
#         return self.model.encode(documents, batch_size=batch_size)

# # ============================================================================
# # MAIN: BUILD FAISS INDEX
# # ============================================================================

# def build_faiss_index():
#     """Main function to build FAISS index from scratch"""
    
#     print("=" * 80)
#     print("๐Ÿ—๏ธ  BUILDING FAISS INDEX FROM SCRATCH")
#     print("=" * 80)
    
#     # ========================================================================
#     # STEP 1: LOAD KNOWLEDGE BASE
#     # ========================================================================
#     print(f"\n๐Ÿ“– STEP 1: Loading knowledge base...")
#     print(f"   File: {KB_JSONL_FILE}")
    
#     if not os.path.exists(KB_JSONL_FILE):
#         print(f"   โŒ ERROR: File not found!")
#         print(f"   Please copy your knowledge base to: {KB_JSONL_FILE}")
#         return False
    
#     kb_data = []
#     with open(KB_JSONL_FILE, 'r', encoding='utf-8') as f:
#         for line_num, line in enumerate(f, 1):
#             try:
#                 kb_data.append(json.loads(line))
#             except json.JSONDecodeError as e:
#                 print(f"   โš ๏ธ Warning: Skipping invalid JSON on line {line_num}: {e}")
    
#     print(f"   โœ… Loaded {len(kb_data)} documents")
    
#     if len(kb_data) == 0:
#         print(f"   โŒ ERROR: Knowledge base is empty!")
#         return False
    
#     # ========================================================================
#     # STEP 2: PREPARE DOCUMENTS FOR ENCODING
#     # ========================================================================
#     print(f"\n๐Ÿ“ STEP 2: Preparing documents for encoding...")
    
#     documents = []
#     for i, item in enumerate(kb_data):
#         # Combine instruction + response for embedding (same as training)
#         instruction = item.get('instruction', '')
#         response = item.get('response', '')
        
#         # Create combined text
#         if instruction and response:
#             text = f"{instruction} {response}"
#         elif instruction:
#             text = instruction
#         elif response:
#             text = response
#         else:
#             print(f"   โš ๏ธ Warning: Document {i} has no content, using placeholder")
#             text = "empty document"
        
#         documents.append(text)
    
#     print(f"   โœ… Prepared {len(documents)} documents for encoding")
#     print(f"   Average length: {sum(len(d) for d in documents) / len(documents):.1f} chars")
    
#     # ========================================================================
#     # STEP 3: LOAD RETRIEVER AND ENCODE DOCUMENTS
#     # ========================================================================
#     print(f"\n๐Ÿ”ฎ STEP 3: Encoding documents with trained retriever...")
    
#     if not os.path.exists(RETRIEVER_MODEL_PATH):
#         print(f"   โŒ ERROR: Retriever model not found!")
#         print(f"   Please copy your trained model to: {RETRIEVER_MODEL_PATH}")
#         return False
    
#     # Load retriever
#     retriever = RetrieverModel(RETRIEVER_MODEL_PATH, device=DEVICE)
    
#     # Encode all documents
#     print(f"   Encoding {len(documents)} documents...")
#     print(f"   Batch size: {BATCH_SIZE}")
#     print(f"   This may take a few minutes... โ˜•")
    
#     try:
#         embeddings = retriever.encode_documents(documents, batch_size=BATCH_SIZE)
#         print(f"   โœ… Encoded {embeddings.shape[0]} documents")
#         print(f"   Embedding dimension: {embeddings.shape[1]}")
#     except Exception as e:
#         print(f"   โŒ ERROR during encoding: {e}")
#         import traceback
#         traceback.print_exc()
#         return False
    
#     # ========================================================================
#     # STEP 4: BUILD FAISS INDEX
#     # ========================================================================
#     print(f"\n๐Ÿ” STEP 4: Building FAISS index...")
    
#     dimension = embeddings.shape[1]
#     print(f"   Dimension: {dimension}")
    
#     # Create FAISS index (Inner Product = Cosine similarity after normalization)
#     print(f"   Creating IndexFlatIP...")
#     index = faiss.IndexFlatIP(dimension)
    
#     # Normalize embeddings for cosine similarity
#     print(f"   Normalizing embeddings...")
#     faiss.normalize_L2(embeddings)
    
#     # Add to index
#     print(f"   Adding {embeddings.shape[0]} vectors to FAISS index...")
#     index.add(embeddings.astype('float32'))
    
#     print(f"   โœ… FAISS index built successfully")
#     print(f"   Total vectors: {index.ntotal}")
    
#     # ========================================================================
#     # STEP 5: SAVE WITH COMPATIBLE FORMAT
#     # ========================================================================
#     print(f"\n๐Ÿ’พ STEP 5: Saving with compatible format...")
    
#     # Create models directory if it doesn't exist
#     os.makedirs(os.path.dirname(OUTPUT_PKL_FILE), exist_ok=True)
    
#     try:
#         # โœ… NEW FORMAT: Save as dictionary with version info
#         print(f"   Creating compatible save format...")
#         save_data = {
#             'format_version': 'v2',  # Mark as new format
#             'index_bytes': faiss.serialize_index(index),  # FAISS bytes
#             'kb_data': kb_data,  # Knowledge base
#             'dimension': dimension,
#             'num_vectors': index.ntotal,
#             'faiss_version': faiss.__version__
#         }
        
#         print(f"   Pickling dictionary...")
#         with open(OUTPUT_PKL_FILE, 'wb') as f:
#             pickle.dump(save_data, f, protocol=pickle.HIGHEST_PROTOCOL)
        
#         file_size_mb = Path(OUTPUT_PKL_FILE).stat().st_size / (1024 * 1024)
#         print(f"   โœ… Saved: {OUTPUT_PKL_FILE}")
#         print(f"   File size: {file_size_mb:.2f} MB")
#         print(f"   Format: v2 (compatible)")
#         print(f"   FAISS version used: {faiss.__version__}")
#     except Exception as e:
#         print(f"   โŒ ERROR saving pickle: {e}")
#         import traceback
#         traceback.print_exc()
#         return False
    
#     # ========================================================================
#     # STEP 6: VERIFY SAVED FILE
#     # ========================================================================
#     print(f"\nโœ… STEP 6: Verifying saved file...")
    
#     try:
#         with open(OUTPUT_PKL_FILE, 'rb') as f:
#             loaded_data = pickle.load(f)
        
#         # Check format
#         if isinstance(loaded_data, dict) and loaded_data.get('format_version') == 'v2':
#             print(f"   โœ… Format: v2 (compatible)")
            
#             # Deserialize FAISS index
#             loaded_index = faiss.deserialize_index(loaded_data['index_bytes'])
#             loaded_kb = loaded_data['kb_data']
            
#             print(f"   โœ… Verification successful")
#             print(f"   Index vectors: {loaded_index.ntotal}")
#             print(f"   KB documents: {len(loaded_kb)}")
#             print(f"   Dimension: {loaded_data['dimension']}")
            
#             if loaded_index.ntotal != len(loaded_kb):
#                 print(f"   โš ๏ธ WARNING: Size mismatch detected!")
#         else:
#             print(f"   โš ๏ธ WARNING: Unexpected format detected")
            
#     except Exception as e:
#         print(f"   โŒ ERROR verifying file: {e}")
#         import traceback
#         traceback.print_exc()
#         return False
    
#     # ========================================================================
#     # SUCCESS!
#     # ========================================================================
#     print("\n" + "=" * 80)
#     print("๐ŸŽ‰ SUCCESS! FAISS INDEX BUILT AND SAVED")
#     print("=" * 80)
#     print(f"\n๐Ÿ“Š Summary:")
#     print(f"   Documents: {len(kb_data)}")
#     print(f"   Vectors: {index.ntotal}")
#     print(f"   Dimension: {dimension}")
#     print(f"   File: {OUTPUT_PKL_FILE} ({file_size_mb:.2f} MB)")
#     print(f"   Format: v2 (compatible with all FAISS versions)")
#     print(f"   FAISS version: {faiss.__version__}")
#     print(f"\n๐Ÿš€ Next steps:")
#     print(f"   1. Upload {OUTPUT_PKL_FILE} to HuggingFace Hub")
#     print(f"   2. Update your retriever loading code (see below)")
#     print(f"   3. Restart your backend")
#     print(f"   4. Test retrieval - should work now!")
#     print("\n" + "=" * 80)
#     print("๐Ÿ“ IMPORTANT: Update your loading code to handle v2 format:")
#     print("=" * 80)
#     print("""
# # In your retriever.py or wherever you load the index:

# with open('faiss_index.pkl', 'rb') as f:
#     data = pickle.load(f)

# # Check format
# if isinstance(data, dict) and data.get('format_version') == 'v2':
#     # NEW FORMAT (v2)
#     index = faiss.deserialize_index(data['index_bytes'])
#     kb_data = data['kb_data']
#     print(f"โœ… Loaded v2 format: {index.ntotal} vectors")
# else:
#     # OLD FORMAT (try to handle gracefully)
#     print("โš ๏ธ Old format detected, please rebuild")
#     raise ValueError("Please rebuild FAISS index with new script")
#     """)
#     print("=" * 80 + "\n")
    
#     return True

# # ============================================================================
# # RUN SCRIPT
# # ============================================================================

# if __name__ == "__main__":
#     success = build_faiss_index()
    
#     if not success:
#         print("\n" + "=" * 80)
#         print("โŒ FAILED TO BUILD FAISS INDEX")
#         print("=" * 80)
#         print("\nPlease check:")
#         print("1. Knowledge base file exists: data/final_knowledge_base.jsonl")
#         print("2. Retriever model exists: app/models/best_retriever_model.pth")
#         print("3. You have enough RAM (embeddings need ~1GB for 10k docs)")
#         print("=" * 80 + "\n")
#         exit(1)




























# ======================================================================================================
# CLAUDE OPTIMIZED VERSION FOR FASTER ENCODING PROCESS
# ======================================================================================================
"""
Build FAISS Index from Scratch - OPTIMIZED VERSION
โšก FASTER with GPU auto-detection and larger batches

Run this ONCE before starting the backend:
    python build_faiss_index.py

Optimizations:
- Auto-detects GPU (10-50x faster than CPU)
- Larger batch sizes (256 instead of 32)
- Progress bars
- Memory efficient processing

Author: Banking RAG Chatbot
Date: November 2025
"""

# Suppress warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
import warnings
warnings.filterwarnings('ignore')

import pickle
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import faiss
import numpy as np
from pathlib import Path
from transformers import AutoTokenizer, AutoModel
from typing import List
from tqdm import tqdm  # Progress bars

# ============================================================================
# CONFIGURATION - UPDATE THESE PATHS!
# ============================================================================

KB_JSONL_FILE = "data/final_knowledge_base.jsonl"
RETRIEVER_MODEL_PATH = "app/models/best_retriever_model.pth"
OUTPUT_PKL_FILE = "app/models/faiss_index.pkl"

# โšก AUTO-DETECT GPU (will use GPU if available, CPU otherwise)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# โšก OPTIMIZED BATCH SIZE
# - GPU: Use 256 (or even 512 if you have 16GB+ VRAM)
# - CPU: Use 32 (to avoid RAM issues)
BATCH_SIZE = 256 if DEVICE == "cuda" else 32

print(f"๐Ÿ”ง Configuration:")
print(f"   Device: {DEVICE}")
print(f"   Batch size: {BATCH_SIZE}")
if DEVICE == "cuda":
    print(f"   GPU: {torch.cuda.get_device_name(0)}")
    print(f"   VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")

# ============================================================================
# CUSTOM SENTENCE TRANSFORMER
# ============================================================================

class CustomSentenceTransformer(nn.Module):
    def __init__(self, model_name: str = "intfloat/e5-base-v2"):
        super().__init__()
        print(f"   Loading base model: {model_name}...")
        self.encoder = AutoModel.from_pretrained(model_name)
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.config = self.encoder.config
        print(f"   โœ… Base model loaded")
    
    def forward(self, input_ids, attention_mask):
        outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        token_embeddings = outputs.last_hidden_state
        input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
        embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
            input_mask_expanded.sum(1), min=1e-9
        )
        embeddings = F.normalize(embeddings, p=2, dim=1)
        return embeddings
    
    def encode(self, sentences: List[str], batch_size: int = 32) -> np.ndarray:
        """โšก Optimized encoding with progress bar"""
        self.eval()
        if isinstance(sentences, str):
            sentences = [sentences]
        
        processed_sentences = [f"query: {s.strip()}" for s in sentences]
        all_embeddings = []
        
        # โšก Progress bar
        num_batches = (len(processed_sentences) + batch_size - 1) // batch_size
        pbar = tqdm(total=len(processed_sentences), desc="   Encoding", unit="docs")
        
        with torch.no_grad():
            for i in range(0, len(processed_sentences), batch_size):
                batch_sentences = processed_sentences[i:i + batch_size]
                
                tokens = self.tokenizer(
                    batch_sentences,
                    truncation=True,
                    padding=True,
                    max_length=128,
                    return_tensors='pt'
                ).to(self.encoder.device)
                
                embeddings = self.forward(tokens['input_ids'], tokens['attention_mask'])
                all_embeddings.append(embeddings.cpu().numpy())
                
                pbar.update(len(batch_sentences))
        
        pbar.close()
        return np.vstack(all_embeddings)

# ============================================================================
# RETRIEVER MODEL
# ============================================================================

class RetrieverModel:
    def __init__(self, model_path: str, device: str = "cpu"):
        print(f"\n๐Ÿค– Loading retriever model...")
        print(f"   Device: {device}")
        self.device = device
        self.model = CustomSentenceTransformer("intfloat/e5-base-v2").to(device)
        
        print(f"   Loading weights from: {model_path}")
        try:
            state_dict = torch.load(model_path, map_location=device)
            self.model.load_state_dict(state_dict)
            print(f"   โœ… Trained weights loaded")
        except Exception as e:
            print(f"   โš ๏ธ Warning: Could not load trained weights: {e}")
            print(f"   Using base e5-base-v2 model instead")
        
        self.model.eval()
        
        # โšก Mixed precision for faster inference on GPU
        if device == "cuda":
            self.model = self.model.half()  # FP16
            print(f"   โšก Using FP16 (mixed precision) for faster encoding")
    
    def encode_documents(self, documents: List[str], batch_size: int = 32) -> np.ndarray:
        return self.model.encode(documents, batch_size=batch_size)

# ============================================================================
# MAIN: BUILD FAISS INDEX
# ============================================================================

def build_faiss_index():
    print("=" * 80)
    print("๐Ÿ—๏ธ  BUILDING FAISS INDEX FROM SCRATCH (OPTIMIZED)")
    print("=" * 80)
    
    # ========================================================================
    # STEP 1: LOAD KNOWLEDGE BASE
    # ========================================================================
    print(f"\n๐Ÿ“– STEP 1: Loading knowledge base...")
    print(f"   File: {KB_JSONL_FILE}")
    
    if not os.path.exists(KB_JSONL_FILE):
        print(f"   โŒ ERROR: File not found!")
        return False
    
    kb_data = []
    with open(KB_JSONL_FILE, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            try:
                kb_data.append(json.loads(line))
            except json.JSONDecodeError as e:
                print(f"   โš ๏ธ Warning: Skipping invalid JSON on line {line_num}")
    
    print(f"   โœ… Loaded {len(kb_data)} documents")
    
    if len(kb_data) == 0:
        print(f"   โŒ ERROR: Knowledge base is empty!")
        return False
    
    # ========================================================================
    # STEP 2: PREPARE DOCUMENTS
    # ========================================================================
    print(f"\n๐Ÿ“ STEP 2: Preparing documents for encoding...")
    
    documents = []
    for i, item in enumerate(kb_data):
        instruction = item.get('instruction', '')
        response = item.get('response', '')
        
        if instruction and response:
            text = f"{instruction} {response}"
        elif instruction:
            text = instruction
        elif response:
            text = response
        else:
            text = "empty document"
        
        documents.append(text)
    
    print(f"   โœ… Prepared {len(documents)} documents")
    avg_len = sum(len(d) for d in documents) / len(documents)
    print(f"   Average length: {avg_len:.1f} chars")
    
    # โšก Estimate encoding time
    if DEVICE == "cuda":
        est_time = len(documents) / (BATCH_SIZE * 100)  # ~100 docs/sec on GPU
        print(f"   โšก Estimated time on GPU: {est_time:.1f} seconds")
    else:
        est_time = len(documents) / (BATCH_SIZE * 2)  # ~2 docs/sec on CPU
        print(f"   โณ Estimated time on CPU: {est_time/60:.1f} minutes")
    
    # ========================================================================
    # STEP 3: ENCODE DOCUMENTS
    # ========================================================================
    print(f"\n๐Ÿ”ฎ STEP 3: Encoding documents with trained retriever...")
    
    if not os.path.exists(RETRIEVER_MODEL_PATH):
        print(f"   โŒ ERROR: Retriever model not found!")
        return False
    
    import time
    start_time = time.time()
    
    retriever = RetrieverModel(RETRIEVER_MODEL_PATH, device=DEVICE)
    
    print(f"   Encoding {len(documents)} documents...")
    print(f"   Batch size: {BATCH_SIZE}")
    
    try:
        embeddings = retriever.encode_documents(documents, batch_size=BATCH_SIZE)
        
        elapsed = time.time() - start_time
        print(f"   โœ… Encoded {embeddings.shape[0]} documents in {elapsed:.1f}s")
        print(f"   Speed: {len(documents)/elapsed:.1f} docs/sec")
        print(f"   Embedding dimension: {embeddings.shape[1]}")
    except Exception as e:
        print(f"   โŒ ERROR during encoding: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    # ========================================================================
    # STEP 4: BUILD FAISS INDEX
    # ========================================================================
    print(f"\n๐Ÿ” STEP 4: Building FAISS index...")
    
    dimension = embeddings.shape[1]
    print(f"   Dimension: {dimension}")
    
    print(f"   Creating IndexFlatIP...")
    index = faiss.IndexFlatIP(dimension)
    
    print(f"   Normalizing embeddings...")
    faiss.normalize_L2(embeddings)
    
    print(f"   Adding {embeddings.shape[0]} vectors to FAISS index...")
    index.add(embeddings.astype('float32'))
    
    print(f"   โœ… FAISS index built successfully")
    print(f"   Total vectors: {index.ntotal}")
    
    # ========================================================================
    # STEP 5: SAVE WITH V2 FORMAT
    # ========================================================================
    print(f"\n๐Ÿ’พ STEP 5: Saving with v2 format (compatible)...")
    
    os.makedirs(os.path.dirname(OUTPUT_PKL_FILE), exist_ok=True)
    
    try:
        print(f"   Creating v2 save format...")
        save_data = {
            'format_version': 'v2',
            'index_bytes': faiss.serialize_index(index),
            'kb_data': kb_data,
            'dimension': dimension,
            'num_vectors': index.ntotal,
            'faiss_version': faiss.__version__,
            'device_used': DEVICE,
            'build_time': elapsed
        }
        
        print(f"   Pickling...")
        with open(OUTPUT_PKL_FILE, 'wb') as f:
            pickle.dump(save_data, f, protocol=pickle.HIGHEST_PROTOCOL)
        
        file_size_mb = Path(OUTPUT_PKL_FILE).stat().st_size / (1024 * 1024)
        print(f"   โœ… Saved: {OUTPUT_PKL_FILE}")
        print(f"   File size: {file_size_mb:.2f} MB")
    except Exception as e:
        print(f"   โŒ ERROR saving: {e}")
        return False
    
    # ========================================================================
    # STEP 6: VERIFY
    # ========================================================================
    print(f"\nโœ… STEP 6: Verifying...")
    
    try:
        with open(OUTPUT_PKL_FILE, 'rb') as f:
            loaded = pickle.load(f)
        
        loaded_index = faiss.deserialize_index(loaded['index_bytes'])
        loaded_kb = loaded['kb_data']
        
        print(f"   โœ… Verification successful")
        print(f"   Index vectors: {loaded_index.ntotal}")
        print(f"   KB documents: {len(loaded_kb)}")
    except Exception as e:
        print(f"   โŒ ERROR verifying: {e}")
        return False
    
    # ========================================================================
    # SUCCESS!
    # ========================================================================
    total_time = time.time() - start_time
    
    print("\n" + "=" * 80)
    print("๐ŸŽ‰ SUCCESS! FAISS INDEX BUILT AND SAVED")
    print("=" * 80)
    print(f"\n๐Ÿ“Š Summary:")
    print(f"   Documents: {len(kb_data)}")
    print(f"   Vectors: {index.ntotal}")
    print(f"   Dimension: {dimension}")
    print(f"   File: {OUTPUT_PKL_FILE} ({file_size_mb:.2f} MB)")
    print(f"   Format: v2 (compatible)")
    print(f"   Device: {DEVICE}")
    print(f"   Total time: {total_time:.1f}s ({total_time/60:.1f} min)")
    print(f"   Encoding speed: {len(documents)/elapsed:.1f} docs/sec")
    print(f"\n๐Ÿš€ Next steps:")
    print(f"   1. Upload {OUTPUT_PKL_FILE} to HuggingFace Hub")
    print(f"   2. Restart your backend")
    print(f"   3. Test - should work now!")
    print("=" * 80 + "\n")
    
    return True

if __name__ == "__main__":
    success = build_faiss_index()
    
    if not success:
        print("\nโŒ FAILED TO BUILD FAISS INDEX")
        print("\nPlease check:")
        print("1. data/final_knowledge_base.jsonl exists")
        print("2. app/models/best_retriever_model.pth exists")
        print("3. You have enough RAM/VRAM")
        exit(1)


































# """
# Build FAISS Index from Scratch - COMPATIBLE VERSION
# Creates faiss_index.pkl with proper serialization for version compatibility

# Run this ONCE before starting the backend:
#     python build_faiss_index.py

# Author: Banking RAG Chatbot
# Date: November 2025
# """

# # Suppress warnings
# import os
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
# import warnings
# warnings.filterwarnings('ignore')

# import pickle
# import json
# import torch
# import torch.nn as nn
# import torch.nn.functional as F
# import faiss
# import numpy as np
# from pathlib import Path
# from transformers import AutoTokenizer, AutoModel
# from typing import List

# # ============================================================================
# # CONFIGURATION - UPDATE THESE PATHS!
# # ============================================================================

# # Where is your knowledge base JSONL file?
# KB_JSONL_FILE = "data/final_knowledge_base.jsonl"

# # Where is your trained retriever model?
# RETRIEVER_MODEL_PATH = "app/models/best_retriever_model.pth"

# # Where to save the output FAISS pickle?
# OUTPUT_PKL_FILE = "app/models/faiss_index.pkl"

# # Device (auto-detect GPU/CPU)
# DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# # Batch size for encoding (reduce if you get OOM errors)
# BATCH_SIZE = 32

# # ============================================================================
# # CUSTOM SENTENCE TRANSFORMER (Same as retriever.py)
# # ============================================================================

# class CustomSentenceTransformer(nn.Module):
#     """
#     Custom SentenceTransformer - exact copy from retriever.py
#     Uses e5-base-v2 with mean pooling and L2 normalization
#     """
    
#     def __init__(self, model_name: str = "intfloat/e5-base-v2"):
#         super().__init__()
#         print(f"   Loading base model: {model_name}...")
#         self.encoder = AutoModel.from_pretrained(model_name)
#         self.tokenizer = AutoTokenizer.from_pretrained(model_name)
#         self.config = self.encoder.config
#         print(f"   โœ… Base model loaded")
    
#     def forward(self, input_ids, attention_mask):
#         """Forward pass through BERT encoder"""
#         outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        
#         # Mean pooling
#         token_embeddings = outputs.last_hidden_state
#         input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
#         embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
#             input_mask_expanded.sum(1), min=1e-9
#         )
        
#         # L2 normalize
#         embeddings = F.normalize(embeddings, p=2, dim=1)
#         return embeddings
    
#     def encode(self, sentences: List[str], batch_size: int = 32) -> np.ndarray:
#         """Encode sentences - same as training"""
#         self.eval()
#         if isinstance(sentences, str):
#             sentences = [sentences]
        
#         # Add 'query: ' prefix for e5-base-v2
#         processed_sentences = [f"query: {s.strip()}" for s in sentences]
        
#         all_embeddings = []
#         with torch.no_grad():
#             for i in range(0, len(processed_sentences), batch_size):
#                 batch_sentences = processed_sentences[i:i + batch_size]
                
#                 # Tokenize
#                 tokens = self.tokenizer(
#                     batch_sentences,
#                     truncation=True,
#                     padding=True,
#                     max_length=128,
#                     return_tensors='pt'
#                 ).to(self.encoder.device)
                
#                 # Get embeddings
#                 embeddings = self.forward(tokens['input_ids'], tokens['attention_mask'])
#                 all_embeddings.append(embeddings.cpu().numpy())
        
#         return np.vstack(all_embeddings)

# # ============================================================================
# # RETRIEVER MODEL (Wrapper)
# # ============================================================================

# class RetrieverModel:
#     """Wrapper for trained retriever model"""
    
#     def __init__(self, model_path: str, device: str = "cpu"):
#         print(f"\n๐Ÿค– Loading retriever model...")
#         print(f"   Device: {device}")
#         self.device = device
#         self.model = CustomSentenceTransformer("intfloat/e5-base-v2").to(device)
        
#         # Load trained weights
#         print(f"   Loading weights from: {model_path}")
#         try:
#             state_dict = torch.load(model_path, map_location=device)
#             self.model.load_state_dict(state_dict)
#             print(f"   โœ… Trained weights loaded")
#         except Exception as e:
#             print(f"   โš ๏ธ Warning: Could not load trained weights: {e}")
#             print(f"   Using base e5-base-v2 model instead")
        
#         self.model.eval()
    
#     def encode_documents(self, documents: List[str], batch_size: int = 32) -> np.ndarray:
#         """Encode documents"""
#         return self.model.encode(documents, batch_size=batch_size)

# # ============================================================================
# # MAIN: BUILD FAISS INDEX
# # ============================================================================

# def build_faiss_index():
#     """Main function to build FAISS index from scratch"""
    
#     print("=" * 80)
#     print("๐Ÿ—๏ธ  BUILDING FAISS INDEX FROM SCRATCH")
#     print("=" * 80)
    
#     # ========================================================================
#     # STEP 1: LOAD KNOWLEDGE BASE
#     # ========================================================================
#     print(f"\n๐Ÿ“– STEP 1: Loading knowledge base...")
#     print(f"   File: {KB_JSONL_FILE}")
    
#     if not os.path.exists(KB_JSONL_FILE):
#         print(f"   โŒ ERROR: File not found!")
#         print(f"   Please copy your knowledge base to: {KB_JSONL_FILE}")
#         return False
    
#     kb_data = []
#     with open(KB_JSONL_FILE, 'r', encoding='utf-8') as f:
#         for line_num, line in enumerate(f, 1):
#             try:
#                 kb_data.append(json.loads(line))
#             except json.JSONDecodeError as e:
#                 print(f"   โš ๏ธ Warning: Skipping invalid JSON on line {line_num}: {e}")
    
#     print(f"   โœ… Loaded {len(kb_data)} documents")
    
#     if len(kb_data) == 0:
#         print(f"   โŒ ERROR: Knowledge base is empty!")
#         return False
    
#     # ========================================================================
#     # STEP 2: PREPARE DOCUMENTS FOR ENCODING
#     # ========================================================================
#     print(f"\n๐Ÿ“ STEP 2: Preparing documents for encoding...")
    
#     documents = []
#     for i, item in enumerate(kb_data):
#         # Combine instruction + response for embedding (same as training)
#         instruction = item.get('instruction', '')
#         response = item.get('response', '')
        
#         # Create combined text
#         if instruction and response:
#             text = f"{instruction} {response}"
#         elif instruction:
#             text = instruction
#         elif response:
#             text = response
#         else:
#             print(f"   โš ๏ธ Warning: Document {i} has no content, using placeholder")
#             text = "empty document"
        
#         documents.append(text)
    
#     print(f"   โœ… Prepared {len(documents)} documents for encoding")
#     print(f"   Average length: {sum(len(d) for d in documents) / len(documents):.1f} chars")
    
#     # ========================================================================
#     # STEP 3: LOAD RETRIEVER AND ENCODE DOCUMENTS
#     # ========================================================================
#     print(f"\n๐Ÿ”ฎ STEP 3: Encoding documents with trained retriever...")
    
#     if not os.path.exists(RETRIEVER_MODEL_PATH):
#         print(f"   โŒ ERROR: Retriever model not found!")
#         print(f"   Please copy your trained model to: {RETRIEVER_MODEL_PATH}")
#         return False
    
#     # Load retriever
#     retriever = RetrieverModel(RETRIEVER_MODEL_PATH, device=DEVICE)
    
#     # Encode all documents
#     print(f"   Encoding {len(documents)} documents...")
#     print(f"   Batch size: {BATCH_SIZE}")
#     print(f"   This may take a few minutes... โ˜•")
    
#     try:
#         embeddings = retriever.encode_documents(documents, batch_size=BATCH_SIZE)
#         print(f"   โœ… Encoded {embeddings.shape[0]} documents")
#         print(f"   Embedding dimension: {embeddings.shape[1]}")
#     except Exception as e:
#         print(f"   โŒ ERROR during encoding: {e}")
#         import traceback
#         traceback.print_exc()
#         return False
    
#     # ========================================================================
#     # STEP 4: BUILD FAISS INDEX WITH PROPER SERIALIZATION
#     # ========================================================================
#     print(f"\n๐Ÿ” STEP 4: Building FAISS index...")
    
#     dimension = embeddings.shape[1]
#     print(f"   Dimension: {dimension}")
    
#     # Create FAISS index (Inner Product = Cosine similarity after normalization)
#     print(f"   Creating IndexFlatIP...")
#     index = faiss.IndexFlatIP(dimension)
    
#     # Normalize embeddings for cosine similarity
#     print(f"   Normalizing embeddings...")
#     faiss.normalize_L2(embeddings)
    
#     # Add to index
#     print(f"   Adding {embeddings.shape[0]} vectors to FAISS index...")
#     index.add(embeddings.astype('float32'))
    
#     print(f"   โœ… FAISS index built successfully")
#     print(f"   Total vectors: {index.ntotal}")
    
#     # ========================================================================
#     # STEP 5: SAVE WITH PROPER FAISS SERIALIZATION (VERSION COMPATIBLE!)
#     # ========================================================================
#     print(f"\n๐Ÿ’พ STEP 5: Saving with FAISS serialization (version-compatible)...")
    
#     # Create models directory if it doesn't exist
#     os.makedirs(os.path.dirname(OUTPUT_PKL_FILE), exist_ok=True)
    
#     # โœ… PROPER WAY: Serialize FAISS index to bytes first
#     print(f"   Serializing FAISS index to bytes...")
#     try:
#         # Write FAISS index to bytes (works across FAISS versions!)
#         index_bytes = faiss.serialize_index(index)
        
#         # Now pickle the bytes + kb_data
#         print(f"   Pickling (index_bytes, kb_data) tuple...")
#         with open(OUTPUT_PKL_FILE, 'wb') as f:
#             pickle.dump((index_bytes, kb_data), f, protocol=pickle.HIGHEST_PROTOCOL)
        
#         file_size_mb = Path(OUTPUT_PKL_FILE).stat().st_size / (1024 * 1024)
#         print(f"   โœ… Saved: {OUTPUT_PKL_FILE}")
#         print(f"   File size: {file_size_mb:.2f} MB")
#     except Exception as e:
#         print(f"   โŒ ERROR saving pickle: {e}")
#         import traceback
#         traceback.print_exc()
#         return False
    
#     # ========================================================================
#     # STEP 6: VERIFY SAVED FILE
#     # ========================================================================
#     print(f"\nโœ… STEP 6: Verifying saved file...")
    
#     try:
#         with open(OUTPUT_PKL_FILE, 'rb') as f:
#             loaded_index_bytes, loaded_kb = pickle.load(f)
        
#         # Deserialize FAISS index from bytes
#         loaded_index = faiss.deserialize_index(loaded_index_bytes)
        
#         print(f"   โœ… Verification successful")
#         print(f"   Index vectors: {loaded_index.ntotal}")
#         print(f"   KB documents: {len(loaded_kb)}")
        
#         if loaded_index.ntotal != len(loaded_kb):
#             print(f"   โš ๏ธ WARNING: Size mismatch detected!")
#     except Exception as e:
#         print(f"   โŒ ERROR verifying file: {e}")
#         import traceback
#         traceback.print_exc()
#         return False
    
#     # ========================================================================
#     # SUCCESS!
#     # ========================================================================
#     print("\n" + "=" * 80)
#     print("๐ŸŽ‰ SUCCESS! FAISS INDEX BUILT AND SAVED")
#     print("=" * 80)
#     print(f"\n๐Ÿ“Š Summary:")
#     print(f"   Documents: {len(kb_data)}")
#     print(f"   Vectors: {index.ntotal}")
#     print(f"   Dimension: {dimension}")
#     print(f"   File: {OUTPUT_PKL_FILE} ({file_size_mb:.2f} MB)")
#     print(f"\n๐Ÿš€ Next steps:")
#     print(f"   1. Upload {OUTPUT_PKL_FILE} to HuggingFace Hub")
#     print(f"   2. Restart your backend")
#     print(f"   3. Test retrieval - should work now!")
#     print("=" * 80 + "\n")
    
#     return True

# # ============================================================================
# # RUN SCRIPT
# # ============================================================================

# if __name__ == "__main__":
#     success = build_faiss_index()
    
#     if not success:
#         print("\n" + "=" * 80)
#         print("โŒ FAILED TO BUILD FAISS INDEX")
#         print("=" * 80)
#         print("\nPlease check:")
#         print("1. Knowledge base file exists: data/final_knowledge_base.jsonl")
#         print("2. Retriever model exists: app/models/best_retriever_model.pth")
#         print("3. You have enough RAM (embeddings need ~1GB for 10k docs)")
#         print("=" * 80 + "\n")
#         exit(1)