File size: 88,501 Bytes
b66c232
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
 
b66c232
 
 
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
 
 
 
 
 
 
 
 
 
 
 
 
2c996b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66c232
2c996b2
 
 
 
 
 
 
 
b66c232
2c996b2
 
 
 
 
 
 
 
b66c232
 
 
 
2c996b2
b66c232
2c996b2
b66c232
2c996b2
b66c232
 
 
 
2c996b2
 
 
 
b66c232
2c996b2
b66c232
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
{
 "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": 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",
    "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",
    "    # 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",
    "        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, stop_words=[]):\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
}