File size: 37,347 Bytes
e137e27
 
 
 
 
 
 
 
 
4028499
e137e27
24b53c0
8feeca0
 
 
24b53c0
583d7c5
24b53c0
 
583d7c5
 
24b53c0
 
 
583d7c5
24b53c0
 
 
583d7c5
24b53c0
 
 
583d7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
b4e3ff3
583d7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cee378
583d7c5
 
 
 
 
 
 
 
b4e3ff3
583d7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4e3ff3
583d7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b53c0
 
 
 
 
 
 
 
31b08ca
 
 
 
 
9f87a47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb8c2a5
 
9f87a47
 
 
 
 
 
31b08ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b08ca
 
 
 
 
 
 
 
 
 
 
 
 
e137e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b53c0
e137e27
5493cad
 
 
bb8c2a5
5493cad
8feeca0
24b53c0
e137e27
5493cad
e137e27
5493cad
 
 
ee3ad0f
 
f3f6d37
 
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
from fasthtml.common import *
from fasthtml.components import *
from plotly import graph_objects as go
from fh_plotly import plotly2fasthtml
import pandas as pd
import json
from data_viewer import view_data, gen_random_id
from rich import print
import uuid
import plotly.express as px

filtering_process = Div(
    Section(
          P("This section contains the specific steps taken to filter all 14 curated source datasets.")  
    ),
    Section(
        H3("Wikipedia"),
        H4("Download and Extraction"),
        Ol(
            Li("Downloaded from Wikimedia official dump of wikipedia on huggingface https://huggingface.co/datasets/wikimedia/wikipedia/tree/main"),
            Li("Data is originally in parqet format so we use huggingface dataset.to_json function to convert it to the jsonl format"),
        ),
        H4("Filtering"),
        Ol(
            Li("As we expect the dataset to be already of high quality so only one filter is applied which is to remove all documents (articles) with less than 10 words (not inclusive)"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Whole wikipedia was deduped using minhash generation following Slim pajama code"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining wikipedia was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("ArXiv"),
        H4("Download and Extraction"),
        Ol(
            Li("All the data was downloaded in original latex format from Arxiv official S3 dump s3://arxic/src"),
            Li("We try to encode the downloaded data into utf-8 or guess encoding using chardet library"),
            Li("After that pandoc was used to extract information from the latex files and saved as markdown format - code: pandoc -s {tex} -o out/{out_name}.md --wrap=none"),
            Li("All markdowns were combined to create jsonl files"),
        ),
        H4("Filtering"),
        P("Multiple filters are used here after manually verifying output of all the filters as suggested by peS2o dataset"),
        Ol(
            Li("min_word: less than 500 words (not inclusive) are discarded"),
            Li("Language: any language other than English are discarded"),
            Li("Frequency: The most frequent word in the paper consists of alpha characters only, and it appears in less than 7.5% of the document. Words are obtained by splitting the text on whitespace."),
            Li("Unigram log probablity: Must have higher than -20 average unigram log probability. To calculate the average log word probability, we use word frequencies extracted from the 1T Web Ngram corpus; specifically, we use the list available created by Rachel Tatman. A copy is hosted here."),
            Li("number 4 above had hyperlinks that need to be included"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done with all papers combined."),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("This data was part of paper domain which are combined together and minhash was generated and deduped together with all the datasets after doing local dedup."),
        ),
        
    ),
    Section(
        H3("S2ORC"),
        H4("Download and Extraction"),
        Ol(
            Li("This was downloaded directly in zip format using S2ORC api key and normal get request. code: response = urllib.request.urlopen(url)"),
            Li("There were two kind of datasets that was downloaded S2ORC and S2ORC abstract"),
        ),
        H4("Filtering - S2ORC"),
        P("1. Multiple filters are used here after manually verifying output of all the filters as suggested by peS2o dataset"),
        Ol(
            Li("title_abstract: must have title and abstract"),
            Li("The paper must be in English. To determine the language of each document, we use the pycld3 library. We run pycld3 on the first 2000 characters of each paragraph in the paper. The language of the paper is the most common language of the paragraphs."),
            Li("word_count: less than 500 words (not inclusive) are discarded"),
            Li("paragraph_count: The paper must have at least 5 paragraphs after removing paragraphs with less than -20 average log world probability"),
            Li("frequency: The most frequent word in the paper consists of alpha characters only, and it appears in less than 7.5% of the document. Words are obtained by splitting the text on whitespace."),
        ),
        H4("Filtering - S2ORC Abstract"),
        P("1. Multiple filters are used here after manually verifying output of all the filters as suggested by peS2o dataset. The frequency filter was not used as suggested by peS2o because it was removing good samples as inspected manually"),
        Ol(
            Li("title_abstract: must have title and abstract"),
            Li("language: abstract must be in English"),
            Li("word_count: less than 20 (not inclusive) are discarded"),
            Li("Unigram log probablity"),
            Li("frequency: The most frequent word in the paper consists of alpha characters only, and it appears in less than 7.5% of the document. Words are obtained by splitting the text on whitespace."),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done with all papers combined."),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("This data was part of paper domain which are combined together and minhash was generated and deduped together with all the datasets after doing local dedup"),
        ),
        
    ),
    Section(
        H3("PubMed"),
        H4("Download and Extraction"),
        Ol(
            Li("First all the urls of PMC and PMA files are parsed and stored as text file from FTP server https://ftp.ncbi.nlm.nih.gov/pub/pmc/oa_package/"),
            Li("All the urls are downloaded and the downloaded data is in xml.tar format"),
            Li("For pubmed central First tar files are opened using tarfile library and then converted to markdown format using pandoc: pandoc -f jats {nxml} -o {pmcid}.md --wrap=none"),
            Li("All the markdown files are combined to create jsonl files. In jsonl files, 1 line correspond to 1 markdown file."),
            Li("For pubmed abstract, the XML files are in very simple format and beautiful soup is directly used to extract the abstract, title and pmid and stored in jsonl format"),
        ),
        H4("Filtering"),
        P("1. Multiple filters are used here after manually verifying output of all the filters as suggested by peS2o dataset."),
        Ol(
            Li("min_word: less than 100 words (not inclusive) are discarded, less than 20 words for pubmed abstract"),
            Li("Language: any language other than English are discarded"),
            Li("Frequency: The most frequent word in the paper consists of alpha characters only, and it appears in less than 7.5% of the document. Words are obtained by splitting the text on whitespace. This filter is not used for pubmed abstract"),
            Li("Unigram log probablity: Must have higher than -20 average unigram log probability. To calculate the average log word probability, we use word frequencies extracted from the 1T Web Ngram corpus; specifically, we use the list available created by Rachel Tatman. A copy is hosted here."),
            Li("need to add the hyperlinks for the section above"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done with all papers combined."),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("This data was part of paper domain which are combined together and minhash was generated and deduped together with all the datasets after doing local dedup."),
        ),
        
    ),
    Section(
        H3("Phil Papers"),
        H4("Download and Extraction"),
        Ol(
            Li("Original pdf files download location was downloaded from https://philarchive.org/oai.pl "),
            Li("All pdf files were downloaded"),
            Li("Pdf was converted to text using java -jar ../philpapers_resources/src/pdfbox-app-2.0.21.jar ExtractText {f0} {FOUT.name}"),
            Li("Language was detected and added using langdetect library"),
        ),
        H4("Filtering"),
        Ol(
            Li("Many filters were used to clean the phil papers like double whitespaces, new lines etc. All filter details are here: https://github.com/thoppe/The-Pile-PhilPapers/blob/master/pdf_filter.py"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done with all papers combined."),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("This data was part of paper domain which are combined together and minhash was generated and deduped together with all the datasets after doing local dedup."),
        ),
        
    ),
    Section(
        H3("Europarl"),
        H4("Download and Extraction"),
        Ol(
            Li("Original data was downloaded from http://www.statmt.org/europarl/v7/europarl.tgz"),
            Li("Finally the remaining files are converted to jsonl lines"),
        ),
        H4("Filtering"),
        Ol(
            Li("Smaller than 200 characters of documents are removed while downloading so no others filtered were run"),
            Li("Tags were also removed while downloading"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within europarl itself"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining europarl was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("HackerNews"),
        H4("Download and Extraction"),
        Ol(
            Li("Data was parsed using hackernews story ids starting using https://hacker-news.firebaseio.com/v0/item/"),
            Li("Story ids was started from 1 till 37500000 (all stories that gives error while pinging the url was removed). Each post is a story, with each reply another story"),
            Li("As there were too many requests error, there was a wait(2 sec) statement included in the code"),
            Li("As the number of stories were large and containing all the replies was time consuming and possibility of introducing too much error, only longest depth threads were included from 3rd level onwards. So we include the title then all the replies (2nd level) but replies to those replies (3rd level) were only the ones which has maximum depth."),
        ),
        H4("Filtering"),
        Ol(
            Li("Min word: 10"),
            Li("Language: Only english"),
            Li("Unigram log probablity"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within hackernews itself"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining data was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("USPTO"),
        H4("Download and Extraction"),
        Ol(
            Li("Data was downloaded and extracted using tags from https://bulkdata.uspto.gov/data/patent/grant/redbook/fulltext/"),
            Li("There were three different format that needed three different functions to download and extract the data based on year: Pre_2002, 2002_to_2004, post_2004"),

        ),
        H4("Filtering"),
        Ol(
            Li("Min word: 50"),
            Li("Language: Only english"),
            Li("Unigram log probablity"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within USPTO itself"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining data was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("FreeLaw"),
        H4("Download and Extraction"),
        Ol(
            Li("CSV format bulk data was downloaded from https://storage.courtlistener.com/bulk-data/"),
            Li("They have multiple dumps as shown below with lot of duplicates (exact number is given in the table at the top)"),
            Li("there is an image to show here!"),
            Li("As these are csv files, they have multiple columns where text can be present, so we extracted text from the following columns using html2text function which just convert and extract tags from html tags"),
            Li("image to show"),
            Li("Text was also extracted from row named 'plain_text'"),
            Li("Priority is always given to plain_text first then from 6 to 1 in the subsequent order following pile logic"),
        ),
        H4("Filtering"),
        Ol(
            Li("Min word: 50"),
            Li("Language: Only english"),
            Li("Unigram log probablity"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within freelaw itself which removed 90%+ duplicates"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining data was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("StackExchange"),
        H4("Download and Extraction"),
        Ol(
            Li("Archive dump was used to download data from all the stackexchange sub urls, eg., math.stackexchange etc."),
            Li("Raw data is in XML format with lot of metadata. We only used two files Posts.xml and Comments.xml"),
            Li("We parsed using post_id to connect each question to answer and then to comments so our data has same hierarchy as stackexchange UI"),
            Li("""
              1. Questions:
  2. Comment1:
  3. Comment2:
  4. Answer1:
  5. Comment1:
  6. Comment2:
  7. Answer2:
  8. Comment1:
  9. Comment2:
            """),
        ),
        H4("Filtering"),
        Ol(
            Li("Min word: 10"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within stackexchange itself"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining data was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("Ubuntu IRC"),
        H4("Download and Extraction"),
        Ol(
            Li("All the data was downloaded from https://irclogs.ubuntu.com/{date.year}/{date.month:02d}/{date.day:02d}/ based on the year"),
            Li("During extraction, we cleaned the logs using following functions"),
            Li("image here"),
        ),
        H4("Filtering"),
        Ol(
            Li("Min word: 10"),
            Li("Language: Only english"),
            Li("Unigram log probablity"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within Ubuntu IRC itself"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining data was deduped again with all the datasets combined"),
        ),
        
    ),
    Section(
        H3("DM Maths"),
        H4("Download and Extraction"),
        Ol(
            Li("Directly downloaded from hugging-face dump dm_maths/"),
            Li("Data was converted in jsonl format where each lines are : Question: TEXT Answer: TEXT"),
        ),
        H4("Filtering"),
        Ol(
            Li("None"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("None"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("None"),
        ),
        
    ),
    Section(
        H3("PG19"),
        H4("Download and Extraction"),
        Ol(
            Li("Directly downloaded from hugging-face dump pg19/"),
        ),
        H4("Filtering"),
        Ol(
            Li("Min word: 20"),
            Li("Language: ???"),
            Li("Unigram log probablity"),
        ),
        H4("Local Deduplication Process"),
        Ol(
            Li("Local dedup was done within PG19 itself"),
        ),
        H4("Global Deduplication Process"),
        Ol(
            Li("After local dedup, remaining data was deduped again with all the datasets combined"),
        ),
        
    ),
)




overview_text = P("Curated sources comprise high-quality datasets that contain domain-specificity. These sources, such as Arxiv, Wikipedia, and Stack Exchange, provide valuable data that is excluded from the web dataset mentioned above. Analyzing and processing non-web data can yield insights and opportunities for various applications. Details about each of the sources are provided below. ")
copyright_disclaimer = P("We respect the copyright of the data sources and have not included the controversial data that was used in Pile like YouTube and Opensubtitles, Reddit threads, and books.")

local_dedup_text = P("Each curated data source has been prepared using its specific rules and has been locally deduped using min-hash near deduplication. Details about the dataset are shown below in the table:")

treemap_data = {
  'Source': ['ArXiv', 'PubMed Central', 'PubMed Abstract', 'S2ORC Full Text', 'S2ORC Abstract', 'PhilPapers', 'Wikipedia', 'StackExchange', 'EuroParl', 'Ubuntu IRC', 'Freelaw', 'PG19', 'USPTO', 'HackerNews', 'DM Maths'],
  'Category': ['Papers', 'Papers', 'Papers', 'Papers', 'Papers', 'Papers', 'Internet', 'Conversational', 'Legal/Formal', 'Conversational', 'Legal/Formal', 'Books', 'Legal/Formal', 'Conversational', 'Reasoning'],
  'Count': [100, 200, 150, 120, 80, 90, 300, 250, 180, 150, 150, 250, 180, 120, 90],
  'Details': [
    'A repository of scientific papers in various disciplines, including computer science, physics, mathematics, and more.',
    'A database of biomedical and life sciences research articles.',
    'Abstracts of biomedical literature from various sources.',
    'Full-text articles from the Semantic Scholar Open Research Corpus.',
    'Abstracts of articles from the Semantic Scholar Open Research Corpus.',
    'Papers from the PhilPapers database, a comprehensive index and bibliography of philosophy research.',
    'A collaborative online encyclopedia that covers a wide range of topics.',
    'A network of question-and-answer websites on various subjects, including programming, science, mathematics, and more.',
    'A collection of multilingual parallel corpora of parliamentary debates from the European Parliament.',
    'Chat logs from the Ubuntu Internet Relay Chat (IRC) channels.',
    'Legal documents and court cases from various jurisdictions.',
    'A collection of books from Project Gutenberg, a digital library of public domain works.',
    'Patent documents from the United States Patent and Trademark Office.',
    'User-generated news and discussion platform focused on technology and startups.',
    'Deep Mind Maths dataset with generated questions.'
  ]
}
# Calculate percentage for each data source
total_count = sum(treemap_data['Count'])
treemap_data['Percentage'] = [count / total_count * 100 for count in treemap_data['Count']]

# Create treemap
fig = px.treemap(treemap_data, path=['Category', 'Source'], values='Count', hover_data=['Details', 'Percentage'], hover_name='Source')

# Set the size of the chart


# Display treemap if you want to update the size.update_layout(width=800, height=600)
treemap_chart = fig






data_pipeline_table = pd.DataFrame(
        {
            "Data Source": [
                "Papers",
                "Wikipedia",
                "StackExchange",
                "Europarl",
                "Ubuntu IRC",
                "HackerNews",
                "PG-19",
                "USPTO",
                "Freelaw",
                "DM Math",
            ],
            "Percent Filtered": [
                "15%",
                "21%",
                "<0.1%",
                "1%",
                "0.4%",
                "60%",
                "0.8%",
                "22.5%",
                "94%",
                "0",
            ],
            "Unique Document Percentage": [
                "75.99%",
                "91.91%",
                "98.02%",
                "98.87%",
                "100%",
                "99.91%",
                "31.81%",
                "99.94%",
                "91.01%",
                "0",
            ],
            "2 - 5 Duplicates": [
                "19.4%",
                "4.7%",
                "1.27%",
                "0.94%",
                "0",
                "0.05%",
                "20.03%",
                "0.05%",
                "6,87%",
                "0",
            ],
            "6 - 10 Duplicates": [
                "2.89%",
                "1.58%",
                "0.35%",
                "0.09%",
                "0",
                "0.02%",
                "24.27%",
                "0.01%",
                "1.07%",
                "0",
            ],
            "11 - 100 Duplicates": [
                "1.17%",
                "1.76%",
                "0.35%",
                "0.1",
                "0",
                "0.02%",
                "22.26%",
                "0.01%",
                "1.05%",
                "0",
            ],
            "101 - 1000 Duplicates": [
                "0.01%",
                "0.05%",
                "0.01%",
                "0",
                "0",
                "<0.01%",
                "1.58%",
                "<0.01%",
                "0.01%",
                "0",
            ],
            "1001+ Duplicates": [
                "<0.01%",
                "<0.01%",
                "<0.01%",
                "0",
                "0",
                "<0.01%",
                "0.06%",
                "0",
                "0",
                "0",
            ],
        }
    )

table_html_data_pipe = data_pipeline_table.to_html(index=False, border=0)
table_div_data_pipe = Div(NotStr(table_html_data_pipe), style="margin: 40px;")

data_descriptions = pd.DataFrame(
    {
        "Source": [
            "Papers - ArXiv",
            "Papers - PhilPapers",
            "Papers - S2ORC",
            "Papers - PubMed Central",
            "Papers - PubMed Abstract",
            "Wikipedia",
            "StackExchange",
            "EuroParl",
            "Ubuntu IRC",
            "Freelaw",
            "PG-19",
            "USPTO",
            "HackerNews",
            "DM Maths",
        ],
        "Description": [
            "The ArXiv dataset is a vast collection of preprint research papers primarily in Mathematics, Computer Science, and Physics. Established in 1991, it offers high-quality text and mathematical knowledge, making it an invaluable resource for academic and scientific research. ArXiv papers are typically written in LaTeX, a popular typesetting system for these fields. We have extracted the information from latex and converted it into a text format.",
            "Papers from the PhilPapers database, a comprehensive index and bibliography of philosophy research maintained by the Center for Digital Philosophy at the University of Western Ontario.",
            "The Semantic Scholar Open Research Corpus (S2ORC) is a comprehensive dataset designed for natural language processing (NLP) and text-mining research over scientific papers. It includes rich metadata, and abstract and full-text content for millions of academic papers across various disciplines. This dataset is further divided into two components, S2ORC abstract and S2ORC full text.",
            "The PubMed Central (PMC) dataset is a comprehensive collection of full-text biomedical and life sciences journal articles run by the United States of America’s National Center for Biotechnology Information (NCBI). It provides open access to a wealth of scientific literature, facilitating research and discovery in the medical and biological fields starting from 2008 by the NIH Public Access Policy. Articles in PMC are available for text mining and other secondary analyses, making it an invaluable resource for researchers and developers and other downstream tasks.",
            "Abstracts of more than 30 million publications of biomedical literature from various sources mainly including biomedical articles run by the National Library of Medicine. ",
            "Wikipedia is an encyclopedia form of high-quality text data used for language modeling. We have included filtered and deduplicated versions of complete Wikipedia data directly provided by the Wikipedia Foundation for more than 350 languages.",
            "A network of question-and-answer websites on various subjects, including programming, science, mathematics, and more. This is one of the largest publicly available repositories for question-answer pairs. We have included comments also to include an overall discussion on each post.",
            "A collection of multilingual parallel corpora of parliamentary debates from the European Parliament. This is a high-quality legacy dataset earlier used for translation tasks.",
            "Chat logs from the Ubuntu Internet Relay Chat (IRC) channels on the Freenode IRC chat server. This data is also another form of dialog dataset on niche topics.",
            "Legal documents and court cases from various jurisdictions provided by US-registered non-profit firm Free Law Project. We have included data from CourtListener which included millions of legal opinions from federal and state courts.",
            "A collection of books from Project Gutenberg, a digital library of public domain works. This contains all the books that were published before 1919.",
            "Patent documents from the United States Patent and Trademark Office.",
            "High-quality dialog-based dataset where user comments on the links as the head post aggregated by Y Combinator.",
            "DeepMind Maths dataset with generated questions from various topics like algebra, calculus, geometry, etc. Maths data is included to improve model reasoning abilities in the downstream tasks.",
        ],

    }
)

table_html_desc = data_descriptions.to_html(index=False, border=0)
table_desc = Div(NotStr(table_html_desc), style="margin: 40px;")


data_sources = [
    "Freelaw",
    "Wikipedia",
    "PhilPapers",
    "Arxiv",
    "S2ORC",
    "S2ORC Abstract",
    "Pubmed",
    "USPTO",
    "Hackernews",
    "Ubuntu IRC",
    "StackExchange",
    "DM Maths",
    "PG19",
    "Europarl",
]


def get_data(data_source: str = "Freelaw", doc_id: int = 3, target: str = "foo"):
    doc_id = max(0, min(int(doc_id), 9))

    if data_source == "Freelaw":
        raw_sample_doc = json.load(open("data/curated_samples/freelaw_raw.json"))
        extracted_sample_doc = json.load(
            open("data/curated_samples/freelaw_extract.json")
        )
    elif data_source == "Wikipedia":
        raw_sample_doc = extracted_sample_doc = json.load(
            open("data/curated_samples/wiki.json")
        )
    elif data_source == "StackExchange":
        raw_sample_doc = json.load(open("data/curated_samples/stackexchange_raw.json"))
        extracted_sample_doc = json.load(
            open("data/curated_samples/stackexchange_extract.json")
        )
    elif data_source == "PhilPapers":
        raw_sample_doc = extracted_sample_doc = json.load(
            open("data/curated_samples/philpapers_raw.json")
        )
    elif data_source == "Arxiv":
        raw_sample_doc = json.load(open("data/curated_samples/arxiv_raw.json"))
        extracted_sample_doc = json.load(
            open("data/curated_samples/arxiv_extract.json")
        )
    elif data_source == "S2ORC":
        raw_sample_doc = extracted_sample_doc = json.load(
            open("data/curated_samples/s2orc_raw.json")
        )
    elif data_source == "S2ORC Abstract":
        raw_sample_doc = extracted_sample_doc = json.load(
            open("data/curated_samples/s2orc_abstract_raw.json")
        )
    elif data_source == "Pubmed":
        raw_sample_doc = json.load(open("data/curated_samples/pubmed_raw.json"))
        extracted_sample_doc = json.load(
            open("data/curated_samples/pubmed_extract.json")
        )
    elif data_source == "DM Maths":
        raw_sample_doc = json.load(open("data/curated_samples/dm_maths_raw.json"))
        extracted_sample_doc = json.load(
            open("data/curated_samples/dm_maths_extract.json")
        )
    elif data_source == "PG19":
        raw_sample_doc = extracted_sample_doc = json.load(
            open("data/curated_samples/pg19_raw.json")
        )
    elif data_source == "Europarl":
        raw_sample_doc = extracted_sample_doc = json.load(
            open("data/curated_samples/europarl_raw.json")
        )
    else:
        raw_sample_doc = extracted_sample_doc = [{} for _ in range(10)]

    raw_json = raw_sample_doc[doc_id]
    extracted_json = extracted_sample_doc[doc_id]
    return view_data(
        raw_json,
        extracted_json,
        doc_id=doc_id,
        data_source=data_source,
        data_sources=data_sources,
        target=target,
    )


def get_chart_28168342():
    fig = go.Figure()
    filter_names = [
        "Download",
        "Language",
        "Min word count",
        "Title Abstract",
        "Majority language",
        "Paragraph count",
        "Frequency",
        "Unigram log probability",
        "Local dedup",
    ]

    data_sources = [
        ("Wikipedia", [100, 90, 80, 70, 60, 50, 40, 30, 20]),
        ("Freelaw", [100, 90, 80, 70, 60, 50, 40, 20, 20]),
        ("DM Maths", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("USPTO", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("PG19", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("Hackernews", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("Ubuntu IRC", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("Europarl", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("StackExchange", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("Arxiv", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("S2ORC", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("S2ORC Abstract", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("PubMed Central", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("PubMed Central Abstract", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
        ("PhilPapers", [100, 90, 80, 70, 60, 40, 40, 30, 20]),
    ]

    for name, x_values in data_sources:
        fig.add_trace(
            go.Funnel(
                name=name,
                orientation="h",
                y=filter_names,
                x=x_values,
                textinfo="value+percent total",
                textposition="inside",
            )
        )

    fig.update_layout(height=500, plot_bgcolor="rgba(0,0,0,0)")
    return fig


def update(target: str, request):
    params = request.query_params
    if data_source := params.get(f"data_source_{target}"):
        return get_data(
            data_source, params.get(f"doc_id_{target}", 3), target)
    if doc_id := params.get(f"doc_id_{target}"):
        return get_data(
            params.get(f"data_source_{target}"), doc_id, target)


def curated(request):

    # Partial Updates
    params = dict(request.query_params)
    if target := params.get("target"):
        if data_source := params.get(f"data_source_{target}"):
            return get_data(
                data_source, params.get(f"doc_id_{target}", 3), params.get("target")
            )
        if doc_id := params.get(f"doc_id_{target}"):
            return get_data(
                params.get(f"data_source_{target}"), doc_id, params.get("target")
            )
    
    data_preparation_steps = pd.DataFrame(
        {
            "Method": [
                "HTTP/FTP dumps",
                "Web crawling",
                "Archive snapshot",
                "Generated",
                "Curated",
            ],
            "Description": [
                "Acquiring data from HTTP/FTP dumps",
                "Crawling websites to extract data",
                "Working with archive dumps",
                "Generating synthetic data",
                "High quality curated data",
            ],
            "Source": [
                "Freelaw | Wikipedia | PhilPapers | Arxiv | S2ORC | Pubmeds",
                "USPTO | Hackernews | Ubuntu IRC",
                "StackExchange",
                "DM Maths",
                "PG19 | Europarl",
            ],
        }
    )

    table_html = data_preparation_steps.to_html(index=False, border=0)
    table_div = Div(NotStr(table_html), style="margin: 40px;")

    text = P("""This initial stage serves as the foundation for the entire
    process. Here, we focus on acquiring and extracting the raw data, which can
    come from various sources such as crawling websites, using HTTP/FTP dumps,
    or working with archive dumps.  For instance, to download and prepare a
    dataset, we can specific downloaders based on the data source. Each dataset
    might have its own downloader script which can be updated in real time to
    handle changes in the data source.  Here is a general outline of the data
    preparation process: It's worth noting that some pipelines might require
    invoking additional functions or scripts to handle specific data sources or
    formats.  These helper scripts can be located within specific directories
    or modules dedicated to the dataset.""")

    data_preparation_div = Div(
        H3("Data Preparation"),
        text,
        table_div,
        Div(
            get_data(target=gen_random_id()),
            style="border: 1px solid #ccc; padding: 20px;",
        ),
    )

    text = P("""Data preprocessing is a crucial step in the data science
    pipeline. It involves cleaning and transforming raw data into a format that
    is suitable for analysis. This process includes handling missing values,
    normalizing data, encoding categorical variables, and more.""")

    preprocessing_steps = pd.DataFrame(
        {
            "Step": [
                "Language Filter",
                "Min Word Count",
                "Title Abstract",
                "Majority Language",
                "Paragraph Count",
                "Frequency",
                "Unigram Log Probability",
            ],
            "Description": [
                "Filtering data based on language",
                "Setting a minimum word count threshold",
                "Extracting information from the title and abstract",
                "Identifying the majority language in the dataset",
                "Counting the number of paragraphs in each document",
                "Calculating the frequency of each word in the dataset",
                "Calculating the log probability of each unigram",
            ],
            "Need": [
                "To remove documents in unwanted languages",
                "To filter out documents with very few words",
                "To extract relevant information for analysis",
                "To understand the distribution of languages in the dataset",
                "To analyze the structure and length of documents",
                "To identify important words in the dataset",
                "To measure the significance of individual words",
            ],
            "Pros": [
                "Improves data quality by removing irrelevant documents",
                "Filters out low-quality or incomplete documents",
                "Provides additional information for analysis",
                "Enables language-specific analysis and insights",
                "Helps understand the complexity and content of documents",
                "Identifies important terms and topics in the dataset",
                "Quantifies the importance of individual words",
            ],
            "Cons": [
                "May exclude documents in less common languages",
                "May remove documents with valuable information",
                "May introduce bias in the analysis",
                "May not accurately represent the language distribution",
                "May not capture the complexity of document structure",
                "May be sensitive to noise and outliers",
                "May not capture the semantic meaning of words",
            ],
        }
    )

    table_html = preprocessing_steps.to_html(index=False, border=0)
    table_div = Div(NotStr(table_html), style="margin: 40px;")
    data_preprocessing_div = Div(H3("Data Preprocessing"), text, table_div)
    
    return Div(
            H2("Curated Sources: Overview"),
            overview_text,
            copyright_disclaimer,
            plotly2fasthtml(treemap_chart),
            table_desc,
            H2("Curated Sources Processing"),
            filtering_process,
            data_preparation_div,
            H3("Data Filtering"),
            data_preprocessing_div,
            plotly2fasthtml(get_chart_28168342()),
            H2("Local Deduplication"),
            local_dedup_text,
            table_div_data_pipe, 
            id="inner-text",
)