File size: 78,818 Bytes
6d1ffdb
 
 
 
 
 
 
 
 
95ca342
 
 
 
5c79a89
 
 
 
 
 
 
6d1ffdb
6c48551
6d1ffdb
 
 
 
 
 
95ca342
 
5c79a89
 
 
b5fb8d2
 
 
 
5c79a89
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c79a89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c79a89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
5c79a89
 
 
 
 
95ca342
 
 
 
 
 
 
 
5c79a89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
5c79a89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5fb8d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c79a89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c48551
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eace42
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eace42
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec4559
 
 
 
 
 
 
 
6d1ffdb
 
4ec4559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
 
 
 
66afa80
6d1ffdb
 
 
 
66afa80
 
6d1ffdb
 
 
66afa80
 
 
6d1ffdb
 
 
66afa80
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66afa80
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c79a89
95ca342
 
5c79a89
95ca342
 
 
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
95ca342
6d1ffdb
 
 
95ca342
6d1ffdb
 
 
 
6c48551
6d1ffdb
 
6c48551
6d1ffdb
 
 
 
 
95ca342
 
6c48551
 
95ca342
 
 
 
 
6d1ffdb
6c48551
6d1ffdb
95ca342
6d1ffdb
95ca342
59dfe15
95ca342
 
 
 
 
 
6c48551
95ca342
6c48551
95ca342
6c48551
 
 
 
95ca342
59dfe15
6c48551
6d1ffdb
 
 
 
 
 
 
 
95ca342
6d1ffdb
95ca342
 
 
 
6d1ffdb
 
 
 
 
 
 
 
 
 
 
6c48551
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
6c48551
95ca342
59dfe15
95ca342
 
 
 
 
 
59dfe15
95ca342
59dfe15
 
95ca342
 
 
 
 
59dfe15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
 
59dfe15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c48551
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
59dfe15
 
 
 
 
 
6d1ffdb
59dfe15
6d1ffdb
59dfe15
6d1ffdb
59dfe15
6d1ffdb
59dfe15
 
 
 
 
 
 
6d1ffdb
59dfe15
 
 
 
6d1ffdb
59dfe15
 
95ca342
59dfe15
 
95ca342
59dfe15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
59dfe15
 
 
 
 
 
6d1ffdb
59dfe15
6d1ffdb
59dfe15
 
 
 
 
 
 
6d1ffdb
59dfe15
 
 
 
 
 
 
 
 
 
6d1ffdb
 
59dfe15
 
 
 
 
 
6d1ffdb
 
 
 
 
 
dcf628b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72f7858
6d1ffdb
 
 
 
 
4ec4559
6d1ffdb
4ec4559
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
 
 
4ec4559
 
 
 
 
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
66afa80
6d1ffdb
 
 
 
66afa80
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
5c79a89
 
 
 
 
 
 
95ca342
 
 
 
 
5c79a89
95ca342
 
 
 
 
 
 
 
b5fb8d2
 
058eb47
 
 
 
b5fb8d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
dcf628b
c20ba74
 
 
dcf628b
 
 
 
 
 
 
66afa80
 
 
 
 
 
72f7858
 
66afa80
 
 
 
 
 
dcf628b
4ec4559
 
 
 
 
 
 
 
 
 
 
dcf628b
 
 
 
 
 
 
 
 
 
 
 
 
 
6d1ffdb
dcf628b
 
 
 
 
c20ba74
dcf628b
 
 
 
 
c20ba74
dcf628b
 
 
 
 
 
 
 
 
66afa80
 
dcf628b
 
4ec4559
 
 
 
 
 
 
 
 
dcf628b
6c48551
 
6d1ffdb
dcf628b
6c48551
6d1ffdb
dcf628b
 
c20ba74
dcf628b
 
 
 
6d1ffdb
 
72f7858
6d1ffdb
 
dcf628b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72f7858
6d1ffdb
 
 
 
 
0af1f17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ca342
 
 
 
 
0af1f17
6d1ffdb
 
 
 
0af1f17
6d1ffdb
 
0af1f17
 
6d1ffdb
 
0af1f17
6d1ffdb
d085bec
0af1f17
72f7858
 
6d1ffdb
0af1f17
6d1ffdb
 
 
 
 
d085bec
6d1ffdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9af0c15
 
6d1ffdb
 
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
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699

import gradio as gr
from googleapiclient.discovery import build
import google.generativeai as genai
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import re
import os
import numpy as np
import json
import sqlite3
from datetime import datetime
import hashlib
import io
import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload

GOOGLE_API_KEY = "AIzaSyASwqVh3ELFVKH-W3WuHtmjg3XgtwjJQKg"
SEARCH_ENGINE_ID = "f34f8a4816771488b"
GEMINI_API_KEY = "AIzaSyAHPzJ_VjTX3gZLBV28d3sq97SdER2qfkc"
MODEL_PATH = "./vietnamese_fake_news_model"

genai.configure(api_key=GEMINI_API_KEY)

# Knowledge Base Configuration
KNOWLEDGE_BASE_DB = "knowledge_base.db"
CONFIDENCE_THRESHOLD = 0.95  # 95% Gemini confidence threshold for RAG knowledge base
ENABLE_KNOWLEDGE_BASE_SEARCH = True  # Enable knowledge base search with training data

# Enhanced RAG System Configuration
ENABLE_ENHANCED_RAG = True  # Enable enhanced RAG system for Google Drive
RAG_CONFIDENCE_THRESHOLD = 0.95  # 95% threshold for saving to RAG

# Cloud Storage Configuration
USE_CLOUD_STORAGE = True  # Set to True to use cloud storage instead of local DB
CLOUD_STORAGE_TYPE = "google_drive"  # Options: "google_drive", "google_cloud", "local"
GOOGLE_DRIVE_FILE_ID = None  # Will be set when file is created

# Load Google Drive file ID if it exists
try:
    if os.path.exists('google_drive_file_id.txt'):
        with open('google_drive_file_id.txt', 'r') as f:
            GOOGLE_DRIVE_FILE_ID = f.read().strip()
        print(f"📁 Loaded Google Drive file ID: {GOOGLE_DRIVE_FILE_ID}")
except Exception as e:
    print(f"Could not load Google Drive file ID: {e}")
GOOGLE_CLOUD_BUCKET = "your-bucket-name"  # For Google Cloud Storage

print("Loading the DistilBERT model we trained...")
try:
    if os.path.exists(MODEL_PATH):
        tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
        model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
        print("DistilBERT model loaded successfully!")
    else:
        print(f"Model directory '{MODEL_PATH}' not found!")
        print("Our custom model isn't available, trying a backup model...")
        try:
            tokenizer = AutoTokenizer.from_pretrained("distilbert-base-multilingual-cased")
            model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-multilingual-cased", num_labels=2)
            print("Fallback DistilBERT model loaded successfully!")
        except Exception as fallback_error:
            print(f"Fallback model also failed: {fallback_error}")
            tokenizer = None
            model = None
except Exception as e:
    print(f"Error loading DistilBERT model: {e}")
    print("Something went wrong, trying the backup model...")
    try:
        tokenizer = AutoTokenizer.from_pretrained("distilbert-base-multilingual-cased")
        model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-multilingual-cased", num_labels=2)
        print("Fallback DistilBERT model loaded successfully!")
    except Exception as fallback_error:
        print(f"Fallback model also failed: {fallback_error}")
        tokenizer = None
        model = None

# --- CLOUD STORAGE FUNCTIONS ---
def get_google_drive_service():
    """Get authenticated Google Drive service for Hugging Face Spaces"""
    try:
        SCOPES = ['https://www.googleapis.com/auth/drive.file']
        creds = None
        
        # Check if running on Hugging Face Spaces
        import os
        is_hf_space = os.getenv('SPACE_ID') is not None
        
        if is_hf_space:
            # For Hugging Face Spaces, use environment variables
            client_id = os.getenv('GOOGLE_CLIENT_ID')
            client_secret = os.getenv('GOOGLE_CLIENT_SECRET')
            refresh_token = os.getenv('GOOGLE_REFRESH_TOKEN')
            
            if client_id and client_secret and refresh_token:
                creds = Credentials.from_authorized_user_info({
                    'client_id': client_id,
                    'client_secret': client_secret,
                    'refresh_token': refresh_token,
                    'token_uri': 'https://oauth2.googleapis.com/token'
                }, SCOPES)
            else:
                print("⚠️ Google Drive credentials not found in Hugging Face secrets")
                return None
        else:
            # For local development, use files
            if os.path.exists('token.json'):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            
            # If no valid credentials, request authorization
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    if os.path.exists('credentials.json'):
                        flow = InstalledAppFlow.from_client_secrets_file(
                            'credentials.json', SCOPES)
                        creds = flow.run_local_server(port=0)
                    else:
                        print("⚠️ credentials.json not found for local development")
                        return None
                
                # Save credentials for next run
                with open('token.json', 'w') as token:
                    token.write(creds.to_json())
        
        return build('drive', 'v3', credentials=creds)
    except Exception as e:
        print(f"Error setting up Google Drive: {e}")
        return None

def upload_to_google_drive(data, filename="knowledge_base.json"):
    """Upload knowledge base data to Google Drive"""
    try:
        service = get_google_drive_service()
        if not service:
            return None
        
        # Convert data to JSON
        json_data = json.dumps(data, ensure_ascii=False, indent=2)
        file_metadata = {
            'name': filename,
            'parents': []  # Root folder
        }
        
        media = MediaIoBaseUpload(
            io.BytesIO(json_data.encode('utf-8')),
            mimetype='application/json'
        )
        
        file = service.files().create(
            body=file_metadata,
            media_body=media,
            fields='id'
        ).execute()
        
        print(f"✅ Uploaded {filename} to Google Drive (ID: {file.get('id')})")
        return file.get('id')
        
    except Exception as e:
        print(f"Error uploading to Google Drive: {e}")
        return None

def download_from_google_drive(file_id):
    """Download knowledge base data from Google Drive"""
    try:
        service = get_google_drive_service()
        if not service:
            return []
        
        request = service.files().get_media(fileId=file_id)
        file_content = io.BytesIO()
        downloader = MediaIoBaseDownload(file_content, request)
        
        done = False
        while done is False:
            status, done = downloader.next_chunk()
        
        file_content.seek(0)
        data = json.loads(file_content.read().decode('utf-8'))
        
        print(f"✅ Downloaded knowledge base from Google Drive")
        return data
        
    except Exception as e:
        print(f"Error downloading from Google Drive: {e}")
        return []

def save_knowledge_base_cloud(data):
    """Save knowledge base to cloud storage"""
    if CLOUD_STORAGE_TYPE == "google_drive":
        file_id = upload_to_google_drive(data)
        if file_id:
            global GOOGLE_DRIVE_FILE_ID
            GOOGLE_DRIVE_FILE_ID = file_id
        return file_id is not None
    elif CLOUD_STORAGE_TYPE == "google_cloud":
        # TODO: Implement Google Cloud Storage
        print("Google Cloud Storage not implemented yet")
        return False
    return False

def load_knowledge_base_cloud():
    """Load knowledge base from cloud storage"""
    if CLOUD_STORAGE_TYPE == "google_drive" and GOOGLE_DRIVE_FILE_ID:
        return download_from_google_drive(GOOGLE_DRIVE_FILE_ID)
    elif CLOUD_STORAGE_TYPE == "google_cloud":
        # TODO: Implement Google Cloud Storage
        print("Google Cloud Storage not implemented yet")
        return []
    return []

# --- KNOWLEDGE BASE MANAGEMENT ---
def init_knowledge_base():
    """Initialize the SQLite knowledge base"""
    conn = sqlite3.connect(KNOWLEDGE_BASE_DB)
    cursor = conn.cursor()
    
    cursor.execute('''

        CREATE TABLE IF NOT EXISTS knowledge_entries (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            content_hash TEXT UNIQUE,

            news_text TEXT,

            prediction TEXT,

            confidence REAL,

            search_results TEXT,

            gemini_analysis TEXT,

            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            last_accessed TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            access_count INTEGER DEFAULT 1

        )

    ''')
    
    conn.commit()
    conn.close()
    print("Knowledge base initialized successfully!")

def add_to_knowledge_base(news_text, prediction, confidence, search_results, gemini_analysis):
    """Add high-confidence result to knowledge base"""
    try:
        # Create content hash for deduplication
        content_hash = hashlib.md5(news_text.encode('utf-8')).hexdigest()
        
        if USE_CLOUD_STORAGE:
            # Add to cloud storage
            data = load_knowledge_base_cloud()
            
            # Check if entry already exists
            for entry in data:
                if entry.get('content_hash') == content_hash:
                    print(f"Entry already exists in cloud knowledge base (hash: {content_hash[:8]}...)")
                    return False
            
            # Create new entry
            new_entry = {
                'content_hash': content_hash,
                'news_text': news_text,
                'prediction': prediction,
                'confidence': confidence,
                'search_results': search_results,
                'gemini_analysis': gemini_analysis,
                'created_at': datetime.now().isoformat(),
                'last_accessed': datetime.now().isoformat(),
                'access_count': 1
            }
            
            # Add to data and save to cloud
            data.append(new_entry)
            success = save_knowledge_base_cloud(data)
            
            if success:
                print(f"✅ Added high-confidence result to cloud knowledge base (confidence: {confidence:.1%})")
                print(f"   Hash: {content_hash[:8]}...")
                print(f"   Prediction: {prediction}")
                return True
            else:
                return False
        else:
            # Add to local SQLite database
            conn = sqlite3.connect(KNOWLEDGE_BASE_DB)
            cursor = conn.cursor()
            
            # Check if entry already exists
            cursor.execute('SELECT id FROM knowledge_entries WHERE content_hash = ?', (content_hash,))
            if cursor.fetchone():
                print(f"Entry already exists in knowledge base (hash: {content_hash[:8]}...)")
                conn.close()
                return False
            
            # Insert new entry
            cursor.execute('''

                INSERT INTO knowledge_entries 

                (content_hash, news_text, prediction, confidence, search_results, gemini_analysis)

                VALUES (?, ?, ?, ?, ?, ?)

            ''', (
                content_hash,
                news_text,
                prediction,
                confidence,
                json.dumps(search_results, ensure_ascii=False),
                gemini_analysis
            ))
            
            conn.commit()
            conn.close()
            
            print(f"✅ Added high-confidence result to knowledge base (confidence: {confidence:.1%})")
            print(f"   Hash: {content_hash[:8]}...")
            print(f"   Prediction: {prediction}")
            return True
        
    except Exception as e:
        print(f"Error adding to knowledge base: {e}")
        return False

def search_knowledge_base(query_text, limit=5):
    """Search the knowledge base for similar entries"""
    try:
        if USE_CLOUD_STORAGE:
            # Search in cloud storage
            data = load_knowledge_base_cloud()
            if not data:
                return []
            
            # Simple text similarity search in JSON data
            results = []
            query_lower = query_text[:50].lower()
            
            for entry in data:
                if (query_lower in entry.get('news_text', '').lower() or 
                    query_lower in entry.get('gemini_analysis', '').lower()):
                    results.append((
                        entry['news_text'],
                        entry['prediction'],
                        entry['confidence'],
                        entry.get('search_results', []),
                        entry.get('gemini_analysis', ''),
                        entry.get('created_at', ''),
                        entry.get('access_count', 1)
                    ))
            
            # Sort by confidence and access count
            results.sort(key=lambda x: (x[2], x[6]), reverse=True)
            results = results[:limit]
            
            if results:
                print(f"📚 Found {len(results)} similar entries in cloud knowledge base")
                return results
            else:
                return []
        else:
            # Search in local SQLite database
            conn = sqlite3.connect(KNOWLEDGE_BASE_DB)
            cursor = conn.cursor()
            
            # Simple text similarity search (you can enhance this with embeddings later)
            cursor.execute('''

                SELECT news_text, prediction, confidence, search_results, gemini_analysis, 

                       created_at, access_count

                FROM knowledge_entries 

                WHERE news_text LIKE ? OR gemini_analysis LIKE ?

                ORDER BY confidence DESC, access_count DESC

                LIMIT ?

            ''', (f'%{query_text[:50]}%', f'%{query_text[:50]}%', limit))
            
            results = cursor.fetchall()
            
            # Update access count and last_accessed
            for result in results:
                cursor.execute('''

                    UPDATE knowledge_entries 

                    SET access_count = access_count + 1, last_accessed = CURRENT_TIMESTAMP

                    WHERE news_text = ?

                ''', (result[0],))
            
            conn.commit()
            conn.close()
            
            if results:
                print(f"📚 Found {len(results)} similar entries in knowledge base")
                return results
            else:
                return []
            
    except Exception as e:
        print(f"Error searching knowledge base: {e}")
        return []

def format_knowledge_for_rag(knowledge_results):
    """Format knowledge base results for RAG augmentation"""
    if not knowledge_results:
        return ""
    
    knowledge_summary = "\n=== KIẾN THỨC TƯƠNG TỰ TỪ CƠ SỞ DỮ LIỆU ===\n"
    
    for i, (news_text, prediction, confidence, search_results, gemini_analysis, created_at, access_count) in enumerate(knowledge_results, 1):
        knowledge_summary += f"\n{i}. Tin tức tương tự (Độ tin cậy: {confidence:.1%}, Lần truy cập: {access_count}):\n"
        knowledge_summary += f"   Nội dung: {news_text[:200]}...\n"
        knowledge_summary += f"   Kết luận: {prediction}\n"
        knowledge_summary += f"   Thời gian: {created_at}\n"
    
    knowledge_summary += "\n==========================================\n"
    return knowledge_summary

def get_knowledge_base_stats():
    """Get statistics about the knowledge base"""
    try:
        conn = sqlite3.connect(KNOWLEDGE_BASE_DB)
        cursor = conn.cursor()
        
        # Get total entries
        cursor.execute('SELECT COUNT(*) FROM knowledge_entries')
        total_entries = cursor.fetchone()[0]
        
        # Get entries by prediction
        cursor.execute('SELECT prediction, COUNT(*) FROM knowledge_entries GROUP BY prediction')
        prediction_counts = dict(cursor.fetchall())
        
        # Get average confidence
        cursor.execute('SELECT AVG(confidence) FROM knowledge_entries')
        avg_confidence = cursor.fetchone()[0] or 0
        
        # Get most accessed entries
        cursor.execute('SELECT news_text, access_count FROM knowledge_entries ORDER BY access_count DESC LIMIT 3')
        top_accessed = cursor.fetchall()
        
        conn.close()
        
        return {
            'total_entries': total_entries,
            'prediction_counts': prediction_counts,
            'avg_confidence': avg_confidence,
            'top_accessed': top_accessed
        }
        
    except Exception as e:
        print(f"Error getting knowledge base stats: {e}")
        return None

# Initialize knowledge base on startup
init_knowledge_base()

# Initialize Enhanced RAG System
if ENABLE_ENHANCED_RAG:
    try:
        from rag_news_manager import initialize_rag_system
        print("🚀 Initializing Enhanced RAG System...")
        if initialize_rag_system():
            print("✅ Enhanced RAG System initialized successfully!")
        else:
            print("⚠️ Enhanced RAG System initialization failed - continuing without it")
            ENABLE_ENHANCED_RAG = False
    except ImportError as e:
        print(f"⚠️ Enhanced RAG System not available: {e}")
        ENABLE_ENHANCED_RAG = False
    except Exception as e:
        print(f"⚠️ Enhanced RAG System initialization error: {e}")
        ENABLE_ENHANCED_RAG = False

def populate_knowledge_base_from_training_data():
    """Populate knowledge base with existing training data"""
    try:
        import pandas as pd
        
        # Load training data
        df = pd.read_csv('train_final.csv')
        print(f"📚 Loading {len(df)} training samples into knowledge base...")
        
        conn = sqlite3.connect(KNOWLEDGE_BASE_DB)
        cursor = conn.cursor()
        
        added_count = 0
        skipped_count = 0
        
        for index, row in df.iterrows():
            news_text = str(row['content'])
            label = int(row['label'])
            prediction = "REAL" if label == 0 else "FAKE"
            
            # Create content hash for deduplication
            content_hash = hashlib.md5(news_text.encode('utf-8')).hexdigest()
            
            # Check if entry already exists
            cursor.execute('SELECT id FROM knowledge_entries WHERE content_hash = ?', (content_hash,))
            if cursor.fetchone():
                skipped_count += 1
                continue
            
            # Create synthetic analysis for training data
            synthetic_analysis = f"""1. KẾT LUẬN: {prediction}



2. ĐỘ TIN CẬY: THẬT: {95 if prediction == 'REAL' else 5}% / GIẢ: {5 if prediction == 'REAL' else 95}%



3. PHÂN TÍCH CHI TIẾT:

- Nội dung: {'Tin tức được xác minh từ nguồn đào tạo' if prediction == 'REAL' else 'Tin tức giả được xác định từ nguồn đào tạo'}

- Nguồn tin: Dữ liệu huấn luyện đã được xác minh

- Ngữ cảnh: Mẫu từ bộ dữ liệu huấn luyện DistilBERT

- Ngôn ngữ: {'Ngôn ngữ khách quan, tin cậy' if prediction == 'REAL' else 'Ngôn ngữ có dấu hiệu tin giả'}

- Thời gian: Dữ liệu huấn luyện đã được kiểm chứng



4. CÁC DẤU HIỆU CẢNH BÁO: {'Không có dấu hiệu cảnh báo' if prediction == 'REAL' else 'Tin tức được xác định là giả từ nguồn đào tạo'}



5. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC:

- Nguồn: Dữ liệu huấn luyện đã được xác minh

- Độ tin cậy: Cao (từ bộ dữ liệu đào tạo)

- Lưu ý: Mẫu từ tập huấn luyện DistilBERT"""
            
            # Insert training sample
            cursor.execute('''

                INSERT INTO knowledge_entries 

                (content_hash, news_text, prediction, confidence, search_results, gemini_analysis)

                VALUES (?, ?, ?, ?, ?, ?)

            ''', (
                content_hash,
                news_text,
                prediction,
                0.95,  # High confidence for training data
                json.dumps([], ensure_ascii=False),  # Empty search results for training data
                synthetic_analysis
            ))
            
            added_count += 1
            
            # Show progress every 1000 entries
            if added_count % 1000 == 0:
                print(f"   Added {added_count} entries...")
        
        conn.commit()
        conn.close()
        
        print(f"✅ Knowledge base populated successfully!")
        print(f"   📊 Added: {added_count} entries")
        print(f"   ⏭️ Skipped: {skipped_count} duplicates")
        print(f"   🎯 Total entries: {added_count}")
        
        return True
        
    except Exception as e:
        print(f"❌ Error populating knowledge base: {e}")
        return False

# Populate knowledge base with training data on startup
print("🚀 Populating knowledge base with training data...")
populate_knowledge_base_from_training_data()

CREDIBLE_SOURCES = {
    'vnexpress.net': 0.95,
    'tuoitre.vn': 0.95,
    'thanhnien.vn': 0.90,
    'dantri.com.vn': 0.90,
    'vietnamnet.vn': 0.85,
    'zing.vn': 0.85,
    'kenh14.vn': 0.80,
    'soha.vn': 0.80,
    'baotintuc.vn': 0.85,
    'nhandan.vn': 0.90,
    'laodong.vn': 0.85,
    'congan.com.vn': 0.90,
    'quochoi.vn': 0.95,
    'chinhphu.vn': 0.95,
    'moh.gov.vn': 0.90,
    'mofa.gov.vn': 0.90,
    'mard.gov.vn': 0.85,
    'moc.gov.vn': 0.85,
    'mof.gov.vn': 0.85,
    'mst.gov.vn': 0.85,
    'wikipedia.org': 0.95,
    'bbc.com': 0.95,
    'bbc.co.uk': 0.95,
    'cnn.com': 0.90,
    'reuters.com': 0.95,
    'ap.org': 0.95,
    'espn.com': 0.85,
    'fifa.com': 0.95,
    'nytimes.com': 0.90,
    'washingtonpost.com': 0.90,
    'theguardian.com': 0.90
}

def clean_text(text):
    """Clean up the text before feeding it to our model"""
    if not isinstance(text, str):
        text = str(text)
    text = re.sub(r'\s+', ' ', text.strip())
    if len(text) < 10:
        text = "Tin tức ngắn: " + text
    return text

def predict_with_distilbert(text):
    """Run the text through our trained DistilBERT model to get a prediction"""
    if model is None or tokenizer is None:
        return None, None, None, None
    
    try:
        clean_text_input = clean_text(text)
        inputs = tokenizer(
            clean_text_input,
            return_tensors="pt",
            truncation=True,
            padding=True,
            max_length=512
        )
        
        
        with torch.no_grad():
            outputs = model(**inputs)
            predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
        
        
        real_score = predictions[0][0].item()
        fake_score = predictions[0][1].item()
        
        
        if real_score > fake_score:
            prediction = "REAL"
            confidence = real_score
        else:
            prediction = "FAKE"
            confidence = fake_score
        
        return prediction, confidence, real_score, fake_score
        
    except Exception as e:
        print(f"DistilBERT prediction error: {e}")
        return None, None, None, None

def process_search_results(items):
    
    search_results = []
    for item in items:
        search_results.append({
            'title': item.get('title', ''),
            'snippet': item.get('snippet', ''),
            'link': item.get('link', '')
        })
    return search_results

def google_search_fallback(news_text):
    print("Google Search is unavailable - using enhanced content analysis")
    # Enhanced content analysis without external search
    fake_indicators = ['giả', 'sai', 'không đúng', 'bịa đặt', 'lừa đảo', 'fake news', 'tin đồn', 'nghi vấn']
    real_indicators = ['chính thức', 'xác nhận', 'chính xác', 'đúng', 'verified', 'chính phủ', 'bộ y tế', 'cơ quan']
    
    text_lower = news_text.lower()
    fake_count = sum(1 for word in fake_indicators if word in text_lower)
    real_count = sum(1 for word in real_indicators if word in text_lower)
    
    # Create more detailed analysis
    analysis_details = []
    if fake_count > real_count:
        analysis_details.append("Nhiều từ khóa nghi ngờ được sử dụng")
    elif real_count > fake_count:
        analysis_details.append("Có từ khóa xác thực từ nguồn chính thức")
    
    # Check for other patterns
    if len(news_text) < 100:
        analysis_details.append("Tin tức quá ngắn, thiếu thông tin chi tiết")
    if '!' in news_text or '!!!' in news_text:
        analysis_details.append("Sử dụng dấu chấm than thái quá")
    
    snippet = f"Phân tích nội dung: {fake_count} từ nghi ngờ, {real_count} từ xác thực. "
    snippet += "; ".join(analysis_details) if analysis_details else "Không phát hiện dấu hiệu đặc biệt"
    
    return [{
        'title': 'Phân tích nội dung chi tiết (không có tìm kiếm Google)',
        'snippet': snippet,
        'link': 'content-analysis-only'
    }]



def google_search(news_text):
    """Search Google for information about the news, with backup options if it fails"""
    try:
        service = build("customsearch", "v1", developerKey=GOOGLE_API_KEY)
        
        
        search_queries = []
        
        
        if "Argentina" in news_text and "World Cup" in news_text:
            search_queries = [
                "Argentina World Cup 2022 champion winner",
                "Argentina vô địch World Cup 2022",
                "World Cup 2022 Argentina final"
            ]
        elif "COVID" in news_text or "covid" in news_text:
            search_queries = [
                "COVID-19 Vietnam news",
                "COVID Vietnam 2022 2023",
                "dịch COVID Việt Nam"
            ]
        else:
            
            vietnamese_words = re.findall(r'[À-ỹ]+', news_text)
            english_words = re.findall(r'[A-Za-z]+', news_text)
            numbers = re.findall(r'\d{4}', news_text)  # Years
            
            
            if english_words:
                search_queries.append(' '.join(english_words[:5]))
            if vietnamese_words:
                search_queries.append(' '.join(vietnamese_words[:5]))
            if numbers:
                search_queries.append(' '.join(english_words[:3] + numbers))
            
            
            keywords = re.findall(r'[A-Za-zÀ-ỹ]+|\b(?:19|20)\d{2}\b|\b\d{1,2}\b', news_text)
            search_queries.append(' '.join(keywords[:10]))
        
        
        for i, search_query in enumerate(search_queries):
            if not search_query.strip():
                continue
                
            print(f"Strategy {i+1}: Searching for '{search_query}'")
            
            result = service.cse().list(
                q=search_query,
                cx=SEARCH_ENGINE_ID,
                num=10  # Restored to 10 for more comprehensive results
            ).execute()
            
            print(f"API Response keys: {list(result.keys())}")
            if 'searchInformation' in result:
                print(f"Total results: {result['searchInformation'].get('totalResults', 'Unknown')}")
            
            if 'items' in result and result['items']:
                print(f"Found {len(result['items'])} results with strategy {i+1}")
                return process_search_results(result['items'])
            else:
                print(f"No results with strategy {i+1}")
        
        
        print("All strategies failed, trying simple phrase search...")
        simple_query = news_text[:30]  # First 30 characters
        result = service.cse().list(
            q=simple_query,
            cx=SEARCH_ENGINE_ID,
            num=10
        ).execute()
        
        if 'items' in result and result['items']:
            print(f"Found {len(result['items'])} results with simple search")
            return process_search_results(result['items'])
        
        print("All search strategies failed, using fallback...")
        return google_search_fallback(news_text)
            
    except Exception as e:
        print(f"Google Search error: {e}")
        print(f"Error type: {type(e).__name__}")
        
        
        error_str = str(e).lower()
        if any(keyword in error_str for keyword in ["403", "blocked", "quota", "limit", "exceeded"]):
            print("Google Search API blocked/quota exceeded, using fallback...")
            # Return error information along with fallback results
            fallback_results = google_search_fallback(news_text)
            return {
                'results': fallback_results,
                'error': 'QUOTA_EXCEEDED',
                'error_message': 'Google Search API quota exceeded. Using content analysis only.',
                'error_details': str(e)
            }
        elif "invalid" in error_str or "unauthorized" in error_str:
            print("API key issue, using fallback...")
            fallback_results = google_search_fallback(news_text)
            return {
                'results': fallback_results,
                'error': 'API_KEY_INVALID',
                'error_message': 'Google Search API key invalid. Using content analysis only.',
                'error_details': str(e)
            }
        else:
            print("Unknown Google Search error, using fallback...")
            fallback_results = google_search_fallback(news_text)
            return {
                'results': fallback_results,
                'error': 'UNKNOWN_ERROR',
                'error_message': 'Google Search failed. Using content analysis only.',
                'error_details': str(e)
            }

def analyze_sources(search_results):
    """Check how trustworthy the news sources are"""
    if not search_results:
        return 0.50, 0.20, "No sources found", []
    
    
    credible_count = 0
    total_sources = len(search_results)
    found_sources = []
    credible_sources_found = []
    
    for result in search_results:
        domain = result['link'].split('/')[2] if '//' in result['link'] else ''
        found_sources.append(domain)
        
        # Check if this domain matches any credible source
        for source, credibility in CREDIBLE_SOURCES.items():
            if source in domain:
                credible_count += 1
                credible_sources_found.append(f"{source} ({credibility:.0%})")
                break
    
    source_credibility = credible_count / total_sources if total_sources > 0 else 0.50
    
    
    popularity_score = min(1.0, total_sources / 5.0)  # Normalize to 0-1
    
    # Create a summary of what we found
    if source_credibility > 0.7:
        credibility_text = f"High credibility: {credible_count}/{total_sources} sources from reputable outlets"
    elif source_credibility > 0.4:
        credibility_text = f"Medium credibility: {credible_count}/{total_sources} sources from reputable outlets"
    else:
        credibility_text = f"Low credibility: {credible_count}/{total_sources} sources from reputable outlets"
    
    return source_credibility, popularity_score, credibility_text, found_sources, credible_sources_found

def analyze_source_support(news_text, search_results):
    """Check if the search results agree or disagree with the news"""
    if not search_results:
        return 0.5, "No sources to analyze"
    
    support_count = 0
    contradict_count = 0
    total_sources = len(search_results)
    
    # Look for years mentioned in the news
    import re
    news_years = re.findall(r'\b(20\d{2})\b', news_text)
    news_year = news_years[0] if news_years else None
    
    for result in search_results:
        title_snippet = (result.get('title', '') + ' ' + result.get('snippet', '')).lower()
        
        # See if the years match up
        if news_year:
            source_years = re.findall(r'\b(20\d{2})\b', title_snippet)
            if source_years and news_year not in source_years:
                contradict_count += 1
                continue
        
        # Look for words that suggest agreement or disagreement
        support_keywords = ['confirm', 'verify', 'true', 'accurate', 'correct', 'xác nhận', 'chính xác', 'đúng']
        contradict_keywords = ['false', 'fake', 'incorrect', 'wrong', 'sai', 'giả', 'không đúng']
        
        support_score = sum(1 for keyword in support_keywords if keyword in title_snippet)
        contradict_score = sum(1 for keyword in contradict_keywords if keyword in title_snippet)
        
        if contradict_score > support_score:
            contradict_count += 1
        elif support_score > contradict_score:
            support_count += 1
        else:
            # If unclear, assume slight support
            support_count += 0.5
    
    support_ratio = support_count / total_sources if total_sources > 0 else 0.5
    
    if support_ratio > 0.7:
        support_text = f"Sources strongly support the news: {support_count:.1f}/{total_sources} sources confirm"
    elif support_ratio > 0.4:
        support_text = f"Sources mixed: {support_count:.1f}/{total_sources} sources support, {contradict_count} contradict"
    else:
        support_text = f"Sources contradict the news: {contradict_count}/{total_sources} sources contradict"
    
    return support_ratio, support_text

def analyze_with_gemini(news_text, search_results, distilbert_prediction, distilbert_confidence):
    """Use Gemini AI to analyze the news and compare with our model results"""
    try:
        # Knowledge base search with training data
        if ENABLE_KNOWLEDGE_BASE_SEARCH:
            print("🔍 Searching knowledge base for similar entries...")
            knowledge_results = search_knowledge_base(news_text, limit=2)  # Reduced to 2 for speed
            knowledge_context = format_knowledge_for_rag(knowledge_results)
        else:
            knowledge_context = ""
        # Try to use the latest Gemini model available
        try:
            model = genai.GenerativeModel('gemini-2.0-flash-exp')
        except:
            try:
                model = genai.GenerativeModel('gemini-2.5-flash')
            except:
                try:
                    model = genai.GenerativeModel('gemini-1.5-pro')
                except:
                    model = genai.GenerativeModel('gemini-1.5-flash')
        
        # Format the search results for Gemini (limit to top 3 for speed)
        search_summary = ""
        if search_results:
            search_summary = "Kết quả tìm kiếm Google:\n"
            for i, result in enumerate(search_results[:3], 1):  # Reduced from 5 to 3
                search_summary += f"{i}. {result['title']}\n   {result['snippet']}\n   Nguồn: {result['link']}\n\n"
        else:
            search_summary = "Không tìm thấy kết quả tìm kiếm Google cho tin tức này. Điều này có thể do API bị giới hạn hoặc tin tức quá mới/chưa được đăng tải."
        
        # Note: We're not including DistilBERT results to keep Gemini analysis independent
        
        prompt = f"""

Bạn là một chuyên gia phân tích tin tức chuyên nghiệp. Hãy phân tích chi tiết tin tức sau và đánh giá độ tin cậy của nó:



"{news_text}"



{search_summary}



{knowledge_context}



Hãy thực hiện phân tích toàn diện theo các tiêu chí sau:



1. Phân tích nội dung: Kiểm tra tính logic, mâu thuẫn, ngôn ngữ cảm xúc thái quá

2. Phân tích nguồn tin: Đánh giá uy tín và độ tin cậy của nguồn

3. Phân tích ngữ cảnh: So sánh với thông tin có sẵn và kiến thức thực tế

4. Phân tích ngôn ngữ: Tìm dấu hiệu của tin giả như từ ngữ gây sốc, cảm xúc

5. Phân tích thời gian: Kiểm tra tính hợp lý về mặt thời gian



Trả lời theo định dạng sau (chỉ bằng tiếng Việt, viết chi tiết và chuyên nghiệp):



1. KẾT LUẬN: [THẬT/GIẢ/KHÔNG XÁC ĐỊNH]



2. ĐỘ TIN CẬY: [THẬT: X% / GIẢ: Y%] (Trong đó X% là độ tin cậy tin THẬT, Y% là độ tin cậy tin GIẢ, X+Y=100%)



3. PHÂN TÍCH CHI TIẾT:

- Nội dung: [Phân tích chi tiết về nội dung tin tức]

- Nguồn tin: [Đánh giá về nguồn và độ tin cậy]

- Ngữ cảnh: [So sánh với thông tin có sẵn]

- Ngôn ngữ: [Phân tích cách sử dụng từ ngữ]

- Thời gian: [Kiểm tra tính hợp lý về mặt thời gian]



4. CÁC DẤU HIỆU CẢNH BÁO: [Liệt kê các dấu hiệu đáng ngờ nếu có]



5. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC:

- [Hướng dẫn cụ thể để kiểm chứng thông tin]

- [Các nguồn tin đáng tin cậy để tham khảo]

- [Cách phân biệt tin thật và tin giả]



QUAN TRỌNG: Trong phần "ĐỘ TIN CẬY", hãy cung cấp tỷ lệ phần trăm chính xác dựa trên phân tích của bạn. Ví dụ: "THẬT: 95% / GIẢ: 5%" nghĩa là 95% tin tức này là THẬT, 5% là GIẢ.



Viết chi tiết, chuyên nghiệp và hữu ích cho người đọc.

"""
        
        print("Calling Gemini API...")
        print(f"DEBUG - News text being analyzed: {news_text}")
        print(f"DEBUG - Search results count: {len(search_results)}")
        if search_results:
            print(f"DEBUG - First search result title: {search_results[0].get('title', 'No title')}")
        
        # Use settings optimized for faster processing
        generation_config = genai.types.GenerationConfig(
            temperature=0.3,  # Lower for more consistent results
            top_p=0.8,        # Reduced for faster processing
            top_k=20,         # Reduced for faster processing
            max_output_tokens=1000  # Reduced for faster responses
        )
        response = model.generate_content(prompt, generation_config=generation_config)
        print("Gemini API response received successfully")
        return response.text
        
    except Exception as e:
        print(f"Gemini analysis error: {e}")
        print(f"Error type: {type(e).__name__}")
        
        # If we hit the API limit, provide a basic analysis
        if "429" in str(e) or "quota" in str(e).lower():
            print("Gemini API quota exceeded, providing enhanced fallback analysis...")
            
            # Enhanced analysis based on content patterns
            fake_patterns = ['giả', 'sai', 'không đúng', 'bịa đặt', 'lừa đảo', 'fake news', 'tin đồn']
            real_patterns = ['chính thức', 'xác nhận', 'chính xác', 'đúng', 'verified', 'chính phủ', 'bộ y tế']
            
            news_lower = news_text.lower()
            fake_score = sum(1 for pattern in fake_patterns if pattern in news_lower)
            real_score = sum(1 for pattern in real_patterns if pattern in news_lower)
            
            # Adjust prediction based on patterns
            if fake_score > real_score and distilbert_prediction == 'FAKE':
                confidence_boost = "Cao (có từ khóa nghi ngờ)"
            elif real_score > fake_score and distilbert_prediction == 'REAL':
                confidence_boost = "Cao (có từ khóa xác thực)"
            else:
                confidence_boost = "Trung bình"
            
            # Create detailed fallback analysis
            conclusion = 'THẬT' if distilbert_prediction == 'REAL' else 'GIẢ' if distilbert_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH'
            
            # Enhanced analysis based on content patterns
            suspicious_patterns = []
            if fake_score > 0:
                suspicious_patterns.append(f"Tìm thấy {fake_score} từ khóa nghi ngờ")
            if real_score > 0:
                suspicious_patterns.append(f"Tìm thấy {real_score} từ khóa xác thực")
            
            warning_signs = []
            if 'cảnh báo' in news_lower or 'nguy hiểm' in news_lower:
                warning_signs.append("Sử dụng từ ngữ gây sợ hãi")
            if 'ngay lập tức' in news_lower or 'khẩn cấp' in news_lower:
                warning_signs.append("Tạo cảm giác cấp bách không cần thiết")
            if len(news_text) < 100:
                warning_signs.append("Tin tức quá ngắn, thiếu thông tin chi tiết")
            
            fallback_analysis = f"""1. KẾT LUẬN: {conclusion}



2. ĐỘ TIN CẬY: {'THẬT: 5% / GIẢ: 95%' if conclusion == 'GIẢ' else 'THẬT: 95% / GIẢ: 5%' if conclusion == 'THẬT' else 'THẬT: 50% / GIẢ: 50%'}



3. PHÂN TÍCH CHI TIẾT:

- Nội dung: {'Tin tức có vẻ hợp lý' if distilbert_prediction == 'REAL' else 'Tin tức có nhiều dấu hiệu đáng ngờ' if distilbert_prediction == 'FAKE' else 'Nội dung không rõ ràng'}

- Nguồn tin: Google Search không khả dụng (hết quota) - không thể kiểm tra nguồn

- Ngữ cảnh: Phân tích từ khóa: {confidence_boost}

- Ngôn ngữ: {'Ngôn ngữ trung tính' if fake_score == real_score else 'Có dấu hiệu cảm xúc thái quá' if fake_score > real_score else 'Ngôn ngữ khách quan'}

- Thời gian: Không thể xác minh do thiếu thông tin bổ sung



4. CÁC DẤU HIỆU CẢNH BÁO: 

{chr(10).join([f"- {sign}" for sign in warning_signs]) if warning_signs else "- Không phát hiện dấu hiệu cảnh báo rõ ràng"}



5. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC:

- Kiểm tra nguồn: Tìm kiếm thông tin tương tự trên các trang báo uy tín như VnExpress, Tuổi Trẻ, Thanh Niên

- Xác minh thời gian: Kiểm tra xem tin tức có được đăng tải đồng thời trên nhiều nguồn không

- Đánh giá ngôn ngữ: Tránh chia sẻ tin tức có ngôn ngữ cảm xúc thái quá hoặc tạo cảm giác cấp bách

- Lưu ý: Do hệ thống API tạm thời không khả dụng, kết quả phân tích có thể không hoàn toàn chính xác"""
            return fallback_analysis
        
        # For other errors, see what models are available
        try:
            models = genai.list_models()
            print("Available models:")
            for model in models:
                if 'gemini' in model.name.lower():
                    print(f"  - {model.name}")
        except Exception as list_error:
            print(f"Could not list models: {list_error}")
        return f"Lỗi phân tích Gemini: {e}"

def extract_gemini_percentage(gemini_analysis):
    """Extract percentage confidence from Gemini analysis"""
    try:
        gemini_lower = gemini_analysis.lower()
        
        # Look for the confidence percentage pattern
        import re
        
        # Pattern to match "THẬT: X% / GIẢ: Y%" format
        percentage_pattern = r'độ tin cậy.*?thật.*?(\d+)%.*?giả.*?(\d+)%'
        match = re.search(percentage_pattern, gemini_lower)
        
        if match:
            real_percent = int(match.group(1))
            fake_percent = int(match.group(2))
            
            # Normalize to ensure they add up to 100
            total = real_percent + fake_percent
            if total > 0:
                real_percent = real_percent / total
                fake_percent = fake_percent / total
            else:
                real_percent = 0.5
                fake_percent = 0.5
                
            print(f"Extracted Gemini percentages: {real_percent:.1%} real, {fake_percent:.1%} fake")
            return real_percent, fake_percent
        
        # Fallback: try to find individual percentages
        real_match = re.search(r'(\d+)%.*?thật', gemini_lower)
        fake_match = re.search(r'(\d+)%.*?giả', gemini_lower)
        
        if real_match and fake_match:
            real_percent = int(real_match.group(1)) / 100
            fake_percent = int(fake_match.group(1)) / 100
            print(f"Extracted Gemini percentages (fallback): {real_percent:.1%} real, {fake_percent:.1%} fake")
            return real_percent, fake_percent
            
        print("Could not extract Gemini percentages, using conclusion analysis")
        return None, None
        
    except Exception as e:
        print(f"Error extracting Gemini percentages: {e}")
        return None, None
        
        # If we hit the API limit, provide a basic analysis
        if "429" in str(e) or "quota" in str(e).lower():
            print("Gemini API quota exceeded, providing enhanced fallback analysis...")
            
            # Enhanced analysis based on content patterns
            fake_patterns = ['giả', 'sai', 'không đúng', 'bịa đặt', 'lừa đảo', 'fake news', 'tin đồn']
            real_patterns = ['chính thức', 'xác nhận', 'chính xác', 'đúng', 'verified', 'chính phủ', 'bộ y tế']
            
            news_lower = news_text.lower()
            fake_score = sum(1 for pattern in fake_patterns if pattern in news_lower)
            real_score = sum(1 for pattern in real_patterns if pattern in news_lower)
            
            # Adjust prediction based on patterns
            if fake_score > real_score and distilbert_prediction == 'FAKE':
                confidence_boost = "Cao (có từ khóa nghi ngờ)"
            elif real_score > fake_score and distilbert_prediction == 'REAL':
                confidence_boost = "Cao (có từ khóa xác thực)"
            else:
                confidence_boost = "Trung bình"
            
            # Create detailed fallback analysis
            conclusion = 'THẬT' if distilbert_prediction == 'REAL' else 'GIẢ' if distilbert_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH'
            
            # Enhanced analysis based on content patterns
            suspicious_patterns = []
            if fake_score > 0:
                suspicious_patterns.append(f"Tìm thấy {fake_score} từ khóa nghi ngờ")
            if real_score > 0:
                suspicious_patterns.append(f"Tìm thấy {real_score} từ khóa xác thực")
            
            warning_signs = []
            if 'cảnh báo' in news_lower or 'nguy hiểm' in news_lower:
                warning_signs.append("Sử dụng từ ngữ gây sợ hãi")
            if 'ngay lập tức' in news_lower or 'khẩn cấp' in news_lower:
                warning_signs.append("Tạo cảm giác cấp bách không cần thiết")
            if len(news_text) < 100:
                warning_signs.append("Tin tức quá ngắn, thiếu thông tin chi tiết")
            
            fallback_analysis = f"""**1. KẾT LUẬN:** {conclusion}



**2. PHÂN TÍCH CHI TIẾT:**

- **Nội dung:** {'Tin tức có vẻ hợp lý' if distilbert_prediction == 'REAL' else 'Tin tức có nhiều dấu hiệu đáng ngờ' if distilbert_prediction == 'FAKE' else 'Nội dung không rõ ràng'}

- **Nguồn tin:** Google Search không khả dụng (hết quota) - không thể kiểm tra nguồn

- **Ngữ cảnh:** Phân tích từ khóa: {confidence_boost}

- **Ngôn ngữ:** {'Ngôn ngữ trung tính' if fake_score == real_score else 'Có dấu hiệu cảm xúc thái quá' if fake_score > real_score else 'Ngôn ngữ khách quan'}

- **Thời gian:** Không thể xác minh do thiếu thông tin bổ sung



**3. CÁC DẤU HIỆU CẢNH BÁO:** 

{chr(10).join([f"- {sign}" for sign in warning_signs]) if warning_signs else "- Không phát hiện dấu hiệu cảnh báo rõ ràng"}



**4. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC:**

- **Kiểm tra nguồn:** Tìm kiếm thông tin tương tự trên các trang báo uy tín như VnExpress, Tuổi Trẻ, Thanh Niên

- **Xác minh thời gian:** Kiểm tra xem tin tức có được đăng tải đồng thời trên nhiều nguồn không

- **Đánh giá ngôn ngữ:** Tránh chia sẻ tin tức có ngôn ngữ cảm xúc thái quá hoặc tạo cảm giác cấp bách

- **Lưu ý:** Do hệ thống API tạm thời không khả dụng, kết quả phân tích có thể không hoàn toàn chính xác"""
            return fallback_analysis
        
        # For other errors, see what models are available
        try:
            models = genai.list_models()
            print("Available models:")
            for model in models:
                if 'gemini' in model.name.lower():
                    print(f"  - {model.name}")
        except Exception as list_error:
            print(f"Could not list models: {list_error}")
        return f"Lỗi phân tích Gemini: {e}"

def calculate_combined_confidence(distilbert_prediction, distilbert_confidence, source_credibility, popularity_score, gemini_analysis, source_support=0.5):
    """Calculate combined confidence using weighted approach:

    - DistilBERT: 30% weight

    - Gemini AI: 30% weight  

    - Google Search (source credibility + support): 20% weight

    - Other factors: 20% weight

    """
    
    # 1. DISTILBERT SCORE (30% weight)
    if distilbert_prediction == "REAL":
        distilbert_score = distilbert_confidence
    else:
        distilbert_score = 1 - distilbert_confidence
    
    print(f"DistilBERT Score: {distilbert_score:.3f} (30% weight)")
    
    # 2. GEMINI AI SCORE (30% weight)
    gemini_lower = gemini_analysis.lower()
    
    # Try to extract percentage from Gemini analysis first
    gemini_real_percent, gemini_fake_percent = extract_gemini_percentage(gemini_analysis)
    
    if gemini_real_percent is not None and gemini_fake_percent is not None:
        # Use the extracted percentage directly
        gemini_score = gemini_real_percent
        print(f"Gemini Score (from percentage): {gemini_score:.3f} (30% weight) - {gemini_real_percent:.1%} real, {gemini_fake_percent:.1%} fake")
    else:
        # Fallback to conclusion analysis
        conclusion_score = 0.5  # Default neutral
        if "kết luận: giả" in gemini_lower or "kết luận: fake" in gemini_lower:
            conclusion_score = 0.1  # Very low for FAKE
            print("Gemini Conclusion: FAKE")
        elif "kết luận: thật" in gemini_lower or "kết luận: real" in gemini_lower:
            conclusion_score = 0.9  # Very high for REAL
            print("Gemini Conclusion: REAL")
        elif "giả" in gemini_lower and "kết luận" in gemini_lower:
            # Check if "giả" appears near "kết luận"
            conclusion_start = gemini_lower.find("kết luận")
            if conclusion_start != -1:
                conclusion_section = gemini_lower[conclusion_start:conclusion_start + 50]
                if "giả" in conclusion_section:
                    conclusion_score = 0.1
                    print("Gemini Conclusion: FAKE (detected in conclusion section)")
                elif "thật" in conclusion_section:
                    conclusion_score = 0.9
                    print("Gemini Conclusion: REAL (detected in conclusion section)")
        
        # Additional analysis indicators
        fake_indicators = ["giả", "fake", "vô lý", "phi thực tế", "absurd", "preposterous", "impossible", 
                          "không thể xảy ra", "không có căn cứ", "tin giả"]
        real_indicators = ["thật", "real", "chính xác", "đúng", "xác nhận", "verified", "đáng tin cậy"]
        
        fake_count = sum(1 for indicator in fake_indicators if indicator in gemini_lower)
        real_count = sum(1 for indicator in real_indicators if indicator in gemini_lower)
        
        # Adjust based on analysis indicators (but conclusion takes priority)
        if fake_count > real_count:
            analysis_adjustment = -0.2
            print(f"Gemini Analysis: {fake_count} fake indicators vs {real_count} real indicators")
        elif real_count > fake_count:
            analysis_adjustment = 0.2
            print(f"Gemini Analysis: {real_count} real indicators vs {fake_count} fake indicators")
        else:
            analysis_adjustment = 0.0
        
        gemini_score = max(0.1, min(0.9, conclusion_score + analysis_adjustment))
        print(f"Gemini Score (from conclusion): {gemini_score:.3f} (30% weight)")
    
    # 3. GOOGLE SEARCH SCORE (20% weight - source credibility + support)
    # Source credibility component (10%)
    credibility_component = source_credibility * 0.5  # Convert to 0-0.5 scale
    
    # Source support component (10%) 
    support_component = source_support * 0.5  # Convert to 0-0.5 scale
    
    google_search_score = credibility_component + support_component + 0.5  # Add base 0.5 for neutral
    
    # If Gemini strongly says FAKE, reduce Google Search score
    if gemini_score < 0.3:  # Gemini says FAKE (low score)
        google_search_score = min(google_search_score, 0.4)  # Cap at 0.4 when Gemini says fake
        print(f"Google Search Score: {google_search_score:.3f} (20% weight) - Credibility: {source_credibility:.2f}, Support: {source_support:.2f} - CAPPED due to Gemini FAKE")
    else:
        print(f"Google Search Score: {google_search_score:.3f} (20% weight) - Credibility: {source_credibility:.2f}, Support: {source_support:.2f}")
    
    # 4. OTHER FACTORS (20% weight - popularity, etc.)
    other_factors_score = popularity_score * 0.4 + 0.6  # Convert popularity to 0.6-1.0 scale
    
    # If Gemini strongly says FAKE, reduce Other Factors score
    if gemini_score < 0.3:  # Gemini says FAKE (low score)
        other_factors_score = min(other_factors_score, 0.5)  # Cap at 0.5 when Gemini says fake
        print(f"Other Factors Score: {other_factors_score:.3f} (20% weight) - Popularity: {popularity_score:.2f} - CAPPED due to Gemini FAKE")
    else:
        print(f"Other Factors Score: {other_factors_score:.3f} (20% weight) - Popularity: {popularity_score:.2f}")
    
    # 5. COMBINE WITH WEIGHTS
    final_confidence = (
        distilbert_score * 0.30 +      # DistilBERT: 30%
        gemini_score * 0.30 +          # Gemini AI: 30%
        google_search_score * 0.20 +   # Google Search: 20%
        other_factors_score * 0.20     # Other factors: 20%
    )
    
    final_confidence = max(0.05, min(0.95, final_confidence))
    
    print(f"Final Weighted Confidence: {final_confidence:.3f}")
    print(f"  - DistilBERT (30%): {distilbert_score:.3f} × 0.30 = {distilbert_score * 0.30:.3f}")
    print(f"  - Gemini (30%): {gemini_score:.3f} × 0.30 = {gemini_score * 0.30:.3f}")
    print(f"  - Google Search (20%): {google_search_score:.3f} × 0.20 = {google_search_score * 0.20:.3f}")
    print(f"  - Other Factors (20%): {other_factors_score:.3f} × 0.20 = {other_factors_score * 0.20:.3f}")
    
    return final_confidence

def analyze_news(news_text):
    """Main analysis function combining all three tools"""
    try:
        if not news_text.strip():
            empty_message = """

<div style="font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333;">



## 📝 **HƯỚNG DẪN SỬ DỤNG**



<div style="background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%); color: white; padding: 20px; border-radius: 10px; margin: 20px 0; text-align: center;">

<h2 style="margin: 0; font-size: 24px;">💡 Vui lòng nhập tin tức</h2>

<p style="margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">Để bắt đầu phân tích</p>

</div>



<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #17a2b8; margin: 10px 0;">

<p><strong>Hướng dẫn:</strong></p>

<ul>

<li>Nhập tin tức tiếng Việt cần kiểm tra vào ô trên</li>

<li>Nhấn nút "Phân tích với AI nâng cao"</li>

<li>Chờ hệ thống phân tích (có thể mất 10-30 giây)</li>

<li>Xem kết quả phân tích chi tiết</li>

</ul>

</div>



</div>

"""
            return gr.update(value=empty_message, visible=True), "**Độ chắc chắn là tin thật:** 0%", "**Độ chắc chắn là tin giả:** 0%", gr.update(visible=False)
        
        print(f"Analyzing: {news_text[:50]}...")
        
        # Step 1: Search Google for related information
        print("1. Running Google Search...")
        search_error = None
        try:
            search_response = google_search(news_text)
            # Handle both old format (list) and new format (dict with error info)
            if isinstance(search_response, dict) and 'error' in search_response:
                search_results = search_response['results']
                search_error = {
                    'type': search_response['error'],
                    'message': search_response['error_message'],
                    'details': search_response['error_details']
                }
                print(f"Google Search error: {search_error['message']}")
            else:
                search_results = search_response
        except Exception as e:
            print(f"Google Search error: {e}")
            search_results = []
            search_error = {
                'type': 'EXCEPTION',
                'message': 'Google Search failed with exception',
                'details': str(e)
            }
        
        # Step 2: Run our trained model
        print("2. Running DistilBERT analysis...")
        try:
            distilbert_prediction, distilbert_confidence, real_score, fake_score = predict_with_distilbert(news_text)
        except Exception as e:
            print(f"DistilBERT analysis error: {e}")
            distilbert_prediction, distilbert_confidence, real_score, fake_score = None, None, None, None
        
        # Step 3: Check the sources we found
        print("3. Analyzing sources and popularity...")
        try:
            source_credibility, popularity_score, credibility_text, found_sources, credible_sources_found = analyze_sources(search_results)
            source_support, support_text = analyze_source_support(news_text, search_results)
        except Exception as e:
            print(f"Source analysis error: {e}")
            source_credibility, popularity_score, credibility_text = 0.5, 0.2, "Lỗi phân tích nguồn"
            found_sources, credible_sources_found = [], []
            source_support, support_text = 0.5, "Lỗi phân tích hỗ trợ nguồn"
        
        # Step 4: Get Gemini AI analysis
        print("4. Running Gemini analysis...")
        try:
            gemini_analysis = analyze_with_gemini(news_text, search_results, distilbert_prediction, distilbert_confidence)
        except Exception as e:
            print(f"Gemini analysis error: {e}")
            gemini_analysis = f"Lỗi phân tích Gemini: {str(e)}"
        
        # Step 5: Combine everything into final result
        print("5. Calculating combined confidence...")
        print(f"   DistilBERT: {distilbert_prediction} ({distilbert_confidence:.3f})")
        print(f"   Source credibility: {source_credibility:.3f}")
        print(f"   Source support: {source_support:.3f}")
        print(f"   Popularity: {popularity_score:.3f}")
        try:
            combined_confidence = calculate_combined_confidence(
                distilbert_prediction, distilbert_confidence, 
                source_credibility, popularity_score, gemini_analysis, source_support
            )
            print(f"   Final combined confidence: {combined_confidence:.3f}")
        except Exception as e:
            print(f"Confidence calculation error: {e}")
            combined_confidence = 0.5  # Default to neutral
        
        # Step 6: Format the final results
        real_confidence = combined_confidence
        fake_confidence = 1 - combined_confidence
        
        # Step 7: Check if result should be added to knowledge base (using only Gemini confidence for RAG)
        gemini_real_confidence, gemini_fake_confidence = extract_gemini_percentage(gemini_analysis)
        gemini_max_confidence = max(gemini_real_confidence, gemini_fake_confidence)
        
        if gemini_max_confidence > CONFIDENCE_THRESHOLD:
            print(f"🚀 High Gemini confidence detected ({gemini_max_confidence:.1%}) - adding to knowledge base for RAG...")
            final_prediction = "REAL" if gemini_real_confidence > gemini_fake_confidence else "FAKE"
            
            # Add to knowledge base
            success = add_to_knowledge_base(
                news_text=news_text,
                prediction=final_prediction,
                confidence=gemini_max_confidence,  # Use Gemini confidence for RAG storage
                search_results=search_results,
                gemini_analysis=gemini_analysis
            )
            
            if success:
                print("✅ Successfully added to knowledge base for future RAG retrieval!")
            else:
                print("⚠️ Failed to add to knowledge base (duplicate or error)")
        
        # Step 8: Enhanced RAG System - Save to Google Drive if confidence is high enough
        print(f"🔍 DEBUG: ENABLE_ENHANCED_RAG = {ENABLE_ENHANCED_RAG}")
        print(f"🔍 DEBUG: gemini_max_confidence = {gemini_max_confidence}")
        print(f"🔍 DEBUG: RAG_CONFIDENCE_THRESHOLD = {RAG_CONFIDENCE_THRESHOLD}")
        print(f"🔍 DEBUG: Should save? {ENABLE_ENHANCED_RAG and gemini_max_confidence > RAG_CONFIDENCE_THRESHOLD}")
        if ENABLE_ENHANCED_RAG and gemini_max_confidence > RAG_CONFIDENCE_THRESHOLD:
            try:
                from rag_news_manager import add_news_to_rag
                
                print(f"🚀 High confidence detected ({gemini_max_confidence:.1%}) - saving to Enhanced RAG system...")
                final_prediction = "REAL" if gemini_real_confidence > gemini_fake_confidence else "FAKE"
                
                rag_success = add_news_to_rag(
                    news_text=news_text,
                    gemini_analysis=gemini_analysis,
                    gemini_confidence=gemini_max_confidence,
                    prediction=final_prediction,
                    search_results=search_results,
                    distilbert_confidence=distilbert_confidence
                )
                
                if rag_success:
                    print("✅ Successfully saved to Enhanced RAG system (Google Drive)!")
                else:
                    print("⚠️ Failed to save to Enhanced RAG system (duplicate or error)")
                    
            except Exception as e:
                print(f"⚠️ Enhanced RAG system error: {e}")
    
        # Build the detailed report with better formatting
        # Use combined_confidence to determine the final classification (not just DistilBERT)
        final_prediction = "REAL" if combined_confidence > 0.5 else "FAKE" if combined_confidence < 0.5 else "UNCERTAIN"
        prediction_emoji = "✅" if final_prediction == "REAL" else "❌" if final_prediction == "FAKE" else "❓"
        confidence_level = "Cao" if combined_confidence > 0.7 else "Trung bình" if combined_confidence > 0.4 else "Thấp"
        confidence_emoji = "🟢" if combined_confidence > 0.7 else "🟡" if combined_confidence > 0.4 else "🔴"
        
        # Convert technical metrics to user-friendly Vietnamese
        source_quality = "Tốt" if source_credibility > 0.7 else "Trung bình" if source_credibility > 0.4 else "Kém"
        source_count_text = f"{len(search_results)} nguồn tin" if len(search_results) > 0 else "Không tìm thấy nguồn"
        
        # Create source list display
        sources_display = ""
        if found_sources:
            sources_display = "<br>".join([f"• {source}" for source in found_sources[:5]])  # Show max 5 sources
            if len(found_sources) > 5:
                sources_display += f"<br>• ... và {len(found_sources) - 5} nguồn khác"
        elif len(search_results) == 0:
            sources_display = "⚠️ Google Search không khả dụng do hết quota"
        
        # Show credible sources found
        credible_display = ""
        if credible_sources_found:
            credible_display = f"<br><strong>Nguồn uy tín:</strong><br>" + "<br>".join([f"✅ {source}" for source in credible_sources_found])
        
        # Simplify credibility text
        if search_error:
            if search_error['type'] == 'QUOTA_EXCEEDED':
                credibility_summary = f"⚠️ Google Search hết quota - chỉ dùng phân tích nội dung"
                source_count_text = "Không có (API hết quota)"
            elif search_error['type'] == 'API_KEY_INVALID':
                credibility_summary = f"❌ Google Search API key không hợp lệ"
                source_count_text = "Không có (API key lỗi)"
            else:
                credibility_summary = f"⚠️ Google Search lỗi - chỉ dùng phân tích nội dung"
                source_count_text = "Không có (lỗi API)"
        elif "High credibility" in credibility_text:
            credibility_summary = f"✅ Nguồn tin đáng tin cậy"
        elif "Medium credibility" in credibility_text:
            credibility_summary = f"⚠️ Nguồn tin trung bình"
        else:
            credibility_summary = f"❌ Nguồn tin kém tin cậy"
        
        # Simplify support text
        if "strongly support" in support_text.lower():
            support_summary = "✅ Các nguồn ủng hộ tin tức này"
        elif "contradict" in support_text.lower():
            support_summary = "❌ Các nguồn phản bác tin tức này"
        else:
            support_summary = "⚠️ Các nguồn có ý kiến trái chiều"
        
        detailed_analysis = f"""

<div style="font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333;">



## 🔍 **KẾT QUẢ PHÂN TÍCH TIN TỨC**



<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; margin: 20px 0; text-align: center;">

<h2 style="margin: 0; font-size: 24px;">{prediction_emoji} {'TIN THẬT' if final_prediction == 'REAL' else 'TIN GIẢ' if final_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH'}</h2>

<p style="margin: 10px 0 0 0; font-size: 18px; opacity: 0.9;">{confidence_emoji} Độ tin cậy: {confidence_level} ({combined_confidence:.0%})</p>

</div>



### 🤖 **Phân tích bằng AI**

<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #007bff; margin: 10px 0;">

<p><strong>Kết quả:</strong> {prediction_emoji} {'Tin tức này có vẻ THẬT' if final_prediction == 'REAL' else 'Tin tức này có vẻ GIẢ' if final_prediction == 'FAKE' else 'Không thể xác định'}</p>

<p><strong>Độ chắc chắn:</strong> {f"{distilbert_confidence:.0%}" if distilbert_confidence else 'Không có'} - {'Rất cao' if distilbert_confidence and distilbert_confidence > 0.8 else 'Cao' if distilbert_confidence and distilbert_confidence > 0.6 else 'Trung bình' if distilbert_confidence and distilbert_confidence > 0.4 else 'Thấp'}</p>

</div>



### 🌐 **Kiểm tra nguồn tin**

<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #28a745; margin: 10px 0;">

<p><strong>Tìm thấy:</strong> {source_count_text}</p>

<p><strong>Chất lượng nguồn:</strong> {source_quality} ({source_credibility:.0%})</p>

<p><strong>Đánh giá:</strong> {credibility_summary}</p>

<p><strong>Hỗ trợ:</strong> {support_summary}</p>

{sources_display and f'<p><strong>Nguồn tìm thấy:</strong><br>{sources_display}</p>' or ''}

{credible_display}

</div>



{search_error and f'''

### ⚠️ **Cảnh báo Google Search**

<div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107; margin: 10px 0;">

<p><strong>Lỗi:</strong> {search_error["message"]}</p>

<p><strong>Chi tiết:</strong> {search_error["details"]}</p>

<p><strong>Ảnh hưởng:</strong> Hệ thống đang sử dụng phân tích nội dung thay vì tìm kiếm Google. Kết quả có thể kém chính xác hơn.</p>

</div>

''' or ''}



### 🧠 **Phân tích thông minh**

<div style="background: #f8f9fa; padding: 20px; border-radius: 10px; border-left: 4px solid #ffc107; margin: 15px 0; font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6;">

<div style="white-space: pre-line; color: #333;">

{gemini_analysis}

</div>

</div>



### 📊 **KẾT LUẬN CUỐI CÙNG**

<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 15px; border-radius: 8px; margin: 20px 0;">

<p style="margin: 0; font-size: 16px;"><strong>Tin tức này có khả năng {'THẬT' if final_prediction == 'REAL' else 'GIẢ' if final_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH'} với độ tin cậy {max(real_confidence, fake_confidence):.0%}</strong></p>

<p style="margin: 5px 0 0 0; font-size: 14px; opacity: 0.9;">Dựa trên phân tích AI, kiểm tra nguồn tin và đánh giá thông minh</p>

</div>



</div>

"""
    
        return gr.update(value=detailed_analysis, visible=True), f"**Độ chắc chắn là tin thật:** {real_confidence:.1%}", f"**Độ chắc chắn là tin giả:** {fake_confidence:.1%}", gr.update(visible=True)
    
    except Exception as e:
        error_message = f"""

<div style="font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333;">



## ❌ **LỖI PHÂN TÍCH**



<div style="background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); color: white; padding: 20px; border-radius: 10px; margin: 20px 0; text-align: center;">

<h2 style="margin: 0; font-size: 24px;">⚠️ Có lỗi xảy ra</h2>

<p style="margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">Vui lòng thử lại sau</p>

</div>



<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #dc3545; margin: 10px 0;">

<p><strong>Chi tiết lỗi:</strong> {str(e)}</p>

<p><strong>Gợi ý:</strong> Kiểm tra kết nối internet và thử lại</p>

</div>



</div>

"""
        print(f"Analysis error: {e}")
        return gr.update(value=error_message, visible=True), "**Độ chắc chắn là tin thật:** 0%", "**Độ chắc chắn là tin giả:** 0%", gr.update(visible=True)

# --- GRADIO INTERFACE ---
def create_interface():
    with gr.Blocks(title="Vietnamese Fake News Detection System", theme=gr.themes.Soft()) as interface:
        gr.Markdown("""

        <div style="text-align: center; padding: 20px;">

        <h1 style="color: #2c3e50; margin-bottom: 10px;">🔍 Vietnamese Fake News Detection System</h1>

        <p style="color: #7f8c8d; font-size: 16px; margin-bottom: 30px;">Powered by Google Search + Gemini AI + DistilBERT</p>

        

        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 15px; margin: 20px 0;">

        <h3 style="margin: 0 0 15px 0;">🛡️ Hệ thống phát hiện tin giả tiếng Việt</h3>

        <div style="display: flex; justify-content: space-around; flex-wrap: wrap; gap: 15px;">

        <div style="text-align: center;">

        <div style="font-size: 24px; margin-bottom: 5px;">🌐</div>

        <strong>Google Search</strong><br>

        <small>Tìm kiếm thông tin thực tế</small>

        </div>

        <div style="text-align: center;">

        <div style="font-size: 24px; margin-bottom: 5px;">🧠</div>

        <strong>Gemini AI</strong><br>

        <small>Phân tích thông minh</small>

        </div>

        <div style="text-align: center;">

        <div style="font-size: 24px; margin-bottom: 5px;">🤖</div>

        <strong>DistilBERT</strong><br>

        <small>AI chuyên tiếng Việt</small>

        </div>

        </div>

        </div>

        

        <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; border-left: 4px solid #17a2b8; margin: 20px 0;">

        <p style="margin: 0; color: #495057;"><strong>💡 Lưu ý:</strong> Kết quả có thể thay đổi nhẹ giữa các lần phân tích do tính chất AI của Gemini, nhưng độ chính xác tổng thể vẫn được đảm bảo.</p>

        </div>

        

        <div style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); padding: 15px; border-radius: 10px; margin: 20px 0;">

        <h4 style="margin: 0 0 10px 0; color: #333;">🧠 Hệ thống RAG với Cơ sở Tri thức Tự động</h4>

        <p style="margin: 0; color: #555; font-size: 14px;">Khi độ tin cậy > 95%, hệ thống sẽ tự động lưu kết quả vào cơ sở tri thức để sử dụng cho các phân tích tương lai.</p>

        </div>

        </div>

        """)
        
        with gr.Row():
            with gr.Column(scale=2):
                gr.Markdown("### 📝 Nhập tin tức cần kiểm tra")
                news_input = gr.Textbox(
                    placeholder="Nhập tin tức tiếng Việt cần kiểm tra...",
                    lines=4,
                    show_label=False
                )
                
                analyze_btn = gr.Button("🔍 Phân tích với AI nâng cao", variant="primary", size="lg")
            
            with gr.Column(scale=1, visible=False) as results_column:
                gr.Markdown("### 📊 Kết quả phân tích")
                real_confidence = gr.Markdown("**Độ chắc chắn là tin thật:** 0%")
                fake_confidence = gr.Markdown("**Độ chắc chắn là tin giả:** 0%")
        
        detailed_analysis = gr.Markdown("### 📋 Phân tích chi tiết sẽ hiển thị ở đây...", visible=False)
        
        # Event handlers
        analyze_btn.click(
            fn=analyze_news,
            inputs=[news_input],
            outputs=[detailed_analysis, real_confidence, fake_confidence, results_column]
        )
        

    return interface

def test_google_search():
    """Test Google Search API functionality"""
    print("Testing Google Search API...")
    print("=" * 50)
    
    # Test queries
    test_queries = [
        "Argentina World Cup 2022",
        "Vietnam COVID-19 news",
        "Tin tức Việt Nam"
    ]
    
    results_found = 0
    
    for i, query in enumerate(test_queries, 1):
        print(f"\nTest {i}: '{query}'")
        print("-" * 30)
        
        try:
            results = google_search(query)
            print(f"Results: {len(results)} found")
            
            if results:
                results_found += 1
                print(f"First result: {results[0]['title'][:50]}...")
                print(f"   Link: {results[0]['link']}")
            else:
                print("No results found")
                
        except Exception as e:
            print(f"Error: {e}")
    
    print(f"\nTest Summary: {results_found}/{len(test_queries)} tests passed")
    
    if results_found == 0:
        print("\nGoogle Search is not working!")
        print("Possible solutions:")
        print("   1. Check API quota in Google Cloud Console")
        print("   2. Verify API keys are correct")
        print("   3. Ensure Custom Search API is enabled")
        print("   4. Check Search Engine ID is valid")
    elif results_found < len(test_queries):
        print("\nGoogle Search partially working")
        print("Some queries work, others don't - check query formatting")
    else:
        print("\nGoogle Search is working perfectly!")
    
    return results_found > 0

def test_complete_system():
    """Test the complete fake news detection system"""
    print("Testing Complete Vietnamese Fake News Detection System")
    print("=" * 60)
    
    # Test cases
    test_cases = [
        "Argentina vô địch World Cup 2022",
        "Hôm nay trời mưa ở Hà Nội",
        "COVID-19 đã được chữa khỏi hoàn toàn"
    ]
    
    for i, test_text in enumerate(test_cases, 1):
        print(f"\nTest Case {i}: '{test_text}'")
        print("-" * 40)
        
        try:
            result = analyze_news(test_text)
            print("Analysis completed successfully")
            print(f"Result type: {type(result)}")
        except Exception as e:
            print(f"Analysis failed: {e}")

# --- LAUNCH APP ---
if __name__ == "__main__":
    print("Starting Vietnamese Fake News Detection System...")
    print("Tools integrated: Google Search + Gemini AI + DistilBERT")
    
    # Uncomment the line below to run tests first
    # test_google_search()
    
    interface = create_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,  # Standard port for Hugging Face Spaces
        share=False,  # Not needed for Hugging Face Spaces
        show_error=True
    )