File size: 62,972 Bytes
e137e27
 
 
 
 
 
 
 
 
27b61df
3396b8b
e137e27
41b9932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715785a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41b9932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715785a
41b9932
715785a
 
 
e137e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b420f4
 
 
 
 
 
 
 
 
 
 
 
f4f88cc
7b420f4
f4f88cc
7b420f4
 
 
 
 
 
 
e137e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b420f4
41b9932
 
7b420f4
715785a
41b9932
 
 
7b420f4
 
 
0e26631
8981902
 
 
 
0e26631
 
 
5b83110
 
 
 
 
 
0e26631
 
 
5b83110
 
 
 
 
 
0e26631
 
 
 
 
7b420f4
146aa07
7b420f4
e137e27
 
 
 
 
 
 
41b9932
 
e04322e
 
 
7606154
3f9ccc2
 
 
 
e04322e
32c6d51
146aa07
7b420f4
e137e27
 
 
 
64c513d
e04322e
b8195ee
 
 
 
 
 
6084136
 
 
 
 
a810b7b
7b420f4
e137e27
7b420f4
 
e137e27
7b420f4
e137e27
7b420f4
e137e27
7b420f4
e137e27
6084136
 
 
 
 
a810b7b
e137e27
 
 
88c0211
 
 
 
6084136
88c0211
 
 
e137e27
 
 
88c0211
e137e27
88c0211
7b420f4
e137e27
 
 
a810b7b
88c0211
 
 
 
 
 
 
073687e
88c0211
 
 
 
 
073687e
7b420f4
e137e27
7b420f4
 
e137e27
7b420f4
e137e27
 
 
7b420f4
 
 
 
e137e27
 
 
7b420f4
88c0211
 
 
 
e137e27
 
 
88c0211
e137e27
88c0211
 
7b420f4
e137e27
 
 
7b420f4
 
 
 
e137e27
 
7b420f4
88c0211
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
7b420f4
 
 
 
 
 
88c0211
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
 
 
 
 
88c0211
 
 
 
 
 
e137e27
88c0211
7b420f4
e137e27
7b420f4
 
6263148
 
 
 
 
 
e137e27
 
7b420f4
e137e27
 
 
 
7b420f4
e137e27
7b420f4
e137e27
7b420f4
e137e27
 
7b420f4
e137e27
7b420f4
e137e27
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
 
 
 
7b420f4
e137e27
 
 
 
 
 
7b420f4
e137e27
 
 
 
7b420f4
e137e27
 
 
 
7b420f4
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6263148
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
 
 
 
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6263148
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
 
 
aa13e37
 
e137e27
aa13e37
 
e137e27
 
 
aa13e37
 
 
e137e27
aa13e37
465a4f0
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
 
 
26832b9
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
 
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465a4f0
aa13e37
 
 
465a4f0
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6263148
 
 
 
 
 
 
e137e27
aa13e37
7b420f4
7e7a96b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b420f4
ae1d7f9
 
 
aa13e37
 
ae1d7f9
 
 
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae1d7f9
 
e137e27
ae1d7f9
 
 
aa13e37
 
 
 
 
ae1d7f9
 
 
e137e27
 
 
 
 
ae1d7f9
7b420f4
e137e27
 
 
be782f3
e137e27
 
 
 
be782f3
e137e27
7b420f4
e137e27
be782f3
e137e27
 
be782f3
7b420f4
e137e27
 
 
 
ae1d7f9
 
 
aa13e37
 
 
 
 
 
 
 
 
 
ae1d7f9
 
e137e27
 
 
 
ae1d7f9
 
 
aa13e37
 
 
 
 
 
 
ae1d7f9
 
 
7b420f4
e137e27
 
 
 
ae1d7f9
 
 
aa13e37
 
 
 
 
ae1d7f9
 
 
 
 
aa13e37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae1d7f9
 
 
 
 
 
aa13e37
 
 
 
ae1d7f9
 
 
 
 
aa13e37
 
 
 
 
ae1d7f9
 
 
7b420f4
ae1d7f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
 
 
 
 
 
 
 
 
7e7a96b
 
 
 
 
 
 
 
7b420f4
26832b9
 
 
 
 
 
 
e137e27
7b420f4
e137e27
 
 
 
6263148
 
 
 
 
7b420f4
7e7a96b
 
 
ae1d7f9
 
 
 
 
7b420f4
e137e27
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
from fasthtml.common import *
from fasthtml.components import *
import json
import random
import string
from rich import print
import jsonlines
from data.url_blocklist import urls_high_matches, urls_false_positives
from data.non_web_urls import non_web_urls
from fasthtml.components import D_code
import pandas as pd

data_filtering_table_data = pd.DataFrame(
        {
            "Dataset": [
                "TxT360",
                "FineWeb",
                "RefinedWeb",
                "RedPajamaV2",
                "C4",
                "Dolma",
                "RedPajamaV1",
                "The Pile",
            ],
            "Data Reading": [
                "warc",
                "warc",
                "warc",
                "wet",
                "wet",
                "warc",
                "wet",
                "warc",
            ],
            "Text Extraction": [
                "trafilatura",
                "trafilatura",
                "trafilatura",
                "n/a",
                "n/a",
                "?",
                "n/a",
                "jusText",
            ],
            "URL Filtering": [
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "No",
                "No",
                "No",
                "No",
            ],
            "Language Identification": [
                "fastText",
                "fastText",
                "fastText",
                "fastText",
                "langdetect",
                "fastText",
                "fastText",
                "pycld2",
            ],
            "Line Removal": [
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "No",
                "No",
            ],
            "PII Filtering": [
                "Yes",
                "Yes",
                "No",
                "No",
                "No",
                "Yes",
                "No",
                "No",
            ],
            "Exact Deduplication": [
                "Bloom Filter",
                "n/a",
                "ExactSubStr",
                "Bloom Filter",
                "n/a",
                "Bloom Filter",
                "n/a",
                "n/a",
            ],
            "Fuzzy Deduplication": [
                "Global",
                "Local",
                "Local",
                "Local",
                "Local",
                "Local",
                "Local",
                "Global",
            ],
        }
)
table_html_filter_data = data_filtering_table_data.to_html(index=False, border=0)
table_div_filter_data = Div(NotStr(table_html_filter_data), style="margin: 40px;")


qf_filtering_table_data = pd.DataFrame(
        {
            "Dataset": [
                "TxT360",
                "FineWeb",
                "RefinedWeb",
                "RedPajamaV2",
                "C4",
                "Dolma",
                "RedPajamaV1",
                "The Pile",
            ],
            "QF: ML-based": [
                "No",
                "No",
                "No",
                "Yes",
                "No",
                "No",
                "Yes",
                "Yes",
            ],
            "QF: Repition-based": [
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "No",
                "Yes",
                "No",
                "No",
            ],
            "QF: Correction-based": [
                "Yes",
                "Yes",
                "Yes",
                "No",
                "No",
                "No",
                "No",
                "No",
            ],
            "QF: Gopher Rules": [
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "No",
                "Yes",
                "No",
                "No",
            ],
            "QF: C4 Rules": [
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "Yes",
                "No",
                "No",
            ],
    }
)
table_html_qf_filter_data = qf_filtering_table_data.to_html(index=False, border=0)
table_div_qf_filter_data = Div(NotStr(table_html_qf_filter_data), style="margin: 40px;")


def DVS(
    left,
    header,
):
    col1 = Div(
        Pre(
            json.dumps(left, indent=4, ensure_ascii=False),
            style="white-space: pre-wrap; word-break: break-all;",
        ),
        style="float: left; overflow-x: auto;",
    )

    data_display = Div(
        col1,
        style="overflow: auto; clear: both; height: 200px; border: 1px solid #ccc; padding: 20px;",
    )
    return Div(H3(header), data_display, style="margin-top: 10px;")


def DV(
    left_file,
    doc_id,
    header,
    target: str = None,
):
    if target is None:
        target = "".join(random.choices(string.ascii_lowercase, k=8))

    if left_file.endswith("jsonl"):
        left = [x for x in jsonlines.open(left_file)]
    else:
        left = json.load(open(left_file, encoding="utf-8"))
    max_doc_id = len(left) - 1
    slider = Input(
        type="range",
        name=f"doc_id_{target}",
        min="0",
        max=str(max_doc_id),
        value=str(doc_id),
        hx_get=f"/webdata/{target}",
        hx_target=f"#{target}",
        hx_trigger="change",
        hx_swap="innerHTML",
        hx_vals=json.dumps({"left_file": f"{left_file}", "header": f"{header}"}),
    )

    form = Div(
        H3(header),
        Label(
            "Data sample: ", slider, f"{doc_id} of {max_doc_id}", cls="plotly_slider"
        ),
        cls="plotly_input_container",
        style="padding: 20px;",
    )

    col1 = Div(
        Pre(
            json.dumps(left[doc_id], indent=4, ensure_ascii=False),
            style="white-space: pre-wrap; word-break: break-all;",
        ),
        style="float: left; overflow-x: auto;",
    )

    data_display = Div(
        col1,
        style="overflow: auto; clear: both; height: 600px; border: 1px solid #ccc; padding: 20px;",
    )
    return Div(form, data_display, style="margin-top: 10px;", id=target)


def DV2(
    left_file,
    right_file,
    doc_id,
    target: str = None,
):
    if target is None:
        target = "".join(random.choices(string.ascii_lowercase, k=8))

    left = json.load(open(left_file, encoding="utf-8"))
    right = json.load(open(right_file, encoding="utf-8"))
    max_doc_id = len(left) - 1

    slider = Input(
        type="range",
        name=f"doc_id_{target}",
        min="0",
        max=str(max_doc_id),
        value=str(doc_id),
        hx_get=f"/webdata/{target}",
        hx_target=f"#{target}",
        hx_trigger="change",
        hx_swap="innerHTML",
        hx_vals=json.dumps(
            {"left_file": f"{left_file}", "right_file": f"{right_file}"}
        ),
    )

    form = Div(
        Label(
            "Data sample: ", slider, f"{doc_id} of {max_doc_id}", cls="plotly_slider"
        ),
        cls="plotly_input_container",
        style="padding: 20px;",
    )

    col1 = Div(
        H3("Raw format", style="margin-top: 0px;"),
        Pre(
            json.dumps(left[doc_id], indent=4, ensure_ascii=False),
            style="white-space: pre-wrap; word-break: break-all;",
        ),
        style="width: 48%; float: left; overflow-x: auto;",
    )

    col2 = Div(
        H3("Extracted format", style="margin-top: 0px;"),
        Pre(
            json.dumps(right[doc_id], indent=4, ensure_ascii=False),
            style="white-space: pre-wrap; word-break: break-all;",
        ),
        style="width: 48%; float: right; overflow-x: auto;",
    )

    data_display = Div(
        col1,
        col2,
        style="overflow: auto; clear: both; height: 600px; border: 1px solid #ccc; padding: 20px;",
    )
    return Div(form, data_display, style="margin-top: 10px;", id=target)


def update(target: str, request):
    params = request.query_params
    print(params)
    doc_id = int(params.get(f"doc_id_{target}", 3))
    left_file = params.get("left_file")
    right_file = params.get("right_file")
    if left_file and right_file:
        return (
            DV2(
                left_file,
                right_file,
                doc_id,
                target,
            ),
        )
    else:
        return DV(
            left_file,
            doc_id,
            params.get("header"),
            target,
        )


dolma311 = """
words = text.split()
word_count = len(words)
character_count = sum(len(word) for word in words)
...
lines = text.split("\\n")
line_count = len(lines)
...
line_counts = Counter(lines)
attrs.fraction_of_duplicate_lines = sum(count for line, count in line_counts.items() if count > 1) / max(
    line_count, 1
)
attrs.fraction_of_characters_in_duplicate_lines = sum(
    len(line) * count for line, count in line_counts.items() if count > 1
) / max(character_count, 1)
"""


def web_data():
    return Div(
        Div(
        H2("Common Crawl Snapshot Processing"),
        H3("What This Section Contains"),
        P("This section provides a complete discussion on the filtering applied to the 99 Common Crawl snapshots that comprise the web data section of TxT360. The section is split into the following topic areas: "),
        Ul(
            Li("Web Data Processing Summary", style = "margin-bottom: 5px"),
            Li("Document Preperation", style = "margin-bottom: 5px"),
            Li("Line-Level Filtering", style = "margin-bottom: 5px"),
            Li("Local Deduplication", style = "margin-bottom: 5px"),
            Li("Each section is complete with code and comparisons to Dolma, DataTrove, and/or RedPajama-V-2", style = "margin-bottom: 5px"),
        ),
        ),
        
        Div(
            H2("Common Crawl Data Processing Summary"),
            P(
                "To generate a high-quality dataset from large-scale webpages, we have investigated the processing steps used by the community and made our choices based on careful manual inspection. Starting from ",
                A("Common Crawl", href="https://commoncrawl.org/"),
                ", our process can be summarized as five main steps: document preparation, line-level removal, document-level filtering, deduplication and PII removal.",
            ),
            style="margin-top: 20px;",
        ),
        Div(
            Ul(
                Li(
                    A(
                        "Raw Documentation",
                        href="https://drive.google.com/drive/folders/1mIJ-Zx8tRhohFdj4ByMToNz1u_9Saa8W?usp=drive_link",
                    )
                ),
                Li(
                    A(
                        "Github link of Web Data Pipeline",
                        href="https://github.com/CIAI-LLM/WebDataProcessing.git",
                    )
                ),
            ),
            style="""
            background-color: #d4edda; /* Light green background */
            border: 1px solid #c3e6cb; /* Green border */
            border-radius: 5px;
            padding: 15px 15px 0px 15px;
        """,
        ),
        H3("TxT360 CommonCrawl Filtering vs Other Pretraining Datasets")
        P("The following section provides explicit details covering the reasoning and decisions behind each of the filters we applied. The table below provides a high-level comparison of TxT360's filtering compared to other commonly used pretraining datasets."),
        table_div_filter_data,
        P("The table below provides a comparison of the quality filters that have been applied to each dataset."),
        table_div_qf_filter_data,
        P("Our filtering rate is illustrated below. Before deduplication, our filtering rate is comparable to RefinedWeb. During global deduplication, we removed approximately 85.89% of the data, significantly higher than previous works, indicating a large number of duplicates across dumps. "),
        Img(src="images/filter_rate.jpg", height = "300", width = "600" ),
        P("Note: All percentages are based on the number of documents. The gray bars represent the relative percentages of removed documents at each step, while the colorful bars represent the percentages of retained documents relative to the total number of documents in the raw Common Crawl."),
        H3("TxT360 Filter Summary")
        P("This section provides highlevel details into the filtering that is applied to CommonCrawl in TxT360. Each decision listed is discussed in detail further on in this section.")
        P("We adopt rules from RefinedWeb [1] to remove lines if they satisfy any of the following criteria:"),
        Ul(
            Li("the line is only composed of uppercase characters", style = "margin-bottom: 5px"),
            Li("the line is only composed of numerical characters", style = "margin-bottom: 5px"),
            Li("the line matches the pattern “r'^\d+\s+likes$", style = "margin-bottom: 5px"),
            Li("the line only contains one word.", style = "margin-bottom: 5px"),
        ),
        P("We summarize other statistics-based rules originated from Gopher [7] in this section. The statistics can be used include:"),
        Ul(
            Li("the word count in the document", style = "margin-bottom: 5px"),
            Li("the mean word length", style = "margin-bottom: 5px"),
            Li("the number of sentences", style = "margin-bottom: 5px"),
            Li("the symbol-to-word ratio", style = "margin-bottom: 5px"),
            Li("the fraction of alphabetic words", style = "margin-bottom: 5px"),
            Li("and the number of stop words", style = "margin-bottom: 5px"),
        ),
        P("Specifically, we remove any document which satisfies any of the following criteria:"),
        Ul(
            Li("it contains less than 50 words or more than 100,000 words", style = "margin-bottom: 5px"),
            Li("its mean word length is outside the range of 3 to 10", style = "margin-bottom: 5px"),
            Li("it contains less than 3 sentences", style = "margin-bottom: 5px"),
            Li("its symbol-to-word ratio is greater than 0.1", style = "margin-bottom: 5px"),
            Li("the words that contain at least one alphabetic character are less than 80% of the whole words", style = "margin-bottom: 5px"),
            Li("it contains less than two of the stop words (the, be, to, of, and, that, have, with", style = "margin-bottom: 5px"),
        ),

        P("Following C4, we remove any page where the phrase “lorem ipsum” appears since some pages have placeholder “lorem ipsum” text."),
        
        
        H2("1. Document Preparation"),
        
        H3("1.1 Text Extraction"),
        P("""
        Common Crawl provides webpage texts via two formats: WARC (Web ARChive format) and WET (WARC Encapsulated Text). 
        WARC files contain the raw data from the crawl, which store the full HTTP response and request metadata. 
        WET files contain plaintexts extracted by Common Crawl. In line with previous works ([1], [2], [3], [4]), 
        we found WET files to include boilerplate content like navigation menus, ads, and other irrelevant texts. 
        Accordingly, our pipeline starts from raw WARC files, reads with the warcio library, and extracts texts using trafilatura.
        """),
        P("We directly read WARC files instead of WET files and extracted text using Trafilatura. Similar to RefinedWeb, we avoid using Machine Learning (ML)-based metrics for filtering documents to prevent bias introduced by ML models. Importantly, we apply global deduplication across the entire dataset, whereas previous works only use local deduplication. Note that although The Pile also employed global deduplication on its web data (Pile-CC), this accounted for just 0.6\% of 74 snapshots."),

        Details(
                Summary("Text Extraction Examples"),
                DV2("data/sample_wet.json", "data/sample_warc.json", 3),
            style="""
            background-color: #D3D3D3; /* Light grey background */
            border: 1px solid #949494; /* Grey border */ 
            border-radius: 12px;
            """, #https://colors.muz.li/palette/d3d3d3/949494/d3d3d3/d3d3d3/949494
            ),
        #DV2("data/sample_wet.json", "data/sample_warc.json", 3),
        
        H3("1.2 Language Identification"),
        P("""
        After text extraction, the non-English texts are then filtered out by fastText language identifier with a threshold of 0.65.
        This step removes over 60% of the whole data.
        """),
    
       
        Details(
            Summary("Non-English Documents"),
            DV("data/sample_non_en.json", 3, "Sample documents that are classified as non-English"),
        ),
        
        #DV("data/sample_non_en.json", 3, "Sample documents that are classified as non-English"),

        Details(
            Summary("English Documents Scoring Lower than 0.65"),
            DV("data/sample_en_low.json", 3, "Sample documents that are classified as English but with score less than 0.65"),
        ),
        
        H3("1.3 URL Filtering"),
        P("""
        The following section details the decisions behind utilizing the UT1 blocklist. We chose to use the UT1 blocklist as a simple method for filtering
        out potentially harmful content such as adult content. We also excluded URLs that contained the digital version of the curated curated data (e.g. wikipedia.org) to avoid duplication.
        """),
        H3("1.3.1 URL Blocklist"),
        P("""
        Following RefinedWeb [3], we manually inspected the UT1 blocklist to reduce false positives like news 
        articles, sex education, technical blogs, etc. Specifically, we randomly took 903M URLs and matched them with
        4.6M domain names in the UT1 blocklist. Of note, 24 URLs were detected with more than 4k matches and are shown below.
        """),

        Details(
            Summary("24 URL domains with more than 4k matches"),
            DVS(urls_high_matches, "24 URL domains with more than 4k matches"),
        ),
        
        P("""
        We manually removed the following 6 domains from the UT1 blocklist so that they will not be removed from our dataset.
        """),
        Details(
            Summary("6 url domains that are removed from the blocklist"),
            DVS(urls_false_positives, "6 url domains that are removed from the blocklist"),    
        ),
        
        Details(
            Summary("Sample documents whose urls are blocked by the refined url blocklist"),
            DV(
            "data/bad_url_doc.jsonl",
            3,
            "Sample documents whose urls are blocked by the refined url blocklist",
            ),    
        ),
        
        H3("1.3.2 Excluded High Quality Sources"),
        P("""
        To avoid duplication with our high-quality curated datasets, we exclude the following domains from our dataset.
        """),
        
        Details(
            Summary("curated url domains that are excluded from our dataset"),
            DVS(
                non_web_urls,
                "curated url domains that are excluded from our dataset",
            ),
        ),

        Details(
            Summary("Sample documents whose urls are in our curated url domain list"),
            DV("data/sample_url_exclusion.json", 0, "Sample documents whose urls are in our curated url domain list"), 
        ),
         
            
        H2("2. Line-Level Removal"),
        P("""
        Before filtering low-quality documents, we perform the line-level removal to remove low-quality lines. 
        This ensured that computing quality signals would align with the final kept texts.
        """),
        H3("Terminal Punctuation"),
        P("""
        The terminal punctuation has been used in C4 [5] and Dolma [6] to remove lines that do not end with a terminal
        punctuation mark (i.e., “.”, “?”, “!”, or “"”). However, we found it could be too aggressive to remove these
        lines, especially when the text extraction tool “trafilatura”. 
        """),
        P("""
        For instance, in the CommonCrawl file
        CC-MAIN-20230126210844-20230127000844-00000.warc.jsonl, the terminal punctuation rule led to the removal
        of 56,292 additional lines, resulting in the complete exclusion of 2,203 documents from a total of 13,560
        documents (16.25%). Accordingly, we choose to not use terminal punctuation as a signal to remove lines.
        """)

        Details(
            Summary("Sample documents with lines that are removed by the rule of terminal punctuation"),
            DV(
            "data/sample_terminal_punc.json",
            0,
            "Sample documents with lines that are removed by the rule of terminal punctuation",
            ), 
        ),
        
        
        H3('2.1 Word "Javascript"'),
        P("""
        In C4 [5], the authors remove any line with the word "Javascript" since they found that many of the scraped
        pages contained warnings stating that Javascript should be enabled. However, this filtering strategy is too
        strict, which will filter out many lines that are really talking about “Javascript”. 
        """),
        P("""
        In our pipeline, we
        propose to refine the strategy by adding one more keyword to the word "javascript" to avoid false positives.
        The additional keyword could be any one of “enable” / “disable” / “require” / “activate” / “browser”.
        """)
        Details(
            Summary("Sample documents that are removed by original C4 javascript rule but are kept after our refinement"),
            DV(
                "data/sample_java.jsonl",
                0,
                "Sample documents that are removed by original C4 javascript rule but are kept after our refinement",
            ),
        ),
        H3("2.2 Other Rules from RefinedWeb"),
        P("""
        We also adopt rules from RefinedWeb [3] to remove lines if they satisfy any of the following criteria:
        """),
        Ul(
            Li("The line is only composed of uppercase characters,", style = "margin-bottom: 5px"),
            Li("the line is only composed of numerical characters", style = "margin-bottom: 5px"),
            Li("the line matches the pattern “r'^\d+\s+likes$", style = "margin-bottom: 5px"),
            Li("the line only contains one word.", style = "margin-bottom: 5px"),
        ),
        Details(
            Summary("Sample documents with lines that are removed by the RefinedWeb rules"),
            DV(
                "data/sample_refinedweb_line.json",
                0,
                "Sample documents with lines that are removed by the RefinedWeb rules",
            ),
        ),
        H3("2.3 Toxic Lines"),
        P("""
        When doing manual inspection on the data, we found that there are some adult ads in the beginning or end of the 
        document (with a sample shown below), which are hard to remove via document-level filtering strategies. Inspired 
        by this, we develop line-level detoxification using a bad word list from LDNOOBW (+ rule: word length < 10 + the 
        line is in the first 3 lines or in the last 3 lines) to remove toxic lines. Specifically, we do not only consider 
        the bad words from English but also consider the bad words from other languages.
        """),
        Details(
            Summary("Sample documents with toxic lines"),
            DVS(
                json.load(open("data/toxic_lines.json")),
                "Sample documents with toxic lines",
            ),
        ),
        
        H2("3. Document-Level Filtering"),
        P("""
        In this section, we introduce each quality signal used to filter out low-quality documents.
        """),
        Details(
            Summary("Overview of all the quality signals that are used for filtering"),
            DVS(
                json.load(open("data/all_signals.json")),
                "Overview of all the quality signals that are used for filtering",
            ),
        ),
        P("""Similar to previous sections, we will present sample documents filtered out by the given quality signals. 
        Most quality signals were initially introduced by Gopher [2] and subsequently adopted by later 
        studies ([3], [6], [4]). However, we observed that, despite following the same descriptions, the implementation 
        of each quality signal can vary significantly among different dataset pipelines, resulting in disparate 
        outcomes for the same quality signals.
        In our pipeline, we referenced earlier implementations that were publicly available such as Dolma [6], DataTrove [4], 
        and RedPajama V2 [7], and selected the most suitable method based on manual inspections.
        """),
        H3("3.1 Repetition-based Heuristics"),
        P("""
        Many documents contain repeated sequences, potentially due to crawling errors or low-quality sources. In line with previous 
        work ([2], [3], [6]), we choose to remove any document with excessive line, paragraph, or n-gram repetitions.
        """),
        H3("3.1.1 Fraction of (Characters in) Repeated Lines"),
        P("""
        Following Gopher [2], we remove documents containing mupltiple, short duplicate passages, as well as those with few, 
        but longer duplicate passages. To achieve this goal, we calculate over the document both the fraction of passages 
        that are duplicates, and the fraction of characters contained within those duplicated passages.
        """),
        Details(
            Summary("Implementations from Dolma"),
            D_code("""
            words = text.split()
            word_count = len(words)
            character_count = sum(len(word) for word in words)
            ...
            lines = text.split("\n")
            line_count = len(lines)
            ...
            line_counts = Counter(lines)
            attrs.fraction_of_duplicate_lines = sum(count for line, count in line_counts.items() if count > 1) / max(
                line_count, 1
            )
            attrs.fraction_of_characters_in_duplicate_lines = sum(
                len(line) * count for line, count in line_counts.items() if count > 1
            ) / max(character_count, 1)
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from DataTrove"),
            D_code("""
            def find_duplicates(x: list[str]) -> tuple[int, int]:
                unique_x = set()
                duplicate_chars = 0
                duplicate_elements = 0
                for element in x:
                    if element in unique_x:
                        duplicate_chars += len(element)
                        duplicate_elements += 1
            
                    else:
                        unique_x.add(element)
                return duplicate_elements, duplicate_chars
            ...
            self.paragraph_exp = re.compile(r"\n{2,}")
            self._line_splitter = re.compile("\n+")
            ...
            paragraphs = self.paragraph_exp.split(text.strip())
            paragraphs_duplicates, char_duplicates = find_duplicates(paragraphs)
            if self.dup_para_frac and paragraphs_duplicates / len(paragraphs) > self.dup_para_frac:
                return False, "dup_para_frac"
            if self.dup_para_char_frac and char_duplicates / len(text) > self.dup_para_char_frac:
                return False, "dup_para_char_frac"
            
            lines = self._line_splitter.split(text)
            line_duplicates, char_duplicates = find_duplicates(lines)
            if self.dup_line_frac and line_duplicates / len(lines) > self.dup_line_frac:
                return False, "dup_line_frac"
            if self.dup_line_char_frac and char_duplicates / len(text) > self.dup_line_char_frac:
                return False, "dup_line_char_frac"
            """, block="block", language="python"),
        ),
        P("""
        After evaluating the implementations of Dolma and DataTrove (note: RedPajama V2 does not implement these two quality 
        signals), we have made the following decisions:
        """),
        H3("Passage Separation"),
        P("""
        Our manual review of the data revealed that documents extracted using trafilatura do not feature more than one newline 
        symbol separating passages. Testing the splitting pattern "\\n(2,)" on 10,000 sample documents resulted in no more than 
        one split. Consequently, we decided to disregard the distinction between lines and paragraphs in our implementation, 
        opting instead to use a single newline symbol to segment the text into passages.
        """),
        H3("First Occurrence"),
        P("""
        In line with DataTrove's implementation, we chose to exclude the first occurrence. This more conservative strategy 
        helps retain a larger number of documents.
        """),
        H3("Character Count"),
        P("""
        We adjusted the method in Dolma for counting characters within lines by excluding whitespace. This modification 
        ensures consistency with the overall document character count calculation.
        """),
        H3("TxT360 Implementation"),
        Details(
            Summary("TxT360 Implementation"),
            D_code("""
            words = text.split()
            word_count = len(words)
            character_count = sum(len(word) for word in words)
            ...
            lines = text.split("\n")
            line_count = len(lines)
            
            line_counts = Counter(lines)
            attrs.fraction_of_duplicate_lines = (
                sum((count - 1) for line, count in line_counts.items() if count > 1) / line_count
            )
            attrs.fraction_of_characters_in_duplicate_lines = (
                sum(sum(len(w) for w in line.split()) * (count - 1) for line, count in 
                line_counts.items() if count > 1) / character_count
            """, block="block", language="python"),
        ),        
        Details(
            Summary("Sample documents filtered by excessive line repetitions / characters in repeated lines"),
            DV(
                "data/repeat_line_frac.jsonl",
                0,
                "Sample documents filtered by excessive line repetitions / characters in repeated lines",
            ),
        ),
        H3("3.1.2 Fraction of Characters in the Most Common N-grams (n=2,3,4)"),
        P("""
        Following Gopher [2], we remove documents with a high portion of n-grams. For each n ∈ (2, 3, 4), we calculate the 
        fraction of characters contained within the most frequently-occurring n-gram.
        """),
        Details(
            Summary("Implementations from Dolma"),
            D_code("""
            def all_ngram_counts(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
                return [(n, Counter(list(zip(*[words[i:] for i in range(n)])))) for n in range(2, 11)]
            ...
            all_counts = all_ngram_counts(words)
            
            count_most_common_ngrams = (2, 3, 4)
            for n, ngram_counts in all_counts:
                if not ngram_counts:
                    continue
                if n in count_most_common_ngrams:
                    most_common_ngram, count = ngram_counts.most_common(1)[0]
                    value = count * sum(len(w) for w in most_common_ngram) / max(character_count, 1)
                    attrs.fraction_of_characters_in_most_common_ngram.append((n, value))
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from RedPajama-V2"),
            D_code("""
                class Base_RPS_Frac_Chars_In_Top_NGram(RPSBase):  # noqa
                    ## Base class for calculating the fraction of characters in the top N-gram. This operates on the lower-cased, punctation removed content.
                    NGRAM_SIZE: int = None
                
                    __slots__ = []
                
                    def __call__(self, document: Document) -> SignalType:
                        if self.NGRAM_SIZE is None:
                            raise NotImplementedError(
                                "NGRAM_SIZE must be set in the subclass"
                            )
                
                        # get the most common ngram
                        most_common_ngram = Counter(
                            # fetch the ngrams from the document if they exist, otherwise
                            # compute them
                            getattr(document, f"norm_self.NGRAM_SIZEgrams", None)
                            or
                            form_ngrams(iter(document.normalized_words), self.NGRAM_SIZE)
                        ).most_common(1)
                
                        if len(most_common_ngram) == 0:
                            return [(0, len(document), 0.0)]
                
                        ngram, count = most_common_ngram[0]
                
                        if count <= 1:
                            return [(0, len(document), 0.0)]
                
                        total_chars = sum(len(w) for w in document.normalized_words)
                        score = sum(len(w) for w in ngram) * count / total_chars
                        score = round(score, PRECISION)
                        return [(0, len(document), score)]
            """, block="block", language="python"),
        ),
        
        Details(
            Summary("Implementations from DataTrove"),
            D_code("""
            def get_n_grams(words: list[str], n: int) -> list[str]:
                return [" ".join(words[i : i + n]) for i in range(len(words) - n + 1)]
            
            def find_top_duplicate(x: list[str]) -> int:
                counter = Counter()
                for element in x:
                    counter[element] += 1
                top_n_gram = counter.most_common(1)[0]
                return len(top_n_gram[0]) * top_n_gram[1]                
            ...               
            for n, n_frac in self.top_n_grams:
                n_grams = get_n_grams(words, n)
                if not n_grams:
                    continue
                top_char_length = find_top_duplicate(n_grams)
                if top_char_length / len(text) > n_frac:
                    return False, f"top_n_gram"
            """, block="block", language="python"),
        ),
        P("""
        There are almost no contradictions between each implementations of fractions of characters in the most common 
        n-gram. The main process involves counting the occurrences of each n-gram and selecting the most common one. The 
        fraction is then determined by dividing the number of characters in the most common n-gram by the total number of 
        characters. One minor difference is that Dolma and DataTrove calculate the fraction of the most common n-gram even 
        if it only appears once, while RedPajama V2 skips this case.
        We choose to follow Dolma and DataTrove by not skipping cases where the most common n-gram occurs only once. 
        In practice, documents affected by this rule — where the most common n-gram exceeds a given threshold and occurs 
        only once — tend to be short.
        """),
        Details(
            Summary("TxT360 Implementation"),
            D_code("""
            def all_ngram_counts_new(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
                return [(n, list(zip(*[words[i:] for i in range(n)]))) for n in range(2, 11)]
            ...
            all_counts = all_ngram_counts_new(words)
            count_most_common_ngrams = (2, 3, 4)
            for n, ngram_counts in all_counts:
                if not ngram_counts:
                    continue
                if n in count_most_common_ngrams:
                    most_common_ngram, count = Counter(ngram_counts).most_common(1)[0]
                    value = count * sum(len(w) for w in most_common_ngram) / character_count
                    attrs.fraction_of_characters_in_most_common_ngram.append((n, value))
            """, block="block", language="python"),
        ),
        Details(
            Summary("Sample documents filtered by the fraction of characters in the most common n-grams (n=2,3,4)"),
            DV(
                "data/sample_top_ngram.json",
                0,
                "Sample documents filtered by the fraction of characters in the most common n-grams (n=2,3,4)",
            ),
        ),
        H3("3.1.3 Fraction of Characters in Duplicated N-grams (n=5,...,10)"),
        P("""
        Following Gopher [2], we remove documents with a high portion of n-grams. For each n ∈ (5, ..., 10), we calculate the 
        fraction of characters contained within all duplicate n-grams, taking care not to count characters that occur in 
        overlapping n-grams more than once.
        """),
        Details(
            Summary("Implementations from Dolma"),
            D_code("""
            def all_ngram_counts(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
                return [(n, Counter(list(zip(*[words[i:] for i in range(n)])))) for n in range(2, 11)]
            ...
            all_counts = all_ngram_counts(words)
            for n, ngram_counts in all_counts:
                if not ngram_counts:
                    continue
                if n in count_most_common_ngrams:
                    ...
                else:
                    ng_char_count = sum(count * sum(len(w) for w in ng) for ng, count in ngram_counts.items())
                    value = sum(
                        count * sum(len(w) for w in ng) for ng, count in ngram_counts.items() if count > 1
                    ) / max(ng_char_count, 1)
                    attrs.fraction_of_characters_in_duplicate_ngrams.append((n, value))
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from RedPajama-V2"),
            D_code("""
            class Base_RPS_Frac_Chars_In_Dupe_NGrams(RPSBase):  # noqa
                ## Base class for calculating the fraction of characters in duplicate word N-grams. This operates on the lower-cased, punctation removed content. The function also ensures that characters in overlapping ngrams are only counted once.
                NGRAM_SIZE: int = None
                __slots__ = []
            
                def __call__(self, document: Document) -> SignalType:
                    if self.NGRAM_SIZE is None:
                        raise NotImplementedError(
                            "NGRAM_SIZE must be set in the subclass"
                        )
            
                    if len(document.normalized_words) < self.NGRAM_SIZE:
                        return [(0, len(document), 0.0)]
            
                    # fetch the ngrams from the document if they exist, otherwise
                    # compute them
                    doc_n_grams = (
                            getattr(document, f"norm_self.NGRAM_SIZEgrams", None)
                            or
                            tuple(form_ngrams(
                                iter(document.normalized_words), self.NGRAM_SIZE
                            ))
                    )
            
                    # keep only ngrams which occur at least twice
                    ngram_dupes = 
                        ngram for ngram, count in Counter(doc_n_grams).items() if count > 1
            
            
                    duplicated_grams = np.zeros(len(document.normalized_words), dtype=int)
            
                    i = 0
                    for ngram in doc_n_grams:
                        if ngram in ngram_dupes:
                            duplicated_grams[i: i + self.NGRAM_SIZE] = 1
            
                        i += 1
            
                    word_lengths = np.array(list(map(len, document.normalized_words)))
                    chars_duped = np.sum(word_lengths * duplicated_grams)
                    total_chars = np.sum(word_lengths)
            
                    if total_chars == 0:
                        return [(0, len(document), 0.0)]
            
                    score = float(chars_duped / total_chars)
                    score = round(score, PRECISION)
                    return [(0, len(document), score)]
            """, block="block", language="python"),
        ),
        
        Details(
            Summary("Implementations from DataTrove"),
            D_code("""
            def find_all_duplicate(words: list[str], n: int) -> int:
                n_words = len(words)
                unique = set()
                repeated_chars, idx = 0, 0
                while idx < n_words - n + 1:
                    n_gram = "".join(words[idx : idx + n])
                    if n_gram in unique:
                        repeated_chars += len(n_gram)
                        idx += n
                    else:
                        unique.add(n_gram)
                        idx += 1
                assert repeated_chars <= len("".join(words))
                return repeated_chars
            ...
            for n, n_frac in self.dup_n_grams:
                n_duplicates_char = find_all_duplicate(words, n)
                if n_duplicates_char / len(text) > n_frac:
                    return False, f"duplicated_n_grams"
            """, block="block", language="python"),
        ),
        P("""
        For the computation of fraction of characters in duplicate n-gram, Dolma uses the number of characters in all 
        n-grams (with overlapping) as the denominator, and uses the number of characters in all duplicated n-grams 
        (with overlapping) as the numerator."""),
        P("""RedPajama V2 uses the number of all characters in (the words of) the document 
        (without overlapping) as the denominator, and uses the number of characters that are recognized as part of the 
        duplicate n-gram as the numerator."""),
        P("""Datatrove uses the number of all characters in the document (including white 
        spaces, without overlapping) as the denominator, and uses the number of characters that are recognized as 
        duplicate n-gram as the numerator. However, there is a mismatch in DataTrove’s calculation, as the number of 
        characters in the duplicated n-grams excludes white spaces, while the total character count of the document 
        does not."""),
        
        P("""We decided to use the RedPajama V2 implementation but skip the 1st occurrence of the duplicate n-gram.
        """),
        Details(
            Summary("TxT360 Implementation"),
            D_code("""
            def get_dup_ngram_frac(n, doc_n_grams, text):
                # fetch the ngrams from the document if they exist, otherwise compute them
                # doc_n_grams = list(zip(*[words[i:] for i in range(n)]))
            
                duplicated_grams = np.zeros(len(text.split()), dtype=int)
            
                unique_ngrams = set()
            
                for i, ngram in enumerate(doc_n_grams):
                    if ngram in unique_ngrams:
                        duplicated_grams[i: i + n] = 1
                    else:
                        unique_ngrams.add(ngram)
            
                word_lengths = np.array(list(map(len, text.split())))
                chars_duped = np.sum(word_lengths * duplicated_grams)
                total_chars = np.sum(word_lengths)
            
                return float(chars_duped / total_chars)
            
            def all_ngram_counts_new(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
                return [(n, list(zip(*[words[i:] for i in range(n)]))) for n in range(2, 11)]
            ...
            all_counts = all_ngram_counts_new(words)
            count_most_common_ngrams = (2, 3, 4)
            for n, ngram_counts in all_counts:
                if not ngram_counts:
                    continue
                if n in count_most_common_ngrams:
                    ...
                else:
                    score = get_dup_ngram_frac(n, ngram_counts, text)
                    attrs.fraction_of_characters_in_duplicate_ngrams.append((n, score))
            """, block="block", language="python"),
        ),
        Details(
            Summary("An example to show the difference between above implementations"),
            P("""
            Considering n = 5 and the sample sentence:

            "word_a word_b word_c word_d word_e word_f word_g word_a word_b word_c word_d word_e word_f word_g word_a word_b word_c"
        
            In Dolma's implementation, there are 13 5-grams in total with 6 duplicated 5-grams. The resulting fraction of characters in duplicate 5-gram is 6/13.
            In RedPajama's V2 implementation, there are 17*6 characters in total and 14*6 characters that are contained in duplicate 5-grams. The fraction is 14/17.
            In DataTrove's implementation, there are 17*6 + 16(white spaces) characters in total and 10 duplicated 5-grams after excluding the first occurrence. The resulting fraction number is 10*6/(17*6+16).

            In our implementation, there are 17*6 characters in total with 10*6 characters that are duplicated after excluding the first occurence. This results in a fraction of 10/17.
            """),
        ),
        H5(
            "Sample Documents Filtered by the Fraction of Characters in Duplicated N-grams (n=5,...,10)"
        ),
        Details(
            Summary("Sample documents filtered by the fraction of characters in duplicated n-grams (n=5,...,10)"),
            DV(
                "data/sample_dup_ngram.json",
                0,
                "Sample documents filtered by the fraction of characters in duplicated n-grams (n=5,...,10)",
            ),
        ),
        H3("3.2 Line-wise Heuristics"),
        P("""
        Some line-wise information could also be helpful to distinguish low-quality and high-quality documents. Following 
        RefinedWeb [3], we remove the document if the corrected lines represent more than 5% of words. In line with previous 
        works ([2], [3], [6]), we remove the documents if more than 30% of the lines end with an ellipsis or more than 
        90% of lines start with a bullet point.
        """),
        Details(
            Summary("Ellipsis Symbol Identification Implemetations"),
            P("Dolma: "),
            D_code("""
            ELLIPSIS_SYMBOLS = ("…")
            """, block="block", language="python"),
            P("RedPajamaV2: "),
            D_code("""
            ELLIPSIS_SYMBOLS = ("...", "…")
            """, block="block", language="python"),
            P("DataTrove: "),
            D_code("""
            ELLIPSIS_SYMBOLS = ("...", "…")
            """, block="block", language="python"),
            P("TxT360: "),
            D_code("""
            ELLIPSIS_SYMBOLS = ("...", "…", "[...]", "[…]")
            """, block="block", language="python"),
        ),
        Details(
            Summary("Bullet Point Identification Implemetations"),
            P("Dolma: "),
            D_code("""
            BULLET_POINTS = ("*", "-"
            """, block="block", language="python"),
            P("RedPajamaV2: "),
            D_code("""
            BULLET_POINT_SYMBOLS = (
                "•",  # bullet point
                "‣",  # triangular bullet point
                "▶",  # black right pointing triangle
                "◀",  # black left pointing triangle
                "◦",  # white bullet point
                "■",  # black square
                "□",  # white square
                "▪",  # black small square
                "▫",  # white small square
                "–",  # en dash
            )
            """, block="block", language="python"),
            P("DataTrove: "),
            D_code("""
            BULLET_POINT_SYMBOLS = ("•" , "-")
            """, block="block", language="python"),
            P("TxT360: "),
            D_code("""
            BULLET_POINT_SYMBOLS = (
                "•",  # • bullet point
                "‣",  # ‣ triangular bullet point
                "▶",  # ▶ black right pointing triangle
                "◀",  # ◀ black left pointing triangle
                "◦",  # ◦ white bullet point
                "■",  # ■ black square
                "□",  # □ white square
                "▪",  # ▪ black small square
                "▫",  # ▫ white small square
                "-",  # - en dash
                "–",  # – dash
                "—",  # — zh dash 
                "*",  # * star
            )
            """, block="block", language="python"),
        ),
        
        
        Details(
            Summary("Sample documents that are filtered out by line-wise heuristics"),
            DV(
                "data/line_info.json",
                0,
                "Sample documents that are filtered out by line-wise heuristics",
            ),
        ),
        
        H3("3.3 Statistics-based Heuristics"),
        P("We summarize other statistics-based rules originated from Gopher [7] in this section. The statistics can be used include:"),
        Ul(
            Li("the word count in the document", style = "margin-bottom: 5px"),
            Li("the mean word length", style = "margin-bottom: 5px"),
            Li("the number of sentences", style = "margin-bottom: 5px"),
            Li("the symbol-to-word ratio", style = "margin-bottom: 5px"),
            Li("the fraction of alphabetic words", style = "margin-bottom: 5px"),
            Li("and the number of stop words", style = "margin-bottom: 5px"),
        ),
        P("Specifically, we remove any document which satisfies any of the following criteria:"),
        Ul(
            Li("it contains less than 50 words or more than 100,000 words", style = "margin-bottom: 5px"),
            Li("its mean word length is outside the range of 3 to 10", style = "margin-bottom: 5px"),
            Li("it contains less than 3 sentences", style = "margin-bottom: 5px"),
            Li("its symbol-to-word ratio is greater than 0.1", style = "margin-bottom: 5px"),
            Li("the words that contain at least one alphabetic character are less than 80% of the whole words", style = "margin-bottom: 5px"),
            Li("it contains less than two of the stop words (the, be, to, of, and, that, have, with", style = "margin-bottom: 5px"),
        ),
        H3("Word Count"),
        Details(
            Summary("Implementations from Dolma"),
            D_code("""
            words = text.split()
            word_count = len(words)
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from RedPajama-V2"),
            D_code("""
            # the normalized content: lowercased and punctuation removed
            self._normalized_content = normalize(content)
            self._normalized_words = tuple(self._normalized_content.split())
            self._num_normalized_words = len(self._normalized_words)
            
            ...
            def normalize(
                   text: str,
                   remove_punct: bool = True,
                   lowercase: bool = True,
                   nfd_unicode: bool = True,
                   white_space: bool = True
            ) -> str:
               #Normalize the text by lowercasing and removing punctuation.
               # remove punctuation
               if remove_punct:
                   text = text.translate(TRANSLATION_TABLE_PUNCTUATION)
               # lowercase
               if lowercase:
                   text = text.lower()
               if white_space:
                   text = text.strip()
                   text = re.sub(r"\s+", " ", text)
               # NFD unicode normalization
               if nfd_unicode:
                   text = unicodedata.normalize("NFD", text)
               return text
            """, block="block", language="python"),
        ),
        
        Details(
            Summary("Implementations from DataTrove"),
            D_code("""
            words = self.tokenizer.word_tokenize(text)
            n_words = len(words)
            
            non_symbol_words = [w for w in words if any(ch not in PUNCTUATION_SET for ch in w)]
            n_non_symbol_words_words = len(non_symbol_words)
            """, block="block", language="python"),
        ),
        P("""
        Both Dolma and RedPajama V2 split texts into words using white spaces and newline symbols. However, 
        DataTrove employs a tokenizer to split texts into words and ignore punctuations, resulting in a higher 
        word count compared to simple `text.split()`.
        We decided to use simple `len(text.split())` to compute the word count.
        """),
        
        H3("Mean Word Length"),
        P("""
        There is minimal variation among existing pipeline implementations. We simply compute the mean word length as follows:
        """),
        D_code("""
                words = text.split()
                word_count = len(words)
                character_count = sum(len(word) for word in words)
                mean_word_length = character_count / word_count
            """, block="block", language="python"),
        P("""
        It's worth noting that Dolma used the median word length instead of the mean:
        """),
        D_code("""
                from statistics import median
                median_word_length = median(len(word) for word in words)
            """, block="block", language="python"),
        H3("Number of Sentences"),
        P("""
        The only publicly available implementation of this quality signal is from RedPajama V2, which uses regular expressions 
        to split text into sentences.
        """),
        Details(
            Summary("Implementations from RedPajama-V2"),
            D_code("""
            class RPS_Doc_Num_Sentences(RPSBase):  # noqa
             ##The number of sentences in the content. This is calculated using the regex r'[^.!?]+[.!?]*' 
            SENT_PATTERN = re.compile(r'[^.!?]+[.!?]*', flags=re.UNICODE)
        
            __slots__ = ()
        
            def __call__(self, document: Document) -> SignalType:
                ##count the number of sentences in the content using regex
                score = float(len(self.SENT_PATTERN.findall(document.raw_content)))
                return [(0, len(document), score)]
            """, block="block", language="python"),
        ),
        P("""
        However, we found that this approach can mistakenly interpret periods in URLs as sentence endings. To address this, 
        we opted to use `nltk.tokenize.sent_tokenize` for more accurate sentence splitting.
        """),
        Details(
            Summary("TxT360 Implementation"),
            D_code("""
            from nltk.tokenize import sent_tokenize
            ...
            def count_sentences(text):
                sentences = sent_tokenize(text)
                return len(sentences)
            ...
            attrs.num_of_sentences = count_sentences(text)
            """, block="block", language="python"),
        ),
        
        H3("Symbol to Word Ratio"),
        P("""
        Following RedPajama-V2 and DataTrove, we use the symbols of ("#", "...", "…").
        We calculate the ratio as the number of symbols divided by the total number of words.
        """),
        Details(
            Summary("Implementations from Dolma"),
            D_code("""
            SYMBOLS = ("#", "…")
            ...
            attrs.symbol_to_word_ratio = sum(1 for word in words if any(s in word for s in SYMBOLS)) / max(
                        word_count, 1
                    )
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from RedPajama-V2"),
            D_code("""
            class RPS_Doc_Symbol_To_Word_Ratio(RPSBase):  # noqa
    ##The ratio of symbols to words in the content. This is analogous to
    ##the signal used in Gopher. Symbols are defined "#", "...", and "…". 
                SYMBOLS = ("#", "...", "…")
            
                __slots__ = ()
            
                def __call__(self, document: Document) -> SignalType:
                    num_words = document.num_raw_words
            
                    if num_words == 0:
                        return [(0, len(document), None)]
            
                    # count the number of symbols in the content
                    num_symbols = float(sum(
                        document.raw_content.count(x) for x in self.SYMBOLS
                    ))
            
                    score = num_symbols / num_words
                    score = round(score, PRECISION)
                    return [(0, len(document), score)]
            """, block="block", language="python"),
        ),
        
        Details(
            Summary("Implementations from DataTrove"),
            D_code("""
            if self.max_symbol_word_ratio and text.count("#") / n_words > self.max_symbol_word_ratio:
                return False, "gopher_too_many_hashes"
            if self.max_symbol_word_ratio and (text.count("...") + text.count("…")) / n_words > self.max_symbol_word_ratio:
                return False, "gopher_too_many_ellipsis"
            """, block="block", language="python"),
        ),
        Details(
            Summary("TxT360 Implementation"),
            D_code("""
            SYMBOLS = ("#", "...", "…")
            ...
            symbol_pattern = re.compile("|".join(re.escape(symbol) for symbol in SYMBOLS))
            ...
            attrs.symbol_to_word_ratio = sum(1 for word in words if symbol_pattern.search(word)) / word_count
            """, block="block", language="python"),
        ),
        
        H3("Fraction of Alphabetic Words"),
        Details(
            Summary("Implementations from Dolma"),
            D_code("""
            attrs.fraction_of_words_with_alpha_character = sum(
            1 for word in words if any(c.isalpha() for c in word)
        ) / max(word_count, 1)
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from RedPajama-V2"),
            D_code("""
            class RPS_Doc_Frac_No_Alph_Words(RPSBase):  # noqa
                ALPH_REGEX = re.compile(r"[a-zA-Z]")
            
                __slots__ = ()
            
                def __call__(self, document: Document) -> SignalType:
                    num_words = document.num_raw_words
            
                    if num_words == 0:
                        return [(0, len(document), None)]
            
                    num_words_with_alpha = float(sum(
                        int(self.ALPH_REGEX.search(word) is not None)
                        for word in document.raw_words
                    ))
            
                    score = 1.0 - num_words_with_alpha / num_words
                    score = round(score, PRECISION)
                    return [(0, len(document), score)]
            """, block="block", language="python"),
        ),
        Details(
            Summary("Implementations from DataTrove"),
            D_code("""
            # that 80 % of words in a document contain at least one alphabetic character
            if (
                self.max_non_alpha_words_ratio
                and sum([any((c.isalpha() for c in w)) for w in words]) / n_words < self.max_non_alpha_words_ratio
            ):
                return False, "gopher_below_alpha_threshold"
            """, block="block", language="python"),
        ),
        P("""
        Both Dolma and DataTrove use `char.isalpha()` to detect whether a word contains alphabetic characters while 
        RedPajama-V2 employs regular expressions for this purpose. We opt to use regular expressions since `char.isalpha()` 
        can also match words in other languages as long as they are not punctuations.
        """),
        H5("Number of Stop Words"),
        P("""
        The implementations across existing pipelines are largely identical. We adopt them and apply them to our pipeline.
        """),
        D_code("""
        STOP_WORDS = ('the', 'be', 'to', 'of', 'and', 'that', 'have', 'with')
        ...
        stop_words_pattern = re.compile("|".join(re.escape(symbol) for symbol in STOP_WORDS))
        ...
        attrs.num_of_stop_words = sum(1 for word in words if stop_words_pattern.search(word))
        
        """, block="block", language="python"),
        H3("TxT360 Implementation"),
        Details(
            Summary("Sample documents that are filtered out by statistics-based heuristics"),
            DV(
                "data/sample_doc_stat.json",
                0,
                "Sample documents that are filtered out by statistics-based heuristics",
            ),
        ),
        H3("3.4 Others"),
        P("""
        Following C4, we remove any page where the phrase “lorem ipsum” appeared since some pages had placeholder “lorem ipsum” 
        text.
        """),
        
        Details(
            Summary("Sample documents containing 'lorem ipsum'"),
            DV("data/lorem_ipsum.json", 0, "Sample documents containing 'lorem ipsum'"),
        ),
        H2("4. Deduplication"),
        P("""
        After careful filtering, although data quality has improved, a large fraction of the content is repeated across documents. This may be due to the crawler indirectly hitting the same page multiple times, to boilerplate content being repeated (e.g., licences), or even to plagiarism. These duplicates can strongly impact models, favoring memorization instead of generalization.
        """),  # Add detailed content and images as needed
        P("We perform two-level deduplication: local exact deduplication and global fuzzy deduplication"),
        P(B("Local Exact Deduplication")),
        P("To reduce the expensive cost of global deduplication, we apply a local exact deduplication before it. Specifically, each dump is split into 70 splits. A bloom filter is applied within each split."),
        P(B("Global Fuzzy Deduplication")),
        P("NEED TO UPDATE"),
        H2("5. PII Removal"),
        P("..."),  # Add detailed content and images as needed
    )