File size: 118,463 Bytes
b66c232
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
 
b66c232
 
 
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dab5364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
2c996b2
 
 
 
 
 
dab5364
2c996b2
 
b66c232
2c996b2
 
 
 
 
 
 
 
b66c232
 
 
 
2c996b2
b66c232
2c996b2
b66c232
2c996b2
b66c232
 
 
 
2c996b2
 
 
 
b66c232
dab5364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
2c996b2
 
dab5364
2c996b2
 
 
 
 
dab5364
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
 
2c996b2
 
b66c232
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
 
 
2c996b2
b66c232
201583f
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201583f
 
b66c232
 
 
 
 
 
201583f
 
b66c232
 
 
 
 
 
2c996b2
 
b66c232
 
 
 
 
 
 
2c996b2
 
201583f
 
2c996b2
201583f
 
 
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
201583f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
201583f
 
 
 
 
 
 
 
 
2c996b2
 
201583f
 
2c996b2
 
 
 
 
 
 
 
 
 
201583f
 
2c996b2
 
201583f
2c996b2
201583f
 
 
2c996b2
201583f
 
 
 
 
 
 
2c996b2
201583f
 
 
 
 
2c996b2
 
201583f
 
2c996b2
201583f
 
 
2c996b2
201583f
 
 
 
2c996b2
201583f
 
 
 
 
2c996b2
 
 
 
201583f
2c996b2
201583f
2c996b2
201583f
2c996b2
 
 
201583f
2c996b2
201583f
2c996b2
 
201583f
 
 
2c996b2
 
 
201583f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
201583f
b66c232
 
 
 
 
201583f
 
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Kütüphaneler eklenmesi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datasets import load_dataset\n",
    "import pandas as pd \n",
    "from pymongo import MongoClient\n",
    "from transformers import BertTokenizer, BertForMaskedLM, DPRContextEncoderTokenizer,DPRContextEncoder;\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Parquet dosyalarının dataframe olarak yüklenmesi(okuma yapabilmek için)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Parquet dosyalarını DataFrame olarak yükleyin\n",
    "train_df1 = pd.read_parquet('C:\\\\gitProjects\\\\yeni\\\\wikipedia-tr\\\\data\\\\train-00000-of-00002-ed6b025df7a1f653.parquet')\n",
    "train_df2 = pd.read_parquet('C:\\\\gitProjects\\\\yeni\\\\wikipedia-tr\\\\data\\\\train-00001-of-00002-0aa63953f8b51c17.parquet')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# İki DataFrame'i birleştirin\n",
    "merged_train = pd.concat([train_df1, train_df2], ignore_index=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Örneğin %80 train, %20 test olarak ayırın\n",
    "train_data = merged_train.sample(frac=0.8, random_state=42)\n",
    "test_data = merged_train.drop(train_data.index)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Dosya yolları\n",
    "train_dir = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\train_Egitim'\n",
    "test_dir = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\test_Egitim'\n",
    "train_file_path = os.path.join(train_dir, 'merged_train.parquet')\n",
    "test_file_path = os.path.join(test_dir, 'merged_test.parquet')\n",
    "\n",
    "# Dizinlerin var olup olmadığını kontrol etme, gerekirse oluşturma\n",
    "os.makedirs(train_dir, exist_ok=True)\n",
    "os.makedirs(test_dir, exist_ok=True)\n",
    "\n",
    "# Veriyi .parquet formatında kaydetme\n",
    "train_data.to_parquet(train_file_path)\n",
    "test_data.to_parquet(test_file_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dataframe deki bilgileri görme "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             id                                                url  \\\n",
      "515773  3525037  https://tr.wikipedia.org/wiki/P%C5%9F%C4%B1qo%...   \n",
      "517811  3532700      https://tr.wikipedia.org/wiki/Craterolophinae   \n",
      "436350  3203545           https://tr.wikipedia.org/wiki/Notocrabro   \n",
      "223281  1765445    https://tr.wikipedia.org/wiki/Ibrahim%20Sissoko   \n",
      "100272   575462        https://tr.wikipedia.org/wiki/Salah%20Cedid   \n",
      "\n",
      "                  title                                               text  \n",
      "515773    Pşıqo Ahecaqo  Pşıqo Ahecaqo (), Çerkes siyasetçi, askeri kom...  \n",
      "517811  Craterolophinae  Craterolophinae, Depastridae familyasına bağlı...  \n",
      "436350       Notocrabro  Notocrabro Crabronina oymağına bağlı bir cinst...  \n",
      "223281  Ibrahim Sissoko  İbrahim Sissoko (d. 30 Kasım 1991), Fildişi Sa...  \n",
      "100272      Salah Cedid  Salah Cedid (1926-1993) (Arapça: صلاح جديد) Su...  \n",
      "    id                                             url        title  \\\n",
      "5   35       https://tr.wikipedia.org/wiki/Karl%20Marx    Karl Marx   \n",
      "13  48         https://tr.wikipedia.org/wiki/Ruhi%20Su      Ruhi Su   \n",
      "15  53        https://tr.wikipedia.org/wiki/Bilgisayar   Bilgisayar   \n",
      "18  59          https://tr.wikipedia.org/wiki/Edebiyat     Edebiyat   \n",
      "19  64  https://tr.wikipedia.org/wiki/M%C3%BChendislik  Mühendislik   \n",
      "\n",
      "                                                 text  \n",
      "5   Karl Marx (; 5 Mayıs 1818, Trier – 14 Mart 188...  \n",
      "13  Mehmet Ruhi Su (1 Ocak 1912, Van - 20 Eylül 19...  \n",
      "15  Bilgisayar, aritmetik veya mantıksal işlem diz...  \n",
      "18  Edebiyat, yazın veya literatür; olay, düşünce,...  \n",
      "19  Mühendis, insanların her türlü ihtiyacını karş...  \n"
     ]
    }
   ],
   "source": [
    "print(train_data.head())\n",
    "print(test_data.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MongoDb'ye bağlama ve bilgi çekme "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Veriler başarıyla Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'EgitimDatabase'), 'train') MongoDb koleksiyonuna indirildi.\n",
      " Veriler başarıyla Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'EgitimDatabase'), 'test') MongoDb koleksiyonuna indirildi.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from pymongo import MongoClient\n",
    "\n",
    "def get_mongodb(database_name='EgitimDatabase', train_collection_name='train', test_collection_name='test', host='localhost', port=27017):\n",
    "    \"\"\"\n",
    "    MongoDB connection and collection selection for train and test collections.\n",
    "    \"\"\"\n",
    "    client = MongoClient(f'mongodb://{host}:{port}/')\n",
    "    \n",
    "    # Veritabanını seçin\n",
    "    db = client[database_name]\n",
    "    \n",
    "    # Train ve test koleksiyonlarını seçin\n",
    "    train_collection = db[train_collection_name]\n",
    "    test_collection = db[test_collection_name]\n",
    "    \n",
    "    return train_collection, test_collection\n",
    "\n",
    "# Function to load dataset into MongoDB\n",
    "def dataset_read(train_file_path,test_file_path):\n",
    "    data_train = pd.read_parquet(train_file_path, columns=['id', 'url', 'title', 'text'])\n",
    "    data_test = pd.read_parquet(test_file_path, columns=['id', 'url', 'title', 'text'])\n",
    "    data_dict_train = data_train.to_dict(\"records\")\n",
    "    data_dict_test = data_test.to_dict(\"records\")\n",
    "\n",
    "\n",
    "\n",
    "    # Get the MongoDB collections\n",
    "    train_collection, test_collection = get_mongodb(database_name='EgitimDatabase')\n",
    "\n",
    " \n",
    "\n",
    "    # Insert data into MongoDB\n",
    "    train_collection.insert_many(data_dict_train)\n",
    "    test_collection.insert_many(data_dict_test)\n",
    "\n",
    "\n",
    "    print(f\" Veriler başarıyla {train_collection} MongoDb koleksiyonuna indirildi.\")\n",
    "    print(f\" Veriler başarıyla {test_collection} MongoDb koleksiyonuna indirildi.\")\n",
    "    return train_collection,test_collection\n",
    "\n",
    "# Train ve test datasetlerini MongoDB'ye yüklemek için fonksiyonu çağır\n",
    "train_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\train_Egitim\\\\merged_train.parquet'\n",
    "test_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\test_Egitim\\\\merged_test.parquet'\n",
    "\n",
    "train_collection, test_collection = dataset_read(train_file_path, test_file_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from pymongo import MongoClient,errors\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sentence_transformers import SentenceTransformer\n",
    "\n",
    "# MongoDB bağlantı ve koleksiyon seçimi için fonksiyon\n",
    "def get_mongodb(database_name='EgitimDatabase', train_collection_name='train', test_collection_name='test', host='localhost', port=27017):\n",
    "    client = MongoClient(f'mongodb://{host}:{port}/')\n",
    "    db = client[database_name]\n",
    "    train_collection = db[train_collection_name]\n",
    "    test_collection = db[test_collection_name]\n",
    "    return train_collection, test_collection\n",
    "\n",
    "# Dataset'i MongoDB'ye yükleme fonksiyonu\n",
    "def dataset_read(train_file_path, test_file_path):\n",
    "    try:\n",
    "        # MongoDB koleksiyonlarını al\n",
    "        train_collection, test_collection = get_mongodb()\n",
    "\n",
    "        # Eğer koleksiyonlar zaten doluysa, veri yüklemesi yapma\n",
    "        if train_collection.estimated_document_count() > 0 or test_collection.estimated_document_count() > 0:\n",
    "            print(\"Veriler zaten yüklendi, işlem yapılmadı.\")\n",
    "            return train_collection, test_collection\n",
    "\n",
    "        # Datasetleri oku\n",
    "        data_train = pd.read_parquet(train_file_path, columns=['id', 'url', 'title', 'text'])\n",
    "        data_test = pd.read_parquet(test_file_path, columns=['id', 'url', 'title', 'text'])\n",
    "\n",
    "        # Verileri MongoDB'ye yükle\n",
    "        train_collection.insert_many(data_train.to_dict(\"records\"))\n",
    "        test_collection.insert_many(data_test.to_dict(\"records\"))\n",
    "\n",
    "        print(f\"Veriler başarıyla {train_collection.name} koleksiyonuna yüklendi.\")\n",
    "        print(f\"Veriler başarıyla {test_collection.name} koleksiyonuna yüklendi.\")\n",
    "    \n",
    "    except errors.PyMongoError as e:\n",
    "        print(f\"Veri yükleme sırasında hata oluştu: {e}\")\n",
    "\n",
    "    return train_collection, test_collection\n",
    "\n",
    "\n",
    "\n",
    "# Database sınıfı: Veritabanı bağlantıları ve verileri çekme işlevleri\n",
    "class Database:\n",
    "    @staticmethod\n",
    "    def get_mongodb():\n",
    "        return get_mongodb()\n",
    "\n",
    "    @staticmethod\n",
    "    def get_titles_and_texts():\n",
    "        # MongoDB bağlantısı ve koleksiyonları al\n",
    "        train_collection, _ = Database.get_mongodb()\n",
    "\n",
    "        # Sorgu: Hem \"title\" hem de \"text\" alanı mevcut olan belgeler\n",
    "        query = {\"title\": {\"$exists\": True}, \"text\": {\"$exists\": True}}\n",
    "\n",
    "        # Belirtilen alanları seçiyoruz: \"title\", \"text\"\n",
    "        cursor = train_collection.find(query, {\"title\": 1, \"text\": 1, \"_id\": 0})\n",
    "\n",
    "        # Başlık ve metinleri doğru bir şekilde birleştiriyoruz\n",
    "        documents = [{\"title\": doc['title'], \"text\": doc['text']} for doc in cursor]\n",
    "        document_count = len(documents)\n",
    "        return documents, document_count\n",
    "\n",
    "# Train ve test datasetlerini MongoDB'ye yüklemek için fonksiyonu çağır\n",
    "train_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\train_Egitim\\\\merged_train.parquet'\n",
    "test_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\test_Egitim\\\\merged_test.parquet'\n",
    "\n",
    "train_collection, test_collection = dataset_read(train_file_path, test_file_path)\n",
    "\n",
    "# Veritabanından başlıklar ve metinler alınır\n",
    "documents, document_count = Database.get_titles_and_texts()\n",
    "\n",
    "# Sonuçların belirlenmesi\n",
    "print(f\"Başlık ve metin çiftleri: {documents}\")\n",
    "print(f\"Toplam çift sayısı: {document_count}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MongoDb üzerinden title ve text verilerinin çekilmesi "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"@staticmethod\n",
    "    def get_input_titles():\n",
    "        collection = Database.get_mongodb(collection_name='train')\n",
    "        query = {\"title\": {\"$exists\": True}}\n",
    "        cursor = collection.find(query, {\"title\": 1, \"_id\": 0})\n",
    "        title_from_db = [doc['title'] for doc in cursor]\n",
    "\n",
    "        return title_from_db\"\"\"\n",
    "\n",
    "\"\"\"@staticmethod\n",
    "    def get_input_texts():\n",
    "        collection = Database.get_mongodb(collection_name='train')\n",
    "        query = {\"texts\": {\"$exists\": True}}\n",
    "        cursor = collection.find(query, {\"texts\": 1, \"_id\": 0})\n",
    "        texts_from_db = [doc['texts'] for doc in cursor]\n",
    "        return texts_from_db\"\"\"\n",
    "    \n",
    "    #bin tane veri çekerek csv dosyası olarak kaydetme \n",
    "   \n",
    "    \n",
    "\"\"\"@staticmethod\n",
    "    def get_titles_and_texts(batch_size=1000):\n",
    "\n",
    "        \n",
    "        titles = Database.get_input_titles(batch_size=batch_size)\n",
    "        texts = Database.get_input_texts(batch_size=batch_size )\n",
    "        \n",
    "\n",
    "\n",
    "    def test_queries():\n",
    "\n",
    "        collection = Database.get_mongodb(collection_name='train')\n",
    "        # Başlık sorgusu\n",
    "        titles_cursor = collection.find({\"title\": {\"$exists\": True}}, {\"title\": 1, \"_id\": 0})\n",
    "        titles = [doc['title'] for doc in titles_cursor]\n",
    "        \n",
    "\n",
    "        # Metin sorgusu\n",
    "        texts_cursor = collection.find({\"text\": {\"$exists\": True}}, {\"text\": 1, \"_id\": 0})\n",
    "        texts = [doc['text'] for doc in texts_cursor]\n",
    "        \n",
    "        # Başlık ve metinlerin eşleşmesini sağlamak için zip kullanarak birleştiriyoruz\n",
    "        documents = [{\"title\": title, \"text\": text} for title, text in zip(titles, texts)]\n",
    "        document_count = len(documents)\n",
    "        return documents, document_count\n",
    "\n",
    "Database.test_queries()\n",
    "\n",
    "# Veritabanından başlıklar ve metinler alınır\n",
    "documents, document_count = Database.get_titles_and_texts(batch_size=1000)\n",
    "\n",
    "# Sonuçların belirlenmesi\n",
    "print(f\"Başlık ve metin çiftleri: {documents}\")\n",
    "print(f\"Toplam çift sayısı: {document_count}\")\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Output'u vereceğimiz title ve textin kodu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    **Pşıqo Ahecaqo** Pşıqo Ahecaqo (), Çerkes siy...\n",
      "1    **Craterolophinae** Craterolophinae, Depastrid...\n",
      "2    **Notocrabro** Notocrabro Crabronina oymağına ...\n",
      "3    **Ibrahim Sissoko** İbrahim Sissoko (d. 30 Kas...\n",
      "4    **Salah Cedid** Salah Cedid (1926-1993) (Arapç...\n",
      "Name: combined, dtype: object\n",
      "Veriler combined_output.csv dosyasına başarıyla kaydedildi.\n"
     ]
    }
   ],
   "source": [
    "from pymongo import MongoClient\n",
    "import pandas as pd\n",
    "from tqdm.auto import tqdm, trange\n",
    "\n",
    "# Database bağlantıları ve verileri çekme işlevleri\n",
    "class Database:\n",
    "    @staticmethod\n",
    "    def get_mongodb(database_name='EgitimDatabase', train_collection_name='train', test_collection_name='test', host='localhost', port=27017):\n",
    "        client = MongoClient(f'mongodb://{host}:{port}/')\n",
    "        db = client[database_name]\n",
    "        train_collection = db[train_collection_name]\n",
    "        test_collection = db[test_collection_name]\n",
    "        return train_collection, test_collection\n",
    "\n",
    "    def export_to_csv(batch_size=1000, output_file='combined_output.csv'):\n",
    "        train_collection, _ = Database.get_mongodb()\n",
    "        cursor = train_collection.find({}, {\"title\": 1, \"text\": 1, \"_id\": 0})\n",
    "        cursor = cursor.batch_size(batch_size)  # Fix: Call batch_size on the cursor object\n",
    "\n",
    "        # Verileri DataFrame'e dönüştürme\n",
    "        df= pd.DataFrame(list(cursor))\n",
    "        \n",
    "        # title ve text sütunlarını birleştirme\n",
    "        df['combined'] = df.apply(lambda row: f'**{row[\"title\"]}** {row[\"text\"]}', axis=1)\n",
    "        \n",
    "        #title,text and combined sütunlarını ayrı ayrı tutma\n",
    "        #df2['title_only'] = df2['title']\n",
    "        #df2['text_only'] = df2['text']\n",
    "        #df['combined']= output_file\n",
    "\n",
    "        # Sonuçları kontrol etme\n",
    "        combined_text= df['combined'] \n",
    "          # Print the combined column directly\n",
    "        \n",
    "        print(combined_text.head())\n",
    "\n",
    "        # Birleşmiş verileri CSV'ye kaydetme\n",
    "        \n",
    "        df.to_csv(output_file, index=False)\n",
    "        \n",
    "        print(f\"Veriler combined_output.csv dosyasına başarıyla kaydedildi.\")\n",
    "        \n",
    "\n",
    "# CSV dosyasını okuma ve birleştirme işlemi\n",
    "Database.export_to_csv()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "TF-IDF HESAPLAMA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tokens: ['[CLS]', 'Biy', '##ografi', 'İsim', 'P', '##şı', '##q', '##o', 'ismi', 'Ah', '##ec', '##a', '##q', '##o', 'soy', 'ismi', '##dir', '.', 'Çerkes', '##lerin', '\"', '-', 'q', '##o', '\"', 'son', '##eki', 'ile', 'biten', 'hem', 'soya', '##d', '##ları', 'hem', 'de', 'lak', '##ap', '##ları', 'vardı', '.', 'Bu', 'ek', 'Türkçe', 'ad', '##lardaki', '\"', '-', 'oğlu', '\"', 'eki', '##yle', 'eş', 'anlamlı', '##dır', '.', 'P', '##şı', '##q', '##o', 'Türkçe', '\"', 'Beyoğlu', '\"', 'anlamına', 'gelen', 'bir', 'lak', '##ap', '##tır', '.', 'Erken', 'dönem', 'Çerkes', '##ler', 'tarihleri', '##ni', 'yazma', '##dıkları', 've', 'tüm', 'bilgiler', 'Rus', 'kaynaklarından', 'geldiği', 'için', 'Ah', '##ec', '##a', '##q', '##o', 'hakkında', 'pek', 'bir', 'şey', 'kayded', '##ilme', '##di', '.', '177', '##7', \"'\", 'de', 'Çerkes', '##ya', \"'\", 'nın', 'B', '##je', '##duğ', 'bölgesinde', 'doğdu', '.', 'Asker', '##î', 'eğitim', 'ile', 'büyüt', '##üldü', '.', 'Rus', '-', 'Çerkes', 'Savaşı', '##na', 'Katılım', '##ı', 'Birkaç', 'kaynak', ',', 'Ah', '##ec', '##a', '##q', '##o', \"'\", 'nun', 'tüm', 'Çerkes', '##ya', \"'\", 'da', 'saygı', 'duyulan', 'bir', 'kişi', 'olduğunu', 'belirtir', '.', 'En', 'az', '6', '.', '000', 'at', '##lı', '##dan', 'oluşan', 'kalıcı', 'bir', 'ordusu', 'vardı', 've', 'çatışmalar', 'sırasında', 'müfre', '##ze', '##si', '12', '.', '000', 'at', '##lı', '##ya', 'ulaşıyor', '##du', '.', 'Rus', 'birlikleri', '##ne', 'karşı', 'kazandığı', 'zafer', '##lerle', 'ünlü', '##y', '##dü', '.', 'Askeri', 'becerisi', '##nin', 'yanı', 'sıra', 'yetenekli', 'bir', 'devlet', 'adamı', '##ydı', '.', 'Ölüm', '18', '##37', 'yılında', 'Rus', 'tarafına', 'geçti', 've', 'bir', 'yıl', 'sonra', 'hastalık', '##tan', 'öldü', '.', 'Kaynak', '##ça', 'Çerkes', 'soylu', '##lar', '177', '##7', 'doğumlu', '##lar', '18', '##38', 'yılında', 'ölen', '##ler', 'Kafkas', 'Savaşı', \"'\", 'nda', 'kişiler', '[SEP]']\n",
      "Average Embedding Shape: torch.Size([768])\n",
      "Average Embedding: tensor([ 3.1219e-01, -3.4488e-02,  1.1118e-02, -3.6194e-02,  1.3312e-02,\n",
      "         8.7684e-02,  6.0835e-01, -5.8831e-03,  4.2102e-01,  3.7467e-01,\n",
      "        -1.9954e-01,  2.5975e-01, -8.9819e-02,  6.8351e-02, -2.3226e-01,\n",
      "        -6.4409e-02,  1.1375e-01,  6.9892e-02,  3.4909e-01, -2.0660e-01,\n",
      "         4.2718e-02, -2.3758e-01, -1.2146e-01,  6.9431e-01,  8.2034e-02,\n",
      "        -4.4726e-01, -3.9995e-01,  4.9043e-01, -5.3700e-01,  4.0028e-02,\n",
      "         2.4516e-02, -1.9234e-01, -5.9901e-02,  4.0203e-01,  1.7956e-01,\n",
      "         2.7692e-01,  4.2539e-01, -1.0046e-01, -1.9326e-01, -2.3722e-01,\n",
      "         3.9989e-01,  1.1785e-01, -3.7475e-01, -4.7698e-01,  1.2440e-01,\n",
      "         1.7583e-01,  4.7179e-01, -6.1670e-01,  3.4876e-01, -1.1977e-01,\n",
      "         4.3870e-01, -4.7105e-01,  3.8414e-01,  3.6902e-01, -1.2121e-02,\n",
      "        -3.3284e-02,  2.5584e-01,  2.0225e-01,  1.4411e-01,  2.9933e-01,\n",
      "         3.6910e-01,  2.3893e-01,  6.0434e-01,  1.5669e-01, -8.5170e-01,\n",
      "        -2.5171e-01,  3.6258e-01,  4.5186e-01, -2.9369e-01,  3.8370e-01,\n",
      "         4.9858e-01, -7.5623e-02,  1.1362e-02, -1.3621e-01, -2.7373e-01,\n",
      "        -3.1269e-01, -6.4951e-01, -6.9747e-02,  2.1302e-01,  3.4201e-01,\n",
      "        -3.8148e-01, -3.2749e-02,  7.4201e-01, -6.0619e-01, -1.8069e-01,\n",
      "        -1.5151e-01,  7.6336e-02, -4.0224e-02, -5.9742e-01, -1.7219e-02,\n",
      "        -5.6787e-01,  2.6290e-01,  2.3984e-01,  4.8434e-01,  4.7557e-01,\n",
      "         2.2432e-01, -1.0822e-01,  3.5924e-01, -4.4102e-01, -1.1613e+00,\n",
      "         5.3896e-02, -2.8951e-01, -1.0792e+00, -2.2577e-02, -2.9868e-01,\n",
      "        -2.7837e-01,  1.0477e-01,  3.8852e-01,  2.9142e-01, -4.2427e-01,\n",
      "         3.6626e-01,  7.9898e-02,  2.2686e-01,  2.3253e-02, -6.9434e-01,\n",
      "         3.2550e+00, -5.6280e-02,  1.1168e-01,  4.2853e-01,  7.7213e-02,\n",
      "         3.1671e-01, -2.9387e-01, -2.1341e-01, -7.9131e-02, -1.0102e-01,\n",
      "        -5.7301e-01,  5.6494e-01,  2.0392e-01, -2.6974e-01, -9.0448e-01,\n",
      "        -7.6977e-01,  5.1432e-02, -1.3809e-01,  2.2806e-01, -3.8749e-01,\n",
      "         4.0886e-01,  2.2627e-02, -2.4360e-02, -1.0032e-01, -8.8879e-03,\n",
      "        -2.9814e-01,  2.4151e-01, -6.5038e-01,  5.5605e-01, -1.5214e-02,\n",
      "        -4.4102e-01,  2.1589e-01,  8.9567e-02, -3.3454e-01,  4.1183e-01,\n",
      "        -2.5177e-02, -4.8496e-01,  3.7691e-01,  6.1995e-02, -2.9426e-01,\n",
      "        -1.5210e-01,  5.1504e-01,  4.9226e-01,  1.0083e-01,  1.9789e-01,\n",
      "         6.5205e-01, -9.7679e-02,  3.4597e-02,  9.5440e-02,  6.5158e-01,\n",
      "        -5.6019e-01, -1.1912e-01,  1.9009e-01,  1.1314e-01,  1.0752e-01,\n",
      "         4.7765e-01,  2.5196e-01, -1.5925e-01,  1.3468e-01, -1.9441e-01,\n",
      "        -5.0252e-02,  4.2977e-01,  2.7336e-01,  4.7672e-02,  2.3097e-01,\n",
      "         1.5998e-01, -1.3434e-01,  3.8424e-01, -3.9759e-01, -2.6207e-02,\n",
      "         2.9264e-02, -1.2846e-01, -3.9234e-01, -2.3295e-01, -1.4392e-01,\n",
      "         7.9061e-02,  2.8095e-01, -1.6391e-01,  2.0505e-01, -1.2172e-01,\n",
      "        -2.5179e-01,  8.8469e-02, -1.5946e+00, -6.6211e-01,  1.6993e-01,\n",
      "        -1.6472e-02,  2.5519e-01, -2.4024e-02,  5.7010e-01,  6.1551e-03,\n",
      "         7.0113e-02, -3.9507e-01, -2.2114e-02, -2.0259e-01, -8.9107e-03,\n",
      "         1.1820e-01, -1.0522e-02,  5.2899e-01, -3.6007e-01, -5.6266e-01,\n",
      "         1.3287e-01, -5.8443e-01, -2.5912e-01, -4.3816e-02, -1.1244e-01,\n",
      "         1.0696e+00,  3.1219e-01, -4.1700e-01,  1.1373e-01, -2.2935e-01,\n",
      "        -1.4058e-02,  2.6080e-01,  6.1457e-03,  5.5064e-02,  5.2089e-01,\n",
      "         1.3195e-01, -6.0868e-01,  4.0164e-01, -1.8374e-01,  8.4919e-01,\n",
      "        -4.2096e-01, -3.7411e-01,  1.8478e-02, -5.6272e-01, -2.5044e-01,\n",
      "        -1.1385e-01,  1.6000e-01,  3.3307e-01, -5.7846e-02, -4.1887e-02,\n",
      "        -1.7514e-01,  2.8522e-01, -3.3909e-01,  1.7133e-01,  2.4794e-02,\n",
      "        -3.0897e-01,  1.7487e-01, -4.8215e-01, -1.0892e-01,  1.0915e-01,\n",
      "        -2.9227e-02, -6.7439e-02, -3.6022e-01, -8.8648e-02,  2.5974e-01,\n",
      "        -2.2780e-02,  1.8174e-02,  8.9919e-02,  1.6508e+00, -6.3506e-01,\n",
      "         4.9391e-01,  7.9321e-02,  3.2023e-02,  3.1216e-01, -7.8220e-02,\n",
      "         3.5055e-01, -2.8349e-01, -4.8787e-01, -5.3590e-01, -4.5163e-01,\n",
      "         2.4602e-01,  4.0553e-01, -2.9002e-01, -1.6120e-01,  1.3428e-02,\n",
      "         4.7906e-01,  2.2494e-01,  3.5909e-01,  1.2861e-01, -1.7966e-01,\n",
      "         9.8253e-02, -9.9344e-02,  2.3110e-01,  3.1276e-01,  6.4092e-02,\n",
      "         2.7386e-01, -3.8601e-01, -5.6480e-01, -5.6070e-01, -6.4271e-02,\n",
      "        -2.8354e-01,  6.7687e-02, -5.7471e-01,  3.0518e-02, -1.3380e-02,\n",
      "        -3.6718e-01,  3.8880e-01, -1.9569e-01,  2.8110e-01, -2.9406e-01,\n",
      "        -2.5891e-01, -3.0043e-01, -3.3694e-01,  5.7723e-02, -1.2361e+00,\n",
      "        -1.1917e-01, -2.6665e-01, -5.6574e-02, -3.8907e-01,  4.2425e-01,\n",
      "        -6.5229e-02,  6.5768e-01, -1.0842e-01, -7.0508e-01,  8.4208e-02,\n",
      "        -3.7736e-01,  3.2153e-01,  5.6956e-01,  1.2256e-01,  4.2261e-01,\n",
      "        -2.7749e-01,  7.9419e-02, -8.1517e-02, -3.0462e-02,  1.5746e-01,\n",
      "        -8.7179e-02,  1.8869e-01,  4.1413e-01,  3.7192e-01, -1.9835e-01,\n",
      "        -2.5932e-01,  5.4023e-02, -3.8093e-01,  1.1605e-01, -1.4389e-01,\n",
      "        -4.5509e-01, -6.0786e-01,  4.2643e-01,  1.6004e-01, -3.4740e-02,\n",
      "        -4.4579e-01, -5.6887e-01, -1.1662e-01,  2.1577e-01,  6.6576e-03,\n",
      "        -2.3879e-01,  4.4046e-01, -2.6281e-01,  2.4404e-01,  8.1931e-02,\n",
      "         2.2825e-01, -1.5294e-01, -3.7482e-01,  8.8104e-02,  4.0676e-01,\n",
      "         1.6295e-01,  5.8565e-01, -8.0144e-02, -4.1792e-01, -4.6798e-01,\n",
      "         3.9977e-01, -3.7319e-01, -1.2999e-01, -4.4200e-01, -2.9825e-01,\n",
      "        -1.2899e-01, -1.8651e-01, -2.0209e-02, -6.6213e-01,  5.0630e-02,\n",
      "        -4.6655e-01, -4.3796e-01,  6.7476e-02,  3.4367e-01,  1.8640e-01,\n",
      "         3.3172e-01, -4.1092e-01,  2.6630e-02, -4.9168e-02, -3.4948e-01,\n",
      "         1.6500e-02, -4.3398e-01,  2.6911e-01,  3.4227e-02, -2.1475e-01,\n",
      "         9.7154e-01, -2.9554e-01,  8.5149e-01, -6.0231e-01,  1.0421e-01,\n",
      "         6.2897e-01,  1.8700e-02,  1.6866e-01, -7.0568e-03, -6.9820e-01,\n",
      "        -1.3916e-01,  3.2686e-01, -1.5017e-01,  6.5600e-01,  2.9388e-02,\n",
      "        -6.0431e-01,  3.8548e-02, -1.2187e-01, -4.8818e-01,  1.5922e-01,\n",
      "        -2.1494e-02, -2.1316e-01, -1.5983e-01, -3.7928e-01,  5.6203e-01,\n",
      "         3.1285e-01, -4.0310e-01,  3.8763e-01, -4.1886e-01,  1.6276e-01,\n",
      "         1.2610e-01,  3.5952e-01,  1.3288e-01,  6.0504e-01, -3.4769e-01,\n",
      "        -1.5976e-01,  2.9626e-01, -2.2079e-01, -1.5934e-01, -5.8491e-01,\n",
      "        -5.7811e-02, -4.7510e-01,  2.7285e-03,  3.7191e-01,  4.7557e-01,\n",
      "         9.2435e-02,  2.3198e-01, -5.8704e-01, -1.9506e-01, -5.3740e-01,\n",
      "         1.8715e-01, -3.5691e-01,  2.5481e-01,  3.2795e-01, -9.4206e-02,\n",
      "        -2.2492e-01, -3.1406e-01,  4.5814e-01, -1.7896e-01, -3.9470e-01,\n",
      "         1.9183e-01, -4.3177e-01,  2.7146e-01,  1.9477e-01, -1.7568e-02,\n",
      "        -2.0134e-01,  5.7984e-03,  3.0490e-01, -2.7846e-01,  9.8830e-03,\n",
      "        -3.0119e-01, -4.1994e-01, -1.0905e-02,  6.9638e-01,  9.4965e-02,\n",
      "        -2.6103e-01,  8.8206e-02, -1.0292e-01, -1.2342e-01, -2.2317e-03,\n",
      "        -5.2474e-02, -2.1636e-01, -1.6554e-01,  2.3173e-01,  1.2170e-01,\n",
      "         4.5793e-01, -1.1033e-01,  1.4489e-01,  2.2540e-01,  5.2360e-01,\n",
      "        -3.6468e-01, -1.5081e-01, -2.3761e-02,  2.7475e-01,  5.3707e-01,\n",
      "         9.3503e-02, -4.9759e-01,  1.5903e-01, -1.2017e-01,  3.4478e-01,\n",
      "        -2.1399e-01,  3.9456e-01, -3.2861e-01,  1.7182e-01, -1.1697e-01,\n",
      "         5.6727e-03, -1.9770e-01, -2.3682e-01,  2.7554e-01, -3.9236e-01,\n",
      "         2.0691e-01,  1.6439e-01, -3.7138e-01, -7.8304e-01, -1.9874e-01,\n",
      "         6.4637e-01, -2.4494e-01, -4.1920e-01, -3.7675e-01,  1.3178e-01,\n",
      "         1.9076e-01, -1.2906e-01, -6.4864e-04, -9.7821e-03, -1.2172e-01,\n",
      "        -5.5357e-02,  2.2997e-01, -3.2848e-01, -4.1649e-01,  9.9676e-04,\n",
      "        -4.5320e-01, -2.2864e-01, -1.6760e-01, -7.9657e-02, -6.0780e-02,\n",
      "        -1.7627e-01, -4.1947e-02,  2.3884e-01, -4.7784e-03, -3.1593e-01,\n",
      "        -1.0243e-01,  5.3464e-01,  2.7388e-01, -4.2258e-02, -1.5521e-01,\n",
      "        -1.0183e-01, -2.9342e-01, -1.0132e+00,  2.3122e-01, -3.3482e-01,\n",
      "         3.2136e-01, -2.3603e-01, -1.4938e-01, -2.3986e-01,  6.1094e-02,\n",
      "         1.6784e-01, -3.8075e-02,  5.6459e-01, -2.0828e-02, -1.7406e-01,\n",
      "        -2.9475e-01, -5.0143e-01, -1.6885e-01,  4.4070e-01,  3.1866e-01,\n",
      "        -2.7534e-01,  4.1410e-01, -7.2704e-02, -2.9659e-01,  3.0922e-01,\n",
      "        -5.1553e-01, -2.7293e-01, -1.2403e-01,  5.3698e-01,  8.8994e-02,\n",
      "         4.1334e-01,  2.5389e-01,  6.0110e-01, -2.3192e-01, -9.9463e+00,\n",
      "         3.8342e-01, -3.4833e-01,  3.5175e-02, -3.3336e-01,  2.5660e-01,\n",
      "         8.5744e-01, -3.4563e-01,  3.0483e-03,  3.4735e-01,  3.8450e-01,\n",
      "         3.9665e-01,  2.2100e-01,  6.5109e-02, -5.5761e-01, -6.2348e-01,\n",
      "        -1.8679e-01,  1.9003e-01,  7.4262e-02, -5.9655e-02, -3.9839e-01,\n",
      "        -2.2625e-02, -7.6319e-02,  2.9763e-01,  1.4098e-01, -2.8759e-01,\n",
      "        -4.0783e-01,  1.1544e-01,  3.2446e-01, -2.9828e-01,  1.4054e-02,\n",
      "         1.6943e-01, -2.0345e-01, -2.1174e-02,  1.1417e-01,  3.3420e-01,\n",
      "        -1.0892e-01, -3.1187e-01, -5.7087e-01, -1.1561e-02,  4.2107e-02,\n",
      "         4.9406e-01, -3.7056e-01, -3.2354e-01,  5.4846e-02,  2.4392e-01,\n",
      "        -1.2840e-01, -4.3743e-01,  2.4391e-01,  2.1046e-01, -6.3811e-01,\n",
      "         3.5563e-01, -2.0561e-01, -3.0996e-01,  1.6479e-01, -5.1947e-02,\n",
      "         3.2559e-01, -6.3670e-03, -2.7855e-01, -4.2847e-01, -1.2022e-01,\n",
      "         4.0702e-01,  9.6086e-01,  1.3305e-01, -2.0369e-01,  7.5751e-02,\n",
      "        -1.2915e-01, -8.5741e-02,  2.7087e-01,  9.1068e-02, -1.5946e-01,\n",
      "         4.7289e-01,  1.0613e-01,  1.3504e-01,  2.7304e-01, -7.9823e-01,\n",
      "         1.1986e-01,  4.7432e-01, -1.4133e-01,  3.9729e-01, -1.6949e-01,\n",
      "        -9.2290e-01, -1.9302e-01, -7.9017e-02, -6.5796e-01,  1.3385e-02,\n",
      "         1.6185e-01, -3.4487e-01,  5.8601e-01, -1.5023e-01,  5.8034e-01,\n",
      "        -2.8326e-01, -1.6494e-01, -2.9796e-01,  6.7479e-03, -6.3622e-01,\n",
      "        -1.7732e-02, -1.6043e-01, -8.2452e-01, -2.4934e-02, -1.3969e-01,\n",
      "        -1.2475e-01,  2.1235e-01,  6.9211e-02,  1.1795e-01, -2.5098e-02,\n",
      "         4.8630e-01,  3.5354e-01,  4.4272e-01,  2.5360e-01,  2.7441e-01,\n",
      "        -2.6457e-01, -3.3007e-01, -3.1083e-01,  4.9623e-01, -2.7829e-01,\n",
      "        -3.0000e-01, -2.5620e-01,  2.1623e-01, -1.0724e-01, -5.0995e-01,\n",
      "        -4.9460e-01,  8.4283e-02, -3.2844e-01, -6.0080e-01, -1.1809e-01,\n",
      "         1.1040e-01,  3.7749e-02,  3.9097e-01,  2.7157e-02, -3.5270e-01,\n",
      "        -1.0008e-01, -3.1026e-01, -1.9041e-01,  3.7090e-01, -4.5056e-01,\n",
      "        -8.3087e-02, -3.6450e-01, -1.0154e+00, -1.3134e-01, -5.0261e-02,\n",
      "         3.6961e-01, -1.1989e-01, -1.2336e-01,  2.6829e-01, -6.0926e-01,\n",
      "        -3.0037e-01, -1.0460e+00, -2.1501e-01,  1.7171e-01,  1.7970e-02,\n",
      "        -2.0708e-01, -1.3656e-01, -3.2854e-01,  1.2158e-01, -3.0438e-01,\n",
      "        -4.6487e-02,  1.8717e-01, -2.3236e-01, -1.4668e-01, -6.9169e-01,\n",
      "        -2.1502e-01, -1.2722e-01,  3.5600e-01,  1.5203e-03, -3.7041e-01,\n",
      "        -6.5877e-01,  2.1490e-01, -5.1359e-02,  2.2720e-01, -1.6363e-01,\n",
      "        -1.0862e-01,  1.4914e-02,  3.7205e-01,  3.4950e-01, -2.5987e-01,\n",
      "        -2.0222e-01,  3.4466e-02,  5.8733e-01, -1.6877e-01, -4.8642e-01,\n",
      "        -7.8254e-03,  1.2950e-01, -5.6791e-01, -6.6342e-01, -1.5021e-01,\n",
      "        -4.4367e-01, -2.8434e-01, -1.7593e-01, -4.2538e-01, -3.7350e-01,\n",
      "        -4.0185e-02, -6.1727e-01,  2.3771e-01, -4.1247e-01,  3.9440e-01,\n",
      "         1.0506e-01, -4.0222e-01,  5.9232e-01])\n",
      "TF-IDF Keywords: [('rus', np.float64(0.33567254331867563)), ('ahecaqo', np.float64(0.25175440748900674)), ('000', np.float64(0.16783627165933782)), ('1777', np.float64(0.16783627165933782)), ('ile', np.float64(0.16783627165933782)), ('pşıqo', np.float64(0.16783627165933782)), ('türkçe', np.float64(0.16783627165933782)), ('vardı', np.float64(0.16783627165933782)), ('çerkes', np.float64(0.16783627165933782)), ('çerkesya', np.float64(0.16783627165933782)), ('12', np.float64(0.08391813582966891)), ('1837', np.float64(0.08391813582966891)), ('1838', np.float64(0.08391813582966891)), ('adamıydı', np.float64(0.08391813582966891)), ('adlardaki', np.float64(0.08391813582966891)), ('anlamlıdır', np.float64(0.08391813582966891)), ('anlamına', np.float64(0.08391813582966891)), ('askeri', np.float64(0.08391813582966891)), ('askerî', np.float64(0.08391813582966891)), ('atlıdan', np.float64(0.08391813582966891)), ('atlıya', np.float64(0.08391813582966891)), ('az', np.float64(0.08391813582966891)), ('becerisinin', np.float64(0.08391813582966891)), ('belirtir', np.float64(0.08391813582966891)), ('beyoğlu', np.float64(0.08391813582966891)), ('bilgiler', np.float64(0.08391813582966891)), ('birliklerine', np.float64(0.08391813582966891)), ('biyografi', np.float64(0.08391813582966891)), ('bjeduğ', np.float64(0.08391813582966891)), ('bölgesinde', np.float64(0.08391813582966891)), ('büyütüldü', np.float64(0.08391813582966891)), ('devlet', np.float64(0.08391813582966891)), ('doğdu', np.float64(0.08391813582966891)), ('doğumlular', np.float64(0.08391813582966891)), ('duyulan', np.float64(0.08391813582966891)), ('dönem', np.float64(0.08391813582966891)), ('ek', np.float64(0.08391813582966891)), ('ekiyle', np.float64(0.08391813582966891)), ('erken', np.float64(0.08391813582966891)), ('eğitim', np.float64(0.08391813582966891)), ('eş', np.float64(0.08391813582966891)), ('geldiği', np.float64(0.08391813582966891)), ('gelen', np.float64(0.08391813582966891)), ('geçti', np.float64(0.08391813582966891)), ('hakkında', np.float64(0.08391813582966891)), ('hastalıktan', np.float64(0.08391813582966891)), ('ismi', np.float64(0.08391813582966891)), ('ismidir', np.float64(0.08391813582966891)), ('için', np.float64(0.08391813582966891)), ('kafkas', np.float64(0.08391813582966891)), ('kalıcı', np.float64(0.08391813582966891)), ('katılımı', np.float64(0.08391813582966891)), ('kaydedilmedi', np.float64(0.08391813582966891)), ('kaynak', np.float64(0.08391813582966891)), ('kaynaklarından', np.float64(0.08391813582966891)), ('kaynakça', np.float64(0.08391813582966891)), ('kazandığı', np.float64(0.08391813582966891)), ('kişi', np.float64(0.08391813582966891)), ('kişiler', np.float64(0.08391813582966891)), ('lakapları', np.float64(0.08391813582966891)), ('lakaptır', np.float64(0.08391813582966891)), ('müfrezesi', np.float64(0.08391813582966891)), ('nda', np.float64(0.08391813582966891)), ('nun', np.float64(0.08391813582966891)), ('nın', np.float64(0.08391813582966891)), ('olduğunu', np.float64(0.08391813582966891)), ('oluşan', np.float64(0.08391813582966891)), ('ordusu', np.float64(0.08391813582966891)), ('oğlu', np.float64(0.08391813582966891)), ('pek', np.float64(0.08391813582966891)), ('qo', np.float64(0.08391813582966891)), ('savaşı', np.float64(0.08391813582966891)), ('savaşına', np.float64(0.08391813582966891)), ('saygı', np.float64(0.08391813582966891)), ('sim', np.float64(0.08391813582966891)), ('soneki', np.float64(0.08391813582966891)), ('sonra', np.float64(0.08391813582966891)), ('soy', np.float64(0.08391813582966891)), ('soyadları', np.float64(0.08391813582966891)), ('soylular', np.float64(0.08391813582966891)), ('sıra', np.float64(0.08391813582966891)), ('sırasında', np.float64(0.08391813582966891)), ('tarafına', np.float64(0.08391813582966891)), ('tarihlerini', np.float64(0.08391813582966891)), ('ulaşıyordu', np.float64(0.08391813582966891)), ('yazmadıkları', np.float64(0.08391813582966891)), ('yıl', np.float64(0.08391813582966891)), ('zaferlerle', np.float64(0.08391813582966891)), ('çatışmalar', np.float64(0.08391813582966891)), ('çerkesler', np.float64(0.08391813582966891)), ('çerkeslerin', np.float64(0.08391813582966891)), ('öldü', np.float64(0.08391813582966891)), ('ölenler', np.float64(0.08391813582966891)), ('ölüm', np.float64(0.08391813582966891)), ('ünlüydü', np.float64(0.08391813582966891))]\n",
      "BERT Embeddings:\n",
      "Text 1 embedding shape: torch.Size([233, 768])\n"
     ]
    }
   ],
   "source": [
    "#-------------------------tf-ıdf hesaplama\n",
    "import re\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from nltk.stem import WordNetLemmatizer\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from nltk.corpus import stopwords as nltk_stopwords\n",
    "from transformers import BertTokenizer, BertModel\n",
    "import torch\n",
    "\n",
    "# BERT Tokenizer ve Model'i yükleyin\n",
    "tokenizer = BertTokenizer.from_pretrained('dbmdz/bert-base-turkish-cased')\n",
    "model = BertModel.from_pretrained('dbmdz/bert-base-turkish-cased')\n",
    "\n",
    "\n",
    "#-------------------------- burada turkish_stop_words'ü alıyoruz\n",
    "def load_stop_words(file_path):\n",
    "    \"\"\"Stop words'leri dosyadan okuyarak bir liste oluşturur.\"\"\"\n",
    "    with open(file_path, 'r', encoding='utf-8') as file:\n",
    "        stop_words = [line.strip() for line in file if line.strip()]\n",
    "    return stop_words\n",
    "\n",
    "# Türkçe stop words dosyasını yükleyin\n",
    "stop_words_list = load_stop_words('turkish_stop_words.txt')\n",
    "\n",
    "#gömülen kelimeleri k-means ile kümeleyebiliriz , benzerlik oranını hesaplamak için farklı algoritmalardan yararlanabiliriz.\n",
    "def get_bert_embeddings(text):\n",
    "    inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)\n",
    "    with torch.no_grad():\n",
    "        outputs = model(**inputs)\n",
    "    # Son katmandaki gömme (embedding) çıktısını alın\n",
    "    return inputs['input_ids'],outputs.last_hidden_state\n",
    "\n",
    "#--------------------------- textleri tokenize eden fonksiyon \n",
    "def get_token_embeddings(text):\n",
    "    inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)\n",
    "    with torch.no_grad():\n",
    "        outputs = model(**inputs)\n",
    "    embeddings = outputs.last_hidden_state\n",
    "    return embeddings\n",
    "\n",
    "#------------------------------------ token verilerinin ortalaması (eşik değer için)\n",
    "def average_embeddings(embeddings):\n",
    "    # Token vektörlerinin ortalamasını alarak metin düzeyinde özet oluştur\n",
    "    return torch.mean(embeddings, dim=1).squeeze()\n",
    "\n",
    "#keywordsler çıkarmak için kullanacağım fonksiyon \n",
    "def extract_keywords_tfidf(corpus,stop_words_list):\n",
    "    \"\"\"TF-IDF ile anahtar kelimeleri çıkarır, stop words listesi ile birlikte kullanır.\"\"\"\n",
    "    vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n",
    "    X = vectorizer.fit_transform(corpus)\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "    scores = np.asarray(X.sum(axis=0)).flatten()\n",
    "    keywords = {feature_names[i]: scores[i] for i in range(len(feature_names))}\n",
    "    sorted_keywords = sorted(keywords.items(), key=lambda x: x[1], reverse=True)\n",
    "    return sorted_keywords\n",
    "\n",
    "#tokenleri kelimelere dönüştürür ve listeler \n",
    "def decode_tokens(input_ids):\n",
    "    # Token ID'lerini kelimelere dönüştür\n",
    "    tokens = tokenizer.convert_ids_to_tokens(input_ids.squeeze().tolist())\n",
    "    return tokens\n",
    "\n",
    "# Örnek metinler (buranın yerine combined_text kullanılacak)\n",
    "texts = [\"\"\"Biyografi\n",
    "İsim \n",
    "Pşıqo ismi Ahecaqo soy ismidir. Çerkeslerin \"-qo\" soneki ile biten hem soyadları hem de lakapları vardı. Bu ek Türkçe adlardaki \"-oğlu\" ekiyle eş anlamlıdır. Pşıqo Türkçe \"Beyoğlu\" anlamına gelen bir lakaptır.\n",
    "\n",
    "Erken dönem \n",
    "Çerkesler tarihlerini yazmadıkları ve tüm bilgiler Rus kaynaklarından geldiği için Ahecaqo hakkında pek bir şey kaydedilmedi. 1777'de Çerkesya'nın Bjeduğ bölgesinde doğdu. Askerî eğitim ile büyütüldü.\n",
    "\n",
    "Rus-Çerkes Savaşına Katılımı \n",
    "Birkaç kaynak, Ahecaqo'nun tüm Çerkesya'da saygı duyulan bir kişi olduğunu belirtir. En az 6.000 atlıdan oluşan kalıcı bir ordusu vardı ve çatışmalar sırasında müfrezesi 12.000 atlıya ulaşıyordu. Rus birliklerine karşı kazandığı zaferlerle ünlüydü. Askeri becerisinin yanı sıra yetenekli bir devlet adamıydı.\n",
    "\n",
    "Ölüm \n",
    "1837 yılında Rus tarafına geçti ve bir yıl sonra hastalıktan öldü.\n",
    "\n",
    "Kaynakça \n",
    "\n",
    "Çerkes soylular\n",
    "1777 doğumlular\n",
    "1838 yılında ölenler\n",
    "Kafkas Savaşı'nda kişiler \"\"\"]\n",
    "         \n",
    "    \n",
    "\n",
    "    \n",
    "\n",
    "\n",
    "#token ıd leri ve bert gömme vektörleri\n",
    "for text in texts:\n",
    "    input_ids,embeddings= get_bert_embeddings(text)\n",
    "    \n",
    "    # BERT gömme vektörlerini elde et\n",
    "    #embeddings = [get_bert_embeddings(text) for text in texts]\n",
    "\n",
    "    # Tokenları ve ortalama vektörleri al\n",
    "    tokens = decode_tokens(input_ids)\n",
    "    avg_embedding = average_embeddings(embeddings)\n",
    "    print(f\"Tokens: {tokens}\")\n",
    "    print(f\"Average Embedding Shape: {avg_embedding.shape}\")\n",
    "    print(f\"Average Embedding: {avg_embedding}\")\n",
    "\n",
    "# TF-IDF anahtar kelimelerini çıkar\n",
    "keywords = extract_keywords_tfidf(texts,stop_words_list)\n",
    "print(\"TF-IDF Keywords:\", keywords)\n",
    "\n",
    "# Gösterim\n",
    "print(\"BERT Embeddings:\")\n",
    "for i, emb in enumerate(embeddings):\n",
    "    print(f\"Text {i+1} embedding shape: {emb.shape}\")\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Keywords without stop words:\n",
      "[('bir', np.float64(0.5)), ('bu', np.float64(0.5)), ('cümledir', np.float64(0.5)), ('örnek', np.float64(0.5)), ('anahtar', np.float64(0.3779644730092272)), ('kelimeleri', np.float64(0.3779644730092272)), ('kullanarak', np.float64(0.3779644730092272)), ('stop', np.float64(0.3779644730092272)), ('türkçe', np.float64(0.3779644730092272)), ('words', np.float64(0.3779644730092272)), ('çıkarıyoruz', np.float64(0.3779644730092272))]\n",
      "\n",
      "Keywords with stop words:\n",
      "[('cümledir', np.float64(0.7071067811865476)), ('örnek', np.float64(0.7071067811865476)), ('anahtar', np.float64(0.3779644730092272)), ('kelimeleri', np.float64(0.3779644730092272)), ('kullanarak', np.float64(0.3779644730092272)), ('stop', np.float64(0.3779644730092272)), ('türkçe', np.float64(0.3779644730092272)), ('words', np.float64(0.3779644730092272)), ('çıkarıyoruz', np.float64(0.3779644730092272))]\n",
      "\n",
      "Keywords removed by stop words list:\n",
      "{'bu', 'bir'}\n",
      "\n",
      "New keywords added by stop words list:\n",
      "set()\n"
     ]
    }
   ],
   "source": [
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "\n",
    "def test_stop_words_effectiveness(corpus, stop_words_list):\n",
    "    \"\"\"Stop words listesinin etkisini test eder.\"\"\"\n",
    "    # İlk olarak, stop words olmadan TF-IDF hesaplayın\n",
    "    vectorizer_no_stop_words = TfidfVectorizer()\n",
    "    X_no_stop_words = vectorizer_no_stop_words.fit_transform(corpus)\n",
    "    feature_names_no_stop_words = vectorizer_no_stop_words.get_feature_names_out()\n",
    "    scores_no_stop_words = np.asarray(X_no_stop_words.sum(axis=0)).flatten()\n",
    "    keywords_no_stop_words = {feature_names_no_stop_words[i]: scores_no_stop_words[i] for i in range(len(feature_names_no_stop_words))}\n",
    "    sorted_keywords_no_stop_words = sorted(keywords_no_stop_words.items(), key=lambda x: x[1], reverse=True)\n",
    "\n",
    "    # Şimdi, stop words ile TF-IDF hesaplayın\n",
    "    vectorizer_with_stop_words = TfidfVectorizer(stop_words=stop_words_list)\n",
    "    X_with_stop_words = vectorizer_with_stop_words.fit_transform(corpus)\n",
    "    feature_names_with_stop_words = vectorizer_with_stop_words.get_feature_names_out()\n",
    "    scores_with_stop_words = np.asarray(X_with_stop_words.sum(axis=0)).flatten()\n",
    "    keywords_with_stop_words = {feature_names_with_stop_words[i]: scores_with_stop_words[i] for i in range(len(feature_names_with_stop_words))}\n",
    "    sorted_keywords_with_stop_words = sorted(keywords_with_stop_words.items(), key=lambda x: x[1], reverse=True)\n",
    "    \n",
    "    # Stop words listesi etkisini gözlemleyin\n",
    "    print(\"Keywords without stop words:\")\n",
    "    print(sorted_keywords_no_stop_words)\n",
    "    \n",
    "    print(\"\\nKeywords with stop words:\")\n",
    "    print(sorted_keywords_with_stop_words)\n",
    "    \n",
    "    # Farklılıkları göster\n",
    "    all_keywords_no_stop_words = set([kw[0] for kw in sorted_keywords_no_stop_words])\n",
    "    all_keywords_with_stop_words = set([kw[0] for kw in sorted_keywords_with_stop_words])\n",
    "    \n",
    "    print(\"\\nKeywords removed by stop words list:\")\n",
    "    print(all_keywords_no_stop_words - all_keywords_with_stop_words)\n",
    "    \n",
    "    print(\"\\nNew keywords added by stop words list:\")\n",
    "    print(all_keywords_with_stop_words - all_keywords_no_stop_words)\n",
    "\n",
    "# Test verisi ve stop words listesi kullanarak test edin\n",
    "test_stop_words_effectiveness(texts, stop_words_list)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package wordnet to\n",
      "[nltk_data]     C:\\Users\\info\\AppData\\Roaming\\nltk_data...\n",
      "[nltk_data]   Package wordnet is already up-to-date!\n",
      "[nltk_data] Downloading package omw-1.4 to\n",
      "[nltk_data]     C:\\Users\\info\\AppData\\Roaming\\nltk_data...\n",
      "[nltk_data]   Package omw-1.4 is already up-to-date!\n",
      "[nltk_data] Downloading package stopwords to\n",
      "[nltk_data]     C:\\Users\\info\\AppData\\Roaming\\nltk_data...\n",
      "[nltk_data]   Package stopwords is already up-to-date!\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "empty vocabulary; perhaps the documents only contain stop words",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[20], line 100\u001b[0m\n\u001b[0;32m     97\u001b[0m documents, document_count \u001b[38;5;241m=\u001b[39m Database\u001b[38;5;241m.\u001b[39mget_input_documents()\n\u001b[0;32m     99\u001b[0m \u001b[38;5;66;03m# Calculate TF-IDF and get feature names\u001b[39;00m\n\u001b[1;32m--> 100\u001b[0m tfidf_matrix, feature_names \u001b[38;5;241m=\u001b[39m \u001b[43mDatabase\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcalculate_tfidf\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mturkish_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    102\u001b[0m \u001b[38;5;66;03m# Extract keywords\u001b[39;00m\n\u001b[0;32m    103\u001b[0m keywords \u001b[38;5;241m=\u001b[39m Database\u001b[38;5;241m.\u001b[39mextract_keywords(tfidf_matrix, feature_names, stop_words\u001b[38;5;241m=\u001b[39mturkish_stop_words)\n",
      "Cell \u001b[1;32mIn[20], line 43\u001b[0m, in \u001b[0;36mDatabase.calculate_tfidf\u001b[1;34m(documents, stop_words)\u001b[0m\n\u001b[0;32m     40\u001b[0m \u001b[38;5;129m@staticmethod\u001b[39m\n\u001b[0;32m     41\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcalculate_tfidf\u001b[39m(documents, stop_words):\n\u001b[0;32m     42\u001b[0m     vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer(stop_words\u001b[38;5;241m=\u001b[39mstop_words, max_features\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m10000\u001b[39m,min_df\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m2\u001b[39m)\n\u001b[1;32m---> 43\u001b[0m     tfidf_matrix \u001b[38;5;241m=\u001b[39m \u001b[43mvectorizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m     44\u001b[0m     feature_names \u001b[38;5;241m=\u001b[39m vectorizer\u001b[38;5;241m.\u001b[39mget_feature_names_out()\n\u001b[0;32m     45\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:2091\u001b[0m, in \u001b[0;36mTfidfVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m   2084\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_params()\n\u001b[0;32m   2085\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf \u001b[38;5;241m=\u001b[39m TfidfTransformer(\n\u001b[0;32m   2086\u001b[0m     norm\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnorm,\n\u001b[0;32m   2087\u001b[0m     use_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39muse_idf,\n\u001b[0;32m   2088\u001b[0m     smooth_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msmooth_idf,\n\u001b[0;32m   2089\u001b[0m     sublinear_tf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msublinear_tf,\n\u001b[0;32m   2090\u001b[0m )\n\u001b[1;32m-> 2091\u001b[0m X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m   2092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf\u001b[38;5;241m.\u001b[39mfit(X)\n\u001b[0;32m   2093\u001b[0m \u001b[38;5;66;03m# X is already a transformed view of raw_documents so\u001b[39;00m\n\u001b[0;32m   2094\u001b[0m \u001b[38;5;66;03m# we set copy to False\u001b[39;00m\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:1473\u001b[0m, in \u001b[0;36m_fit_context.<locals>.decorator.<locals>.wrapper\u001b[1;34m(estimator, *args, **kwargs)\u001b[0m\n\u001b[0;32m   1466\u001b[0m     estimator\u001b[38;5;241m.\u001b[39m_validate_params()\n\u001b[0;32m   1468\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m config_context(\n\u001b[0;32m   1469\u001b[0m     skip_parameter_validation\u001b[38;5;241m=\u001b[39m(\n\u001b[0;32m   1470\u001b[0m         prefer_skip_nested_validation \u001b[38;5;129;01mor\u001b[39;00m global_skip_validation\n\u001b[0;32m   1471\u001b[0m     )\n\u001b[0;32m   1472\u001b[0m ):\n\u001b[1;32m-> 1473\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m fit_method(estimator, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:1372\u001b[0m, in \u001b[0;36mCountVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m   1364\u001b[0m             warnings\u001b[38;5;241m.\u001b[39mwarn(\n\u001b[0;32m   1365\u001b[0m                 \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUpper case characters found in\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   1366\u001b[0m                 \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m vocabulary while \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlowercase\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   1367\u001b[0m                 \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m is True. These entries will not\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   1368\u001b[0m                 \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m be matched with any documents\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   1369\u001b[0m             )\n\u001b[0;32m   1370\u001b[0m             \u001b[38;5;28;01mbreak\u001b[39;00m\n\u001b[1;32m-> 1372\u001b[0m vocabulary, X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_count_vocab\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfixed_vocabulary_\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m   1374\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mbinary:\n\u001b[0;32m   1375\u001b[0m     X\u001b[38;5;241m.\u001b[39mdata\u001b[38;5;241m.\u001b[39mfill(\u001b[38;5;241m1\u001b[39m)\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:1278\u001b[0m, in \u001b[0;36mCountVectorizer._count_vocab\u001b[1;34m(self, raw_documents, fixed_vocab)\u001b[0m\n\u001b[0;32m   1276\u001b[0m     vocabulary \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mdict\u001b[39m(vocabulary)\n\u001b[0;32m   1277\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m vocabulary:\n\u001b[1;32m-> 1278\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m   1279\u001b[0m             \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mempty vocabulary; perhaps the documents only contain stop words\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   1280\u001b[0m         )\n\u001b[0;32m   1282\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m indptr[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m] \u001b[38;5;241m>\u001b[39m np\u001b[38;5;241m.\u001b[39miinfo(np\u001b[38;5;241m.\u001b[39mint32)\u001b[38;5;241m.\u001b[39mmax:  \u001b[38;5;66;03m# = 2**31 - 1\u001b[39;00m\n\u001b[0;32m   1283\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m _IS_32BIT:\n",
      "\u001b[1;31mValueError\u001b[0m: empty vocabulary; perhaps the documents only contain stop words"
     ]
    }
   ],
   "source": [
    "#---------------------------güncel en yeni \n",
    "from pymongo import MongoClient\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from textblob import TextBlob as tb\n",
    "import numpy as np\n",
    "import math\n",
    "from tqdm.auto import tqdm, trange\n",
    "import tensorflow as tf\n",
    "import nltk\n",
    "import re \n",
    "from nltk.stem import WordNetLemmatizer\n",
    "from nltk.corpus import stopwords\n",
    "\n",
    "turkish_stop_words = stopwords.words('turkish')\n",
    "\n",
    "nltk.download('wordnet')\n",
    "nltk.download('omw-1.4')\n",
    "nltk.download('stopwords')\n",
    "\n",
    "\n",
    "import matplotlib.pyplot as plt \n",
    "\n",
    "class Database:\n",
    "    @staticmethod\n",
    "    def get_mongodb():\n",
    "        return 'mongodb://localhost:27017/', 'combined', 'combined_output'\n",
    "\n",
    "    # Get input documents from MongoDB\n",
    "    @staticmethod\n",
    "    def get_input_documents(limit=1000):\n",
    "        mongo_url, db_name, collection_name = Database.get_mongodb()\n",
    "        client = MongoClient(mongo_url)\n",
    "        db = client[db_name]\n",
    "        collection = db[collection_name]\n",
    "        cursor = collection.find().limit(limit)\n",
    "        combined_text = [doc['text'] for doc in cursor]\n",
    "        document_count = len(combined_text)\n",
    "        return combined_text, document_count\n",
    "    \n",
    "\n",
    "    \n",
    "    nltk.download('turkish_stop_words')\n",
    "    data_without_stopwords = []\n",
    "    for i in range(0, len(response)):\n",
    "        doc = re.sub('[^a-zA-Z]', ' ', response[i])\n",
    "        doc = doc.lower()\n",
    "        doc = doc.split()\n",
    "        doc = [lemmatizer.lemmatize(word) for word in doc if not word in set(stopwords)]\n",
    "        doc = ' '.join(doc)\n",
    "        data_without_stopwords.append(doc)\n",
    "\n",
    "    #print ilk satır orjinal datasetteki\n",
    "    print(data.response[0])\n",
    "\n",
    "    # Calculate TF-IDF and get feature names\n",
    "    @staticmethod\n",
    "    def calculate_tfidf(documents, stop_words):\n",
    "        vectorizer = TfidfVectorizer(stop_words=stop_words, max_features=10000,min_df=2)\n",
    "        vectors = vectorizer.fit_transform(data_without_stopwords)\n",
    "        tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "        feature_names = vectorizer.get_feature_names_out()\n",
    "        return tfidf_matrix, feature_names\n",
    "\n",
    "    # Extract keywords using TF-IDF\n",
    "    def extract_keywords(tfidf_matrix, feature_names, top_n=10):\n",
    "        keywords = {}\n",
    "        for doc_idx, row in enumerate(tfidf_matrix):\n",
    "            filtered_feature_names = [name for name in feature_names if name.lower() not in stop_words]\n",
    "            scores = np.asarray(row.T.todense()).flatten()\n",
    "            sorted_indices = np.argsort(scores)[::-1]\n",
    "            top_features = sorted_indices[:top_n]\n",
    "            doc_keywords = [(filtered_feature_names[idx], scores[idx]) for idx in top_features]\n",
    "            keywords[f'document_{doc_idx+1}'] = doc_keywords\n",
    "        return keywords\n",
    "    \n",
    "    #zip keywords and combined text \n",
    "    \n",
    "    # Identify low TF-IDF words\n",
    "    @staticmethod\n",
    "    def identify_low_tfidf_words(tfidf_matrix, feature_names, threshold=0.001):\n",
    "        avg_scores = np.mean(tfidf_matrix, axis=0).A1\n",
    "        low_tfidf_words = [feature_names[i] for i, score in enumerate(avg_scores) if score < threshold]\n",
    "        return low_tfidf_words\n",
    "    \n",
    "    # Update stop words with low TF-IDF words\n",
    "    @staticmethod\n",
    "    def update_stop_words(existing_stop_words, low_tfidf_words):\n",
    "        updated_stop_words = set(existing_stop_words) | set(low_tfidf_words)\n",
    "        return list(updated_stop_words)\n",
    "\n",
    "\n",
    "#tf-ıdf ile döküman içerisinden kelime seçme \n",
    "#Term Frequency (TF): Bir kelimenin belli bir dökümanda tekrar etme değeri\n",
    "#Inverse Document Frequency (IDF):bir kelimenin tüm dökümanlar arasındaki yaygınlığı Nadir bulunan kelimeler, daha yüksek IDF değerine sahip olur.\n",
    "#tf-ıdf skoru ise bu ikisinin çarpımıdır.\n",
    "\n",
    "    #buraya eşik değer belirlenmeli\n",
    "\n",
    "\n",
    "turkish_stop_words = [\n",
    "   'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n",
    "    'b', 'başlayan', 'bağlı', 'bazı', 'belirli', 'ben', 'bence', \n",
    "    'birkaç', 'birlikte', 'bunu', 'burada', 'biten', 'biz', \n",
    "    'bu', 'buna', 'çünkü', 'da', 'de', 'demek', 'den', 'derken', \n",
    "    'değil', 'daha', 'dolayı', 'edilir', 'eğer', 'en', 'fakat', \n",
    "    'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'ise', \n",
    "    'işte', 'itibaren', 'iyi', 'kadar', 'karşı', 'ki', 'kime', \n",
    "    'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', \n",
    "    'olasılıkla', 'olabilir', 'oluşur', 'önce', 'şu', 'sadece', \n",
    "    'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', \n",
    "    'yanı', 'yani', 'yılında', 'yetenekli', 'yine'\n",
    "]\n",
    "# Get input documents\n",
    "documents, document_count = Database.get_input_documents()\n",
    "\n",
    "# Calculate TF-IDF and get feature names\n",
    "tfidf_matrix, feature_names = Database.calculate_tfidf(documents, turkish_stop_words)\n",
    "\n",
    "# Extract keywords\n",
    "keywords = Database.extract_keywords(tfidf_matrix, feature_names, stop_words=turkish_stop_words)\n",
    "print(keywords)\n",
    "\n",
    "# Identify low TF-IDF words\n",
    "low_tfidf_words = Database.identify_low_tfidf_words(tfidf_matrix, feature_names)\n",
    "print(low_tfidf_words)\n",
    "\n",
    "# Update stop words\n",
    "updated_stop_words = Database.update_stop_words(turkish_stop_words, low_tfidf_words)\n",
    "print(updated_stop_words) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unhashable type: 'set'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[15], line 162\u001b[0m\n\u001b[0;32m    159\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names,keywords\n\u001b[0;32m    161\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;18m__name__\u001b[39m\u001b[38;5;241m==\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m__main__\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[1;32m--> 162\u001b[0m     tfidf_matrix, feature_names,keywords\u001b[38;5;241m=\u001b[39m \u001b[43mmain\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    164\u001b[0m     \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAnahtar Kelimler:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m    165\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m doc, words \u001b[38;5;129;01min\u001b[39;00m keywords\u001b[38;5;241m.\u001b[39mitems():\n",
      "Cell \u001b[1;32mIn[15], line 148\u001b[0m, in \u001b[0;36mmain\u001b[1;34m()\u001b[0m\n\u001b[0;32m    146\u001b[0m initial_stop_words \u001b[38;5;241m=\u001b[39m turkish_stop_words\n\u001b[0;32m    147\u001b[0m \u001b[38;5;66;03m# Stop-words listesini iteratif olarak güncelleyin\u001b[39;00m\n\u001b[1;32m--> 148\u001b[0m final_stop_words \u001b[38;5;241m=\u001b[39m \u001b[43miterative_update\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments_list\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minitial_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    149\u001b[0m \u001b[38;5;66;03m#tf-ıdf hesaplama\u001b[39;00m\n\u001b[0;32m    150\u001b[0m tfidf_matrix, feature_names\u001b[38;5;241m=\u001b[39mcalculate_tfidf(documents_list,final_stop_words)\n",
      "Cell \u001b[1;32mIn[15], line 127\u001b[0m, in \u001b[0;36miterative_update\u001b[1;34m(documents, initial_stop_words, iterations)\u001b[0m\n\u001b[0;32m    126\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21miterative_update\u001b[39m(documents, initial_stop_words, iterations\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m5\u001b[39m):\n\u001b[1;32m--> 127\u001b[0m     stop_words \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mset\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43minitial_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    128\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(iterations):\n\u001b[0;32m    129\u001b[0m         tfidf_matrix, feature_names \u001b[38;5;241m=\u001b[39m calculate_tfidf(documents, stop_words)\n",
      "\u001b[1;31mTypeError\u001b[0m: unhashable type: 'set'"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\"\"\"class Tf:\n",
    "    @staticmethod\n",
    "    def tf(word, blob):\n",
    "        return blob.words.count(word) / len(blob.words)\n",
    "\n",
    "    @staticmethod\n",
    "    def n_containing(word, bloblist):\n",
    "        return sum(1 for blob in bloblist if word in blob.words)\n",
    "\n",
    "    @staticmethod\n",
    "    def idf(word, bloblist):\n",
    "        return math.log(len(bloblist) / (1 + Tf.n_containing(word, bloblist)))\n",
    "\n",
    "    @staticmethod\n",
    "    def tfidf(word, blob, bloblist):\n",
    "        return Tf.tf(word, blob) * Tf.idf(word, bloblist)\n",
    "\n",
    "    @staticmethod\n",
    "    def get_input_documents(limit=1000):\n",
    "        return Database.get_input_documents(limit)\"\"\"\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    \"\"\"\n",
    "    Her döküman için anahtar kelimeleri seç.\n",
    "    :param tfidf_matrix: TF-IDF matris\n",
    "    :param feature_names: TF-IDF özellik isimleri\n",
    "    :param top_n: Her döküman için seçilecek anahtar kelime sayısı\n",
    "    :return: Anahtar kelimeler ve skorlari\n",
    "    \"\"\"\n",
    "    \n",
    "\n",
    "#--------------------------------------------------------------- burada aldığımız  dökümanları listeliyoruz\n",
    "# Dokümanları işleyerek TF-IDF hesaplama\n",
    "#bloblist dökümanların bir listesi\n",
    "\"\"\"bloblist = []\n",
    "for i, blob in enumerate(bloblist):\n",
    "    print(\"Top words in document {}\".format(i + 1))\n",
    "    scores = {word: Tf.tfidf(word, blob, bloblist) for word in blob.words} #dökümanların içerisinde bulunan kelimeleri alır.\n",
    "    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)\n",
    "    for word, score in sorted_words[:3]:\n",
    "        print(\"\\tWord: {}, TF-IDF: {}\".format(word, round(score, 5)))\"\"\"\n",
    "\n",
    "\n",
    "# Dökümanları isimlendir\n",
    "#named_documents = {f'döküman {i+1}': doc for i, doc in enumerate(combined_text)}\n",
    "\n",
    "#features olarak top_keywordsleri belirleyerek metnin bu kelimelerin etrafında olması sağlanmalı  \n",
    "def calculate_tfidf(documents, stop_words):\n",
    "    vectorizer = TfidfVectorizer(stop_words=stop_words, max_features=10000)\n",
    "    tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "    return tfidf_matrix, feature_names\n",
    "\n",
    "#---------------------------------------------------------------------------------\n",
    "#kelimelerin ortalama skorlarını hesaplama \n",
    "def identify_low_tfidf_words(tfidf_matrix, feature_names, threshold=0.001):\n",
    "    # TF-IDF skorlarını toplayarak her kelimenin ortalama skorunu hesaplayın\n",
    "    avg_scores = np.mean(tfidf_matrix, axis=0).A1\n",
    "    low_tfidf_words = [feature_names[i] for i, score in enumerate(avg_scores) if score < threshold]\n",
    "    return low_tfidf_words\n",
    "\n",
    "#kelimelerin yeni geliştirilen eşik değere göre güncellenmesi \n",
    "def update_stop_words(existing_stop_words, low_tfidf_words):\n",
    "    updated_stop_words = set(existing_stop_words) | set(low_tfidf_words)\n",
    "    return list(updated_stop_words)\n",
    "\n",
    "\n",
    "#bu kısım detaylandırılmalı \n",
    "def iterative_update(documents, initial_stop_words, iterations=5):\n",
    "    stop_words = set(initial_stop_words)\n",
    "    for _ in range(iterations):\n",
    "        tfidf_matrix, feature_names = calculate_tfidf(documents, stop_words)\n",
    "        low_tfidf_words = identify_low_tfidf_words(tfidf_matrix, feature_names)\n",
    "        stop_words = update_stop_words(stop_words, low_tfidf_words)\n",
    "    return list(stop_words)\n",
    "\n",
    "\n",
    "\n",
    "def main ():\n",
    "\n",
    "    \n",
    "#anlam ilişkisini de kontrol edecek bir yapı oluşpturulacak title ile benzerlik kontrol ederek yüksek benzerlik içeren kelimler sıralnacak .\n",
    "\n",
    "# Dökümanları liste olarak al\n",
    "    named_documents, _ = Tf.get_input_documents(limit=1000)\n",
    "    documents_list = [doc.get('text', '') if isinstance(doc, dict) else doc for doc in list(named_documents.values())]\n",
    "\n",
    "    #başlangıç stop değerleriyle yeni olanları arasında değişim yapma \n",
    "    initial_stop_words = turkish_stop_words\n",
    "    # Stop-words listesini iteratif olarak güncelleyin\n",
    "    final_stop_words = iterative_update(documents_list, initial_stop_words)\n",
    "    #tf-ıdf hesaplama\n",
    "    tfidf_matrix, feature_names=calculate_tfidf(documents_list,final_stop_words)\n",
    "    keywords=extract_keywords(tfidf_matrix,feature_names,top_n=10)\n",
    "\n",
    "    \n",
    "\n",
    "    print(\"Güncellenmiş Stop-Words Listesi:\", final_stop_words)\n",
    "    print(\"TF-IDF Matrix Shape:\", tfidf_matrix.shape)\n",
    "    print(\"Feature Names Sample:\", feature_names[:10])  # İlk 10 feature adını gösterir\n",
    "\n",
    "    return tfidf_matrix, feature_names,keywords\n",
    "\n",
    "if __name__==\"__main__\":\n",
    "    tfidf_matrix, feature_names,keywords= main()\n",
    "\n",
    "    print(\"Anahtar Kelimler:\")\n",
    "    for doc, words in keywords.items():\n",
    "        print(f\"{doc}: {words}\")\n",
    "    \n",
    "\n",
    "#---------------------------------------------------------\n",
    "    \"\"\"blobs = [tb(doc) for doc in documents_list]  # veya 'title' kullanarak başlıkları işleyebilirsiniz\n",
    "    all_words = set(word for blob in blobs for word in blob.words)\n",
    "\n",
    "    tfidf_scores = {}\n",
    "    for word in all_words:\n",
    "        tfidf_scores[word] = [Tf.tfidf(word, blob, blobs) for blob in blobs]\n",
    "\n",
    "    print(\"TF-IDF Skorları:\")\n",
    "    for word, scores in tfidf_scores.items():\n",
    "        print(f\"Kelime: {word}, Skorlar: {scores}\")\"\"\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "InvalidParameterError",
     "evalue": "The 'stop_words' parameter of TfidfVectorizer must be a str among {'english'}, an instance of 'list' or None. Got {'o', 'den', 'an', 'şey', 'burada', 've', 'ah', 'ise', 'hiç', 'yine', 'biz', 'bu', 'da', 'genellikle', 'yılında', 'belirli', 'se', 'ne', 'kadar', 'neden', 'hem', 'aralar', 'yani', 'daha', 'araba', 'derken', 'dolayı', 'kısaca', 'karşı', 'niye', 'ki', 'bunu', 'buna', 'de', 'herhangi', 'önce', 'tabi', 'kime', 'biten', 'ben', 'ya', 'ya da', 'çünkü', 'mu', 'b', 'demek', 'fakat', 'şimdi', 'birlikte', 'her', 'bağlı', 'nasıl', 'şu', 'sadece', 'tüm', 'aslında', 'edilir', 'ama', 'bence', 'en', 'işte', 'gibi', 'ancak', 'birkaç', 'itibaren', 'mü', 'olabilir', 'bazı', 'oluşur', 'başlayan', 'yanı', 'olasılıkla', 'iyi', 'değil', 'eğer', 'yetenekli'} instead.",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mInvalidParameterError\u001b[0m                     Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[2], line 155\u001b[0m\n\u001b[0;32m    152\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names,documents_list \n\u001b[0;32m    154\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;18m__name__\u001b[39m\u001b[38;5;241m==\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m__main__\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[1;32m--> 155\u001b[0m     tfidf_matrix, feature_names,documents_list\u001b[38;5;241m=\u001b[39m \u001b[43mmain\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    158\u001b[0m \u001b[38;5;66;03m# Sonuçları yazdır\u001b[39;00m\n\u001b[0;32m    159\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mİsimlendirilmiş Dökümanlar:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
      "Cell \u001b[1;32mIn[2], line 142\u001b[0m, in \u001b[0;36mmain\u001b[1;34m()\u001b[0m\n\u001b[0;32m    140\u001b[0m initial_stop_words \u001b[38;5;241m=\u001b[39m turkish_stop_words\n\u001b[0;32m    141\u001b[0m \u001b[38;5;66;03m# Stop-words listesini iteratif olarak güncelleyin\u001b[39;00m\n\u001b[1;32m--> 142\u001b[0m final_stop_words \u001b[38;5;241m=\u001b[39m \u001b[43miterative_update\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments_list\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minitial_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    143\u001b[0m \u001b[38;5;66;03m#tf-ıdf hesaplama\u001b[39;00m\n\u001b[0;32m    144\u001b[0m tfidf_matrix, feature_names\u001b[38;5;241m=\u001b[39mcalculate_tfidf(documents_list,final_stop_words)\n",
      "Cell \u001b[1;32mIn[2], line 124\u001b[0m, in \u001b[0;36miterative_update\u001b[1;34m(documents, initial_stop_words, iterations)\u001b[0m\n\u001b[0;32m    122\u001b[0m stop_words \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mset\u001b[39m(initial_stop_words)\n\u001b[0;32m    123\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(iterations):\n\u001b[1;32m--> 124\u001b[0m     tfidf_matrix, feature_names \u001b[38;5;241m=\u001b[39m \u001b[43mcalculate_tfidf\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    125\u001b[0m     low_tfidf_words \u001b[38;5;241m=\u001b[39m identify_low_tfidf_words(tfidf_matrix, feature_names)\n\u001b[0;32m    126\u001b[0m     stop_words \u001b[38;5;241m=\u001b[39m update_stop_words(stop_words, low_tfidf_words)\n",
      "Cell \u001b[1;32mIn[2], line 103\u001b[0m, in \u001b[0;36mcalculate_tfidf\u001b[1;34m(documents, stop_words)\u001b[0m\n\u001b[0;32m    101\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcalculate_tfidf\u001b[39m(documents, stop_words):\n\u001b[0;32m    102\u001b[0m     vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer(stop_words\u001b[38;5;241m=\u001b[39mstop_words, max_features\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m10000\u001b[39m)\n\u001b[1;32m--> 103\u001b[0m     tfidf_matrix \u001b[38;5;241m=\u001b[39m \u001b[43mvectorizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    104\u001b[0m     feature_names \u001b[38;5;241m=\u001b[39m vectorizer\u001b[38;5;241m.\u001b[39mget_feature_names_out()\n\u001b[0;32m    105\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:2091\u001b[0m, in \u001b[0;36mTfidfVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m   2084\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_params()\n\u001b[0;32m   2085\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf \u001b[38;5;241m=\u001b[39m TfidfTransformer(\n\u001b[0;32m   2086\u001b[0m     norm\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnorm,\n\u001b[0;32m   2087\u001b[0m     use_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39muse_idf,\n\u001b[0;32m   2088\u001b[0m     smooth_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msmooth_idf,\n\u001b[0;32m   2089\u001b[0m     sublinear_tf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msublinear_tf,\n\u001b[0;32m   2090\u001b[0m )\n\u001b[1;32m-> 2091\u001b[0m X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m   2092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf\u001b[38;5;241m.\u001b[39mfit(X)\n\u001b[0;32m   2093\u001b[0m \u001b[38;5;66;03m# X is already a transformed view of raw_documents so\u001b[39;00m\n\u001b[0;32m   2094\u001b[0m \u001b[38;5;66;03m# we set copy to False\u001b[39;00m\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:1466\u001b[0m, in \u001b[0;36m_fit_context.<locals>.decorator.<locals>.wrapper\u001b[1;34m(estimator, *args, **kwargs)\u001b[0m\n\u001b[0;32m   1461\u001b[0m partial_fit_and_fitted \u001b[38;5;241m=\u001b[39m (\n\u001b[0;32m   1462\u001b[0m     fit_method\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mpartial_fit\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m _is_fitted(estimator)\n\u001b[0;32m   1463\u001b[0m )\n\u001b[0;32m   1465\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m global_skip_validation \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m partial_fit_and_fitted:\n\u001b[1;32m-> 1466\u001b[0m     \u001b[43mestimator\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_validate_params\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m   1468\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m config_context(\n\u001b[0;32m   1469\u001b[0m     skip_parameter_validation\u001b[38;5;241m=\u001b[39m(\n\u001b[0;32m   1470\u001b[0m         prefer_skip_nested_validation \u001b[38;5;129;01mor\u001b[39;00m global_skip_validation\n\u001b[0;32m   1471\u001b[0m     )\n\u001b[0;32m   1472\u001b[0m ):\n\u001b[0;32m   1473\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m fit_method(estimator, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:666\u001b[0m, in \u001b[0;36mBaseEstimator._validate_params\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m    658\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_validate_params\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[0;32m    659\u001b[0m \u001b[38;5;250m    \u001b[39m\u001b[38;5;124;03m\"\"\"Validate types and values of constructor parameters\u001b[39;00m\n\u001b[0;32m    660\u001b[0m \n\u001b[0;32m    661\u001b[0m \u001b[38;5;124;03m    The expected type and values must be defined in the `_parameter_constraints`\u001b[39;00m\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    664\u001b[0m \u001b[38;5;124;03m    accepted constraints.\u001b[39;00m\n\u001b[0;32m    665\u001b[0m \u001b[38;5;124;03m    \"\"\"\u001b[39;00m\n\u001b[1;32m--> 666\u001b[0m     \u001b[43mvalidate_parameter_constraints\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m    667\u001b[0m \u001b[43m        \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_parameter_constraints\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m    668\u001b[0m \u001b[43m        \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_params\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdeep\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m    669\u001b[0m \u001b[43m        \u001b[49m\u001b[43mcaller_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[38;5;18;43m__class__\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[38;5;18;43m__name__\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[0;32m    670\u001b[0m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\utils\\_param_validation.py:95\u001b[0m, in \u001b[0;36mvalidate_parameter_constraints\u001b[1;34m(parameter_constraints, params, caller_name)\u001b[0m\n\u001b[0;32m     89\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m     90\u001b[0m     constraints_str \u001b[38;5;241m=\u001b[39m (\n\u001b[0;32m     91\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m, \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;241m.\u001b[39mjoin([\u001b[38;5;28mstr\u001b[39m(c)\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mfor\u001b[39;00m\u001b[38;5;250m \u001b[39mc\u001b[38;5;250m \u001b[39m\u001b[38;5;129;01min\u001b[39;00m\u001b[38;5;250m \u001b[39mconstraints[:\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]])\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m or\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m     92\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconstraints[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m     93\u001b[0m     )\n\u001b[1;32m---> 95\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m InvalidParameterError(\n\u001b[0;32m     96\u001b[0m     \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThe \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mparam_name\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[38;5;124m parameter of \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcaller_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m must be\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m     97\u001b[0m     \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconstraints_str\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m. Got \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mparam_val\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[38;5;124m instead.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m     98\u001b[0m )\n",
      "\u001b[1;31mInvalidParameterError\u001b[0m: The 'stop_words' parameter of TfidfVectorizer must be a str among {'english'}, an instance of 'list' or None. Got {'o', 'den', 'an', 'şey', 'burada', 've', 'ah', 'ise', 'hiç', 'yine', 'biz', 'bu', 'da', 'genellikle', 'yılında', 'belirli', 'se', 'ne', 'kadar', 'neden', 'hem', 'aralar', 'yani', 'daha', 'araba', 'derken', 'dolayı', 'kısaca', 'karşı', 'niye', 'ki', 'bunu', 'buna', 'de', 'herhangi', 'önce', 'tabi', 'kime', 'biten', 'ben', 'ya', 'ya da', 'çünkü', 'mu', 'b', 'demek', 'fakat', 'şimdi', 'birlikte', 'her', 'bağlı', 'nasıl', 'şu', 'sadece', 'tüm', 'aslında', 'edilir', 'ama', 'bence', 'en', 'işte', 'gibi', 'ancak', 'birkaç', 'itibaren', 'mü', 'olabilir', 'bazı', 'oluşur', 'başlayan', 'yanı', 'olasılıkla', 'iyi', 'değil', 'eğer', 'yetenekli'} instead."
     ]
    }
   ],
   "source": [
    "from pymongo import MongoClient\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from textblob import TextBlob as tb\n",
    "import numpy as np\n",
    "import math\n",
    "import nltk \n",
    "import matplotlib.pyplot as plt \n",
    "\n",
    "class Database:\n",
    "    @staticmethod\n",
    "    def get_mongodb():\n",
    "        return 'mongodb://localhost:27017/', 'EgitimDatabase', 'train'\n",
    "\n",
    "#--------------------------------------------------------------------------\n",
    "#combined_text eklenmeli \n",
    "    @staticmethod\n",
    "    def get_input_documents(limit=3):\n",
    "        mongo_url, db_name, collection_name = Database.get_mongodb()\n",
    "        client = MongoClient(mongo_url)\n",
    "        db = client[db_name]\n",
    "        collection = db[collection_name]\n",
    "        cursor = collection.find().limit(limit)\n",
    "        combined_text = [doc for doc in cursor]\n",
    "        document_count = len(combined_text)\n",
    "        \n",
    "        # Dökümanları isimlendir\n",
    "        named_documents = {f'döküman {i+1}': doc for i, doc in enumerate(combined_text)}\n",
    "        \n",
    "        return named_documents, document_count\n",
    "\n",
    "\n",
    "class Tf:\n",
    "    @staticmethod\n",
    "    def tf(word, blob):\n",
    "        return blob.words.count(word) / len(blob.words)\n",
    "\n",
    "    @staticmethod\n",
    "    def n_containing(word, bloblist):\n",
    "        return sum(1 for blob in bloblist if word in blob.words)\n",
    "\n",
    "    @staticmethod\n",
    "    def idf(word, bloblist):\n",
    "        return math.log(len(bloblist) / (1 + Tf.n_containing(word, bloblist)))\n",
    "\n",
    "    @staticmethod\n",
    "    def tfidf(word, blob, bloblist):\n",
    "        return Tf.tf(word, blob) * Tf.idf(word, bloblist)\n",
    "\n",
    "    @staticmethod\n",
    "    def get_input_documents(limit=3):\n",
    "        return Database.get_input_documents(limit)\n",
    "\n",
    "# Kullanım örneği\n",
    "named_documents, document_count = Tf.get_input_documents(limit=1000)\n",
    "\n",
    "#tf-ıdf ile döküman içerisinden kelime seçme \n",
    "\n",
    "def extract_keywords(tfidf_matrix, feature_names, top_n=10):\n",
    "    \"\"\"\n",
    "    Her döküman için anahtar kelimeleri seç.\n",
    "    :param tfidf_matrix: TF-IDF matris\n",
    "    :param feature_names: TF-IDF özellik isimleri\n",
    "    :param top_n: Her döküman için seçilecek anahtar kelime sayısı\n",
    "    :return: Anahtar kelimeler ve skorlari\n",
    "    \"\"\"\n",
    "    keywords = {}\n",
    "    for doc_idx, row in enumerate(tfidf_matrix):\n",
    "        # TF-IDF değerlerini ve özellik isimlerini al\n",
    "        scores = np.asarray(row.T.todense()).flatten()\n",
    "        sorted_indices = np.argsort(scores)[::-1]  # Skorları azalan sırada\n",
    "        top_features = sorted_indices[:top_n]\n",
    "        \n",
    "        doc_keywords = [(feature_names[idx], scores[idx]) for idx in top_features]\n",
    "        keywords[f'document_{doc_idx+1}'] = doc_keywords\n",
    "    \n",
    "    return keywords\n",
    "\n",
    "# Dokümanları işleyerek TF-IDF hesaplama\n",
    "#bloblist dökümanların bir listesi\n",
    "bloblist = []\n",
    "for i, blob in enumerate(bloblist):\n",
    "    print(\"Top words in document {}\".format(i + 1))\n",
    "    scores = {word: Tf.tfidf(word, blob, bloblist) for word in blob.words} #dökümanların içerisinde bulunan kelimeleri alır.\n",
    "    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)\n",
    "    for word, score in sorted_words[:3]:\n",
    "        print(\"\\tWord: {}, TF-IDF: {}\".format(word, round(score, 5)))\n",
    "\n",
    "\n",
    "#buraya eşik değer belirlenmeli\n",
    "turkish_stop_words = [\n",
    "    'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n",
    "    'b', 'başlayan', 'bağlı', 'bazı', 'belirli', 'ben', 'bence', \n",
    "    'birkaç', 'birlikte', 'bunu', 'burada', 'biten', 'biz', \n",
    "    'bu', 'buna', 'çünkü', 'da', 'de', 'demek', 'den', 'derken', \n",
    "    'değil', 'daha', 'dolayı', 'edilir', 'eğer', 'en', 'fakat', \n",
    "    'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'ise', \n",
    "    'işte', 'itibaren', 'iyi', 'kadar', 'karşı', 'ki', 'kime', \n",
    "    'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', \n",
    "    'olasılıkla', 'olabilir', 'oluşur', 'önce', 'şu', 'sadece', \n",
    "    'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', \n",
    "    'yanı', 'yani', 'yılında', 'yetenekli', 'yine'\n",
    "]\n",
    "\n",
    "#features olarak top_keywordsleri belirleyerek metnin bu kelimelerin etrafında olması sağlanmalı  \n",
    "def calculate_tfidf(combined_text, stop_words):\n",
    "    vectorizer = TfidfVectorizer(stop_words=stop_words, max_features=10000)\n",
    "    tfidf_matrix = vectorizer.fit_transform(combined_text)\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "    return tfidf_matrix, feature_names\n",
    "\n",
    "#---------------------------------------------------------------------------------\n",
    "#kelimelerin ortalama skorlarını hesaplama \n",
    "def identify_low_tfidf_words(tfidf_matrix, feature_names, threshold=0.001):\n",
    "    # TF-IDF skorlarını toplayarak her kelimenin ortalama skorunu hesaplayın\n",
    "    avg_scores = np.mean(tfidf_matrix, axis=0).A1\n",
    "    low_tfidf_words = [feature_names[i] for i, score in enumerate(avg_scores) if score < threshold]\n",
    "    return low_tfidf_words\n",
    "\n",
    "#kelimelerin yeni geliştirilen eşik değere göre güncellenmesi \n",
    "def update_stop_words(existing_stop_words, low_tfidf_words):\n",
    "    updated_stop_words = set(existing_stop_words) | set(low_tfidf_words)\n",
    "    return list(updated_stop_words)\n",
    "\n",
    "\n",
    "#bu kısım detaylandırılmalı \n",
    "def iterative_update(combined_text, initial_stop_words, iterations=5):\n",
    "    stop_words = set(initial_stop_words)\n",
    "    for _ in range(iterations):\n",
    "        tfidf_matrix, feature_names = calculate_tfidf(combined_text, stop_words)\n",
    "        low_tfidf_words = identify_low_tfidf_words(tfidf_matrix, feature_names)\n",
    "        stop_words = update_stop_words(stop_words, low_tfidf_words)\n",
    "    return list(stop_words)\n",
    "\n",
    "\n",
    "\n",
    "def main ():\n",
    "\n",
    "    \n",
    "#anlam ilişkisini de kontrol edecek bir yapı oluşpturulacak title ile benzerlik kontrol ederek yüksek benzerlik içeren kelimler sıralnacak .\n",
    "\n",
    "# Dökümanları liste olarak al\n",
    "    documents_list = [doc.get('text', '') if isinstance(doc, dict) else doc for doc in list(named_documents.values())]\n",
    "\n",
    "    #başlangıç stop değerleriyle yeni olanları arasında değişim yapma \n",
    "    initial_stop_words = turkish_stop_words\n",
    "    # Stop-words listesini iteratif olarak güncelleyin\n",
    "    final_stop_words = iterative_update(documents_list, initial_stop_words)\n",
    "    #tf-ıdf hesaplama\n",
    "    tfidf_matrix, feature_names=calculate_tfidf(documents_list,final_stop_words)\n",
    "\n",
    "    \n",
    "\n",
    "    print(\"Güncellenmiş Stop-Words Listesi:\", final_stop_words)\n",
    "    print(\"TF-IDF Matrix Shape:\", tfidf_matrix.shape)\n",
    "    print(\"Feature Names Sample:\", feature_names[:10])  # İlk 10 feature adını gösterir\n",
    "\n",
    "    return tfidf_matrix, feature_names,documents_list \n",
    "\n",
    "if __name__==\"__main__\":\n",
    "    tfidf_matrix, feature_names,documents_list= main()\n",
    "\n",
    "\n",
    "# Sonuçları yazdır\n",
    "print(\"İsimlendirilmiş Dökümanlar:\")\n",
    "for name, doc in named_documents.items():\n",
    "    print(f\"{name}: {doc}\")\n",
    "\n",
    "    print(\"\\nDökümanlar Listesi:\")\n",
    "    print(documents_list)\n",
    "\n",
    "#---------------------------------------------------------\n",
    "    blobs = [tb(doc) for doc in documents_list]  # veya 'title' kullanarak başlıkları işleyebilirsiniz\n",
    "    all_words = set(word for blob in blobs for word in blob.words)\n",
    "\n",
    "    tfidf_scores = {}\n",
    "    for word in all_words:\n",
    "        tfidf_scores[word] = [Tf.tfidf(word, blob, blobs) for blob in blobs]\n",
    "\n",
    "    print(\"TF-IDF Skorları:\")\n",
    "    for word, scores in tfidf_scores.items():\n",
    "        print(f\"Kelime: {word}, Skorlar: {scores}\")\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#----------------------------------------------\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#alternatif keywordleri belirleme \n",
    "#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n",
    "\"\"\"turkish_stop_words = set([\n",
    "        'ad', 'adım', 'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n",
    "     'b', 'bazı', 'belirli', 'ben', 'bence', 'bunu', 'burada', 'biz', 'bu', 'buna', 'çünkü', \n",
    "    'da', 'de', 'demek', 'den', 'derken', 'değil', 'daha', 'dolayı',  'edilir', 'eğer', 'en', 'fakat', \n",
    "    'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'ise', 'işte', 'itibaren', 'iyi', 'kadar', \n",
    "    'karşı', 'ki', 'kime', 'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', 'olabilir', 'oluşur', \n",
    "    'önce', 'şu', 'sadece', 'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', 'yani', 'yine'\n",
    "])\n",
    "def calculate_tfidf(documents):\n",
    "    vectorizer = TfidfVectorizer(stop_words=turkish_stop_words, max_features=10000)  # max_features ile özellik sayısını sınırlıyoruz\n",
    "    tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "    return tfidf_matrix, feature_names\n",
    "\n",
    "#feature_names lerin belirlenmesi grekir \n",
    "tfidf_matrix, feature_names=calculate_tfidf(documents)\n",
    "\n",
    "\n",
    "\n",
    "# En yüksek TF-IDF skorlarına sahip anahtar kelimeleri çıkarın\n",
    "#sıkışık format kullanmarak tf-ıdf matrisini işleme \n",
    "def get_top_n_keywords_sparse(n=10):\n",
    "\n",
    "    # TF-IDF hesaplayıcı oluşturun\n",
    "    vectorizer = TfidfVectorizer()\n",
    "\n",
    "    # Başlıklar ve metinler ile TF-IDF matrisini oluşturun\n",
    "    texts = Database.get_input_texts()\n",
    "    titles = Database.get_input_titles()\n",
    "    \n",
    "\n",
    "    #title ve text değerlerini alarak vektörleştirdik.\n",
    "    tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "\n",
    "    # Özellik adlarını (kelimeleri) alın\n",
    "\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "\n",
    "    # TF-IDF sonuçlarını DataFrame'e dönüştürün\n",
    "    df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n",
    "    print(df)\n",
    "    keywords = {}\n",
    "    for i in range(tfidf_matrix.shape[0]):\n",
    "        row = tfidf_matrix[i].toarray().flatten() #list yapısından çıkarma \n",
    "        sorted_indices = row.argsort()[::-1]  # Büyükten küçüğe sıralama\n",
    "        top_indices = sorted_indices[:n]\n",
    "        top_keywords = [feature_names[idx] for idx in top_indices]\n",
    "        keywords[i] = top_keywords\n",
    "    return keywords\"\"\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'TfidfVectorizer' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[1], line 41\u001b[0m\n\u001b[0;32m     31\u001b[0m turkish_stop_words \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mset\u001b[39m([\n\u001b[0;32m     32\u001b[0m     \u001b[38;5;124m'\u001b[39m\u001b[38;5;124ma\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mabide\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mabi\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mabla\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mad\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124madım\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mah\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mama\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124man\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mancak\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maraba\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maralar\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maslında\u001b[39m\u001b[38;5;124m'\u001b[39m, \n\u001b[0;32m     33\u001b[0m     \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maşşağı\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maz\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mb\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbazı\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbelirli\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mben\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbence\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbunu\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mburada\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbiz\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbu\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbuna\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mçünkü\u001b[39m\u001b[38;5;124m'\u001b[39m, \n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m     37\u001b[0m     \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mönce\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mşu\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124msadece\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124msana\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mse\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mşey\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mşimdi\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mtabi\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mtüm\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mve\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mya\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mya da\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124myani\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124myine\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[0;32m     38\u001b[0m ])\n\u001b[0;32m     40\u001b[0m \u001b[38;5;66;03m# TF-IDF hesaplayıcı oluşturun ve Türkçe durak kelimelerini dahil edin\u001b[39;00m\n\u001b[1;32m---> 41\u001b[0m vectorizer \u001b[38;5;241m=\u001b[39m \u001b[43mTfidfVectorizer\u001b[49m(stop_words\u001b[38;5;241m=\u001b[39mturkish_stop_words)\n\u001b[0;32m     44\u001b[0m \u001b[38;5;124;03m\"\"\"IDF, derlemedeki belge sayısının,\u001b[39;00m\n\u001b[0;32m     45\u001b[0m \u001b[38;5;124;03mincelenen anahtar kelimeyi içeren topluluktaki belge sayısına \u001b[39;00m\n\u001b[0;32m     46\u001b[0m \u001b[38;5;124;03mbölünmesiyle elde edilen algoritmadır. \u001b[39;00m\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m     49\u001b[0m \u001b[38;5;124;03mkülliyat yani incelenen tüm belgelerin adedi 10 ise ve test edilen anahtar kelime,\u001b[39;00m\n\u001b[0;32m     50\u001b[0m \u001b[38;5;124;03mkülliyattaki üç belgede görünüyorsa, bu durumda IDF değeri 0.52’dir (log (10/3)).\"\"\"\u001b[39;00m\n\u001b[0;32m     51\u001b[0m \u001b[38;5;66;03m#TF-IDF puanı; Naive Bayes ve Destek Vektör Makineleri gibi algoritmalara aktarılabilir. Böylece kelime sayısı gibi daha temel yöntemlerin sonuçları büyük ölçüde iyileştirilebilir.\u001b[39;00m\n\u001b[0;32m     52\u001b[0m \u001b[38;5;66;03m#IDF = log ( Dokuman Sayısı / Terimin Geçtiği Dokuman Sayısı )\u001b[39;00m\n\u001b[0;32m     53\u001b[0m \u001b[38;5;66;03m#dokuman sayısılarını almakla başlayacağız.\u001b[39;00m\n\u001b[0;32m     54\u001b[0m \u001b[38;5;66;03m#  : titlelerın sayısı / terimler ise \u001b[39;00m\n",
      "\u001b[1;31mNameError\u001b[0m: name 'TfidfVectorizer' is not defined"
     ]
    }
   ],
   "source": [
    "\n",
    "#---------------------------------------------------------------------------------------------------------------------------------\n",
    "#transformers kütüphanesine ait generation fonksiyonu özellikleri ,PyTorch generate() is implemented in GenerationMixin. \n",
    "\n",
    "\n",
    "\"\"\"from transformers import GenerationConfig\n",
    "\n",
    "# Download configuration from huggingface.co and cache.\n",
    "generation_config = GenerationConfig.from_pretrained(\"openai-community/gpt2\")\n",
    "\n",
    "# E.g. config was saved using *save_pretrained('./test/saved_model/')*\n",
    "generation_config.save_pretrained(\"./test/saved_model/\")\n",
    "generation_config = GenerationConfig.from_pretrained(\"./test/saved_model/\")\n",
    "\n",
    "# You can also specify configuration names to your generation configuration file\n",
    "generation_config.save_pretrained(\"./test/saved_model/\", config_file_name=\"my_configuration.json\")\n",
    "generation_config = GenerationConfig.from_pretrained(\"./test/saved_model/\", \"my_configuration.json\")\n",
    "\n",
    "# If you'd like to try a minor variation to an existing configuration, you can also pass generation\n",
    "# arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored\n",
    "generation_config, unused_kwargs = GenerationConfig.from_pretrained(\n",
    "    \"openai-community/gpt2\", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True\n",
    ")\n",
    "generation_config.top_k\n",
    "\n",
    "unused_kwargs\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "#tf-ıdf hesaplama (anahtar kelimeler için) #Bir kelimenin TF IDF puanı ne kadar yüksekse, kelime bulunduğu belgeyle o kadar alakalıdır.\n",
    "\n",
    "turkish_stop_words = set([\n",
    "    'a', 'abide', 'abi', 'abla', 'ad', 'adım', 'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n",
    "    'aşşağı', 'az', 'b', 'bazı', 'belirli', 'ben', 'bence', 'bunu', 'burada', 'biz', 'bu', 'buna', 'çünkü', \n",
    "    'da', 'de', 'demek', 'den', 'derken', 'değil', 'daha', 'dolayı', 'e', 'edilir', 'eğer', 'en', 'fakat', \n",
    "    'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'i', 'ise', 'işte', 'itibaren', 'iyi', 'kadar', \n",
    "    'karşı', 'ki', 'kime', 'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', 'olabilir', 'oluşur', \n",
    "    'önce', 'şu', 'sadece', 'sana', 'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', 'yani', 'yine'\n",
    "])\n",
    "\n",
    "# TF-IDF hesaplayıcı oluşturun ve Türkçe durak kelimelerini dahil edin\n",
    "vectorizer = TfidfVectorizer(stop_words=turkish_stop_words)\n",
    "\n",
    "\n",
    "\"\"\"IDF, derlemedeki belge sayısının,\n",
    "incelenen anahtar kelimeyi içeren topluluktaki belge sayısına \n",
    "bölünmesiyle elde edilen algoritmadır. \n",
    "Yani ters belge sıklığı bir terimin önemini ölçer,\n",
    "toplam belge sayısının, terimi içeren belge sayısına bölünmesiyle elde edilir.\n",
    "külliyat yani incelenen tüm belgelerin adedi 10 ise ve test edilen anahtar kelime,\n",
    "külliyattaki üç belgede görünüyorsa, bu durumda IDF değeri 0.52’dir (log (10/3)).\"\"\"\n",
    "#TF-IDF puanı; Naive Bayes ve Destek Vektör Makineleri gibi algoritmalara aktarılabilir. Böylece kelime sayısı gibi daha temel yöntemlerin sonuçları büyük ölçüde iyileştirilebilir.\n",
    "#IDF = log ( Dokuman Sayısı / Terimin Geçtiği Dokuman Sayısı )\n",
    "#dokuman sayısılarını almakla başlayacağız.\n",
    "#  : titlelerın sayısı / terimler ise \n",
    "\n",
    "document_number=416434\n",
    "\"\"\"Sonuç olarak TF IDF’nin, SEO’da pratik ve önemli bir kullanım alanına sahip olduğunu söylenebilir,\n",
    " özellikle yüksek kaliteli içeriğin optimize edilmesinde ve oluşturulmasında yararlıdır. \n",
    " Ancak TF IDF, içerik optimizasyonu için tek başına kullanıldığında ciddi sınırlamalarla karşı karşıya kalır:\"\"\"\n",
    "\n",
    "# TF-IDF hesaplayıcı oluşturun\n",
    "vectorizer = TfidfVectorizer()\n",
    "\n",
    "# Başlıklar ve metinler ile TF-IDF matrisini oluşturun\n",
    "texts = Database.get_input_texts()\n",
    "titles,title_count = Database.get_input_titles()\n",
    "documents = titles + texts  # Başlıklar ve metinleri birleştir\n",
    "\n",
    "#title ve text değerlerini alarak vektörleştirdik.\n",
    "tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "\n",
    "# Özellik adlarını (kelimeleri) alın\n",
    "\n",
    "feature_names = vectorizer.get_feature_names_out()\n",
    "\n",
    "# TF-IDF sonuçlarını DataFrame'e dönüştürün\n",
    "df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n",
    "\n",
    "\n",
    "\"\"\"def get_top_n_keywords(df, n=10):\n",
    "    keywords = {}\n",
    "    for i, row in df.iterrows():\n",
    "        sorted_row = row.sort_values(ascending=False)\n",
    "        top_keywords = sorted_row.head(n).index\n",
    "        keywords[i] = top_keywords.tolist()\n",
    "    return keywords\"\"\"\n",
    "\n",
    "# En yüksek TF-IDF skorlarına sahip anahtar kelimeleri çıkarın\n",
    "#sıkışık format kullanmarak tf-ıdf matrisini işleme \n",
    "def get_top_n_keywords_sparse(n=10):\n",
    "\n",
    "    # TF-IDF hesaplayıcı oluşturun\n",
    "    vectorizer = TfidfVectorizer()\n",
    "\n",
    "    # Başlıklar ve metinler ile TF-IDF matrisini oluşturun\n",
    "    texts = Database.get_input_texts()\n",
    "    titles = Database.get_input_titles()\n",
    "    \n",
    "\n",
    "    #title ve text değerlerini alarak vektörleştirdik.\n",
    "    tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "\n",
    "    # Özellik adlarını (kelimeleri) alın\n",
    "\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "\n",
    "    # TF-IDF sonuçlarını DataFrame'e dönüştürün\n",
    "    df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n",
    "    print(df)\n",
    "    keywords = {}\n",
    "    for i in range(tfidf_matrix.shape[0]):\n",
    "        row = tfidf_matrix[i].toarray().flatten() #list yapısından çıkarma \n",
    "        sorted_indices = row.argsort()[::-1]  # Büyükten küçüğe sıralama\n",
    "        top_indices = sorted_indices[:n]\n",
    "        top_keywords = [feature_names[idx] for idx in top_indices]\n",
    "        keywords[i] = top_keywords\n",
    "    return keywords\n",
    "\n",
    "\n",
    "top_keywords = get_top_n_keywords_sparse(tfidf_matrix, feature_names)\n",
    "print(top_keywords)\n",
    "print(f\"Başlıklar: {titles}\")\n",
    "print(f\"Başlık sayısı: {title_count}\")\n",
    "print(f\"Metinler: {texts}\")\n",
    "print(f\"Metin sayısı: {len(texts)}\")\n",
    "print(f\"Birleştirilmiş Belgeler: {documents[:5]}\")  # İlk birkaç belgeyi kontrol etme\n",
    "\n",
    "def calculate_tfidf(docs):\n",
    "    vectorizer = TfidfVectorizer(stop_words=turkish_stop_words)\n",
    "    tfidf_matrix = vectorizer.fit_transform(docs)\n",
    "    feature_names = vectorizer.get_feature_names_out()\n",
    "    return tfidf_matrix, feature_names\n",
    "\n",
    "# İşlem için dökümanları parçalayarak kullanın\n",
    "def process_documents_in_batches(docs, batch_size=1000, top_n=5):\n",
    "    all_keywords = {}\n",
    "    for start in range(0, len(docs), batch_size):\n",
    "        end = min(start + batch_size, len(docs))\n",
    "        batch_docs = docs[start:end]\n",
    "        tfidf_matrix, feature_names = calculate_tfidf(batch_docs)\n",
    "        batch_keywords = get_top_n_keywords_sparse(tfidf_matrix, feature_names, n=top_n)\n",
    "        all_keywords.update(batch_keywords)\n",
    "    return all_keywords\n",
    "\n",
    "#buraya mango db üzerindeki tüm dökümanlar gelmewli \n",
    "keywords= process_documents_in_batches(documents,batch_size=1000,top_n=5)\n",
    "\n",
    "documents = titles + texts  # Başlıklar ve metinleri birleştir\n",
    "print(f\"en yüksek tf-ıdf skoruna sahip anahtar kelimeler:{keywords}\")\n",
    "\n",
    "\n",
    "# Belgeleri TF-IDF matrisine dönüştürün\n",
    "\"\"\"tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "\n",
    "# Özellik adlarını (kelimeleri) alın\n",
    "feature_names = vectorizer.get_feature_names_out()\n",
    "\n",
    "# TF-IDF sonuçlarını DataFrame'e dönüştürün\n",
    "df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n",
    "\n",
    "print(df)\"\"\"\n",
    "\n",
    "#text ve title a göre keywords belirlenmesi\n",
    "\n",
    "#------------------------------------------------------------------------------\n",
    "\n",
    "\n",
    "#sbert ile alt başlıkların oluşturulması\n",
    "\n",
    "#kümelenme ile alt başlıkların belirlenmesi \n",
    "\n",
    "#-------------------------------------------------------------------------------\n",
    "\n",
    "#anahatar kelime ve alt başlıkların veri tabnaına eklnemesi "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#benzerlik hesaplaması için kullanılacak \n",
    "from sentence_transformers import SentenceTransformer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarity Sentences "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#prompt oluştururak generate etmek için hazırlık"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bert Modeliyle tokenizer atama"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer= BertTokenizer.from_pretrained('bert-base-uncased')\n",
    "model=BertForMaskedLM.from_pretrained('bert-base-uncased')\n",
    "\n",
    "\"\"\"BERT MODELİNİ AYARLAMA\n",
    "\n",
    "input_file: Modelin işlem yapacağı giriş dosyasının yolunu belirtir. Bu dosya, metin verilerini içermelidir.\n",
    "-----------------------------------------------------------------------------------------------------------------\n",
    "output_file: Modelin çıktılarının kaydedileceği dosyanın yolunu belirtir.\n",
    "------------------------------------------------------------------------------------------------------------------\n",
    "layers: Hangi BERT katmanlarının kullanılacağını belirler. Örneğin, \"-1,-2,-3,-4\" son dört katmanı ifade eder.\n",
    "----------------------------------------------------------------------------------------------------------------------\n",
    "bert_config_file: Önceden eğitilmiş BERT modelinin yapılandırma dosyasının yolu. Bu dosya modelin mimarisini belirler.\n",
    "--------------------------------------------------------------------------------------------------------------------------\n",
    "max_seq_length: Giriş sekanslarının maksimum uzunluğu. Sekanslar bu uzunluktan uzunsa kesilir, kısa ise sıfır ile doldurulur.\n",
    "--------------------------------------------------------------------------------------------------------------------------------\n",
    "init_checkpoint: Başlangıç ağırlıkları. Genellikle önceden eğitilmiş bir BERT modelinin ağırlıkları buradan yüklenir.\n",
    "----------------------------------------------------------------------------------------------------------------------------\n",
    "vocab_file: BERT modelinin eğitildiği kelime dağarcığının (vocabulary) dosya yolu. Modelin kelime parçacıklarını tanıması için gereklidir.\n",
    "--------------------------------------------------------------------------------------------------------------------------------------------------\n",
    "do_lower_case: Giriş metinlerinin küçük harfe mi dönüştürüleceğini belirler. Küçük harfli model için True, büyük harfli model için False olmalıdır.\n",
    "-----------------------------------------------------------------------------------------------------------------------------------------------------------\n",
    "batch_size: Tahminler sırasında kullanılacak veri kümesi boyutu.\n",
    "--------------------------------------------------------------------------------------------------------------------------------------\n",
    "use_tpu: TPU (Tensor Processing Unit) kullanılıp kullanılmayacağını belirler. True ise TPU, False ise GPU/CPU kullanılır.\n",
    "--------------------------------------------------------------------------------------------------------------------------------\n",
    "master: TPU kullanılıyorsa, TPU'nun ana makinesinin adresi.\n",
    "---------------------------------------------------------------------------------------------------------------------------------------\n",
    "num_tpu_cores: TPU kullanılacaksa, toplam TPU çekirdek sayısını belirtir.\n",
    "-----------------------------------------------------------------------------------------------------------------------------------------\n",
    "use_one_hot_embeddings: TPUs'da genellikle True olarak ayarlanır çünkü bu, tf.one_hot fonksiyonunu kullanarak embedding lookup işlemlerini hızlandırır. GPU/CPU kullanılıyorsa False tercih edilir.\"\"\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "t5 Modeli"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "from dotenv import load_dotenv\n",
    "import os \n",
    "# Load model directly\n",
    "from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n",
    "\n",
    "\n",
    "#tokenizer ve modelin yüklenmesi\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"google/flan-t5-small\")\n",
    "model = AutoModelForSeq2SeqLM.from_pretrained(\"google/flan-t5-small\")\n",
    "prompt = \"Write an article about Machine Learning in Healthcare focusing on Introduction to ML and Applications in Healthcare.\"\n",
    "#api anahtarını çevresel değişken al\n",
    "api_key= os.getenv('HUGGINGFACE_API_KEY')\n",
    "#env dosyasını yükleme\n",
    "load_dotenv()\n",
    "\n",
    "#---------------------------------------------------------------------------------\n",
    "if api_key is None:\n",
    "    raise ValueError(\"Apı anahtarı .env dosyasında bulunamadı\")\n",
    "\n",
    "# Başlıkları oluştur\n",
    "headers = {\"Authorization\": f\"Bearer {api_key}\"}\n",
    "\n",
    "inputs=tokenizer(prompt, return_tensors=\"pt\")\n",
    "input_sequence = \"[CLS] Machine Learning in Healthcare [SEP] Introduction to ML [SEP] Applications in Healthcare [SEP] machine learning, healthcare, AI [SEP]\"\n",
    "#deneme data parçası\n",
    "data = {\n",
    "    \"title\": \"Machine Learning in Healthcare\",\n",
    "    \"sub_headings\": [\"Introduction to ML\", \"Applications in Healthcare\"],\n",
    "    \"keywords\": [\"machine learning\", \"healthcare\", \"AI\"]\n",
    "}\n",
    "\n",
    "# Girdiyi oluşturma\n",
    "prompt = (\n",
    "    f\"Title: {data['title']}\\n\"\n",
    "    f\"Sub-headings: {', '.join(data['sub_headings'])}\\n\"\n",
    "    f\"Keywords: {', '.join(data['keywords'])}\\n\"\n",
    "    f\"Content: {input_sequence}\\n\"\n",
    "    \"Please generate a detailed article based on the above information.\"\n",
    ")\n",
    "\n",
    "#metin üretimi \n",
    "output_sequences = model.generate(\n",
    "    inputs['input_ids'],\n",
    "    max_length=300,  # Üretilecek metnin maksimum uzunluğu\n",
    "    min_length=150,  # Üretilecek metnin minimum uzunluğu\n",
    "    num_return_sequences=1,  # Döndürülecek metin sayısı\n",
    "    do_sample=True,  # Örneklemeye izin ver\n",
    "    top_k=50,  # Top-k sampling kullan\n",
    "    top_p=0.95,  # Top-p sampling kullan\n",
    "    repetition_penalty=1.2,  # Anlamsız tekrarları önlemek için ceza\n",
    "    eos_token_id=tokenizer.eos_token_id  # Tam cümlelerin oluşturulmasını sağla\n",
    ")\n",
    "\n",
    "\n",
    "# Üretilen metni token'lardan çözüp string'e çevir\n",
    "generated_text = tokenizer.decode(output_sequences[0], skip_special_tokens=True)\n",
    "\n",
    "print(generated_text)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}