-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCD-ICJ_Source_CorpusCreation.R
4650 lines (3046 loc) · 111 KB
/
CD-ICJ_Source_CorpusCreation.R
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
#'---
#'title: "Compilation Report | Corpus of Decisions: International Court of Justice (CD-ICJ)"
#'author: Seán Fobbe
#'geometry: margin=3cm
#'papersize: a4
#'fontsize: 11pt
#'output:
#' pdf_document:
#' keep_tex: true
#' toc: true
#' toc_depth: 3
#' number_sections: true
#' pandoc_args: --listings
#' includes:
#' in_header: tex/CD-ICJ_Source_TEX_Preamble_EN.tex
#' before_body: [tex/CD-ICJ_Source_TEX_Author.tex,temp/CD-ICJ_Source_TEX_Definitions.tex,tex/CD-ICJ_Source_TEX_CompilationTitle.tex]
#'bibliography: temp/packages.bib
#'nocite: '@*'
#'---
#'\newpage
#+ results = "asis"
cat(readLines("README.md"),
sep = "\n")
#'\newpage
#'# Preamble
#+
#'## Datestamp
#' This datestamp will be applied to all output files. It is set at the beginning of the script so it will be held constant for all output even if long runtime breaks the date barrier.
datestamp <- Sys.Date()
print(datestamp)
#'## Date and Time (Begin)
begin.script <- Sys.time()
print(begin.script)
#+
#'## Load Packages
library(RcppTOML) # Read and write TOML files
library(httr) # HTTP Tools
library(rvest) # Web Scraping
library(mgsub) # Vectorized Gsub
library(stringr) # String Manipulation
library(pdftools) # PDF utilities
library(fs) # File Operations
library(knitr) # Scientific Reporting
library(kableExtra) # Enhanced Knitr Tables
library(magick) # Required for cropping when compiling PDF
library(DiagrammeR) # Graph/Network Visualization
library(DiagrammeRsvg) # Export DiagrammeR Graphs as SVG
library(rsvg) # Render SVG to PDF
library(ggplot2) # Advanced Plotting
library(scales) # Rescaling of Plots
library(viridis) # Viridis Color Palette
library(RColorBrewer) # ColorBrewer Palette
library(readtext) # Read TXT Files
library(quanteda) # Advanced Text Analytics
library(quanteda.textstats) # Text Statistics Tools
library(quanteda.textplots) # Specialized Plots for Text Statistics
library(textcat) # Classify Text Language
library(data.table) # Advanced Data Handling
library(doParallel) # Parallelization
#'## Load Additional Functions
#' **Note:** Each custom function will be printed in full prior to its first use in order to enhance readability. All custom functions are prefixed with \enquote{f.} for clarity.
lapply(list.files("functions", pattern = "\\.R$", full.names = TRUE), source)
#'# Parameters
#+
#'## Output Directory
#' The directory name must include a terminating slash!
outputdir <- paste0(getwd(),
"/ANALYSIS/")
#+
#'## Read Configuration File
#' All configuration options are set in a separate configuration file that is read here. They should only be changed in that file!
config <- RcppTOML::parseTOML("config.toml")
print(config)
#+
#'## Name of Data Set
datashort <- config$project$shortname
print(datashort)
#'## DOI of Data Set Concept
doi.concept <- config$doi$data$concept
print(doi.concept)
#'## DOI of Specific Version
doi.version <- config$doi$data$version
print(doi.version)
#'## License
license <- config$license$data
print(license)
#'## Scope: Case Numbers
#' These variables define the scope of cases (by ordinal number) to be compiled into the data set.
#'
#' Case number 2 appears to be unassigned. There is no information available on the ICJ website. It is therefore always excluded.
#'
#' The variable for the final case number --- caseno.end --- must be set manually.
caseno.begin <- config$caseno$begin
caseno.end <- config$caseno$end
caseno.exclude <- config$caseno$exclude
print(caseno.begin)
print(caseno.end)
print(caseno.exclude)
#'## Debugging Mode
#' The debugging mode will reduce the number of documents compiled significantly. The full complement of cases takes approximately 11 hours to process with 16 threads on a Ryzen 3700X. The reduced complement captures a variety of cases with key characteristics that are useful in testing all features. Testing should always include cases 116 and 146 or an error will occur.
#'
#' In addition to the mandatory test cases debugging mode will draw two random samples of size *debug.sample*, one from older and one from more recent cases of the ICJ.
mode.debug.toggle <- config$debug$toggle
mode.debug.sample <- config$debug$sample
print(mode.debug.toggle)
print(mode.debug.sample)
#'## DPI for OCR
#' This is the resolution at which PDF files will be converted to TIFF during the OCR step. DPI values will significantly affect the quality of text ouput and file size. Higher DPI requires more RAM, means higher quality text and greater PDF file size. A value of 300 is recommended.
ocr.dpi <- config$ocr$dpi
print(ocr.dpi)
#'## Frequency Tables: Ignored Variables
#' This is a character vector of variable names that will be ignored in the construction of frequency tables.
#'
#' It is a good idea to add variables to this list that are unlikely to produce useful frequency tables. This is often the case for variables with a very large proportion of unique values. Use this option judiciously, as frequency tables are useful for detecting anomalies in the metadata.
freq.var.ignore <- config$freqvar$ignore
print(freq.var.ignore)
#'## Set Download Timeout
options(timeout = config$download$timeout)
#'## Knitr Options
#+
#'### Image Output File Formats
fig.format <- config$fig$format
print(fig.format)
#'### DPI for Raster Graphics
fig.dpi <- config$fig$dpi
print(fig.dpi)
#'### Alignment of Diagrams in Report
fig.align <- config$fig$align
print(fig.align)
#'### Set Knitr Options
knitr::opts_chunk$set(fig.path = outputdir,
dev = fig.format,
dpi = fig.dpi,
fig.align = fig.align)
#'# Manage Directories
#+
#'## Define Set of Data Directories
dirset <- c("EN_PDF_ORIGINAL_FULL",
"FR_PDF_ORIGINAL_FULL",
"EN_PDF_ENHANCED_max2004",
"FR_PDF_ENHANCED_max2004",
"EN_PDF_BEST_FULL",
"FR_PDF_BEST_FULL",
"EN_PDF_BEST_MajorityOpinions",
"FR_PDF_BEST_MajorityOpinions",
"EN_TXT_BEST_FULL",
"FR_TXT_BEST_FULL",
"EN_TXT_TESSERACT_max2004",
"FR_TXT_TESSERACT_max2004",
"EN_TXT_EXTRACTED_FULL",
"FR_TXT_EXTRACTED_FULL")
#'## Directory for Unlabelled Files
dir.unlabelled <- paste(datashort,
datestamp,
"UnlabelledFiles",
sep = "_")
#'## Clean up files from previous runs
delete <- list.files(pattern = "\\.pdf|\\.zip|\\.pdf|\\.csv|\\.tex")
unlink(delete)
for (dir in dirset){
unlink(dir, recursive = TRUE)
}
unlink(outputdir, recursive = TRUE)
unlink(dir.unlabelled, recursive = TRUE)
unlink("temp", recursive = TRUE)
#'## Create directories
for (dir in dirset){
dir.create(dir)
}
dir.create("temp")
dir.create(dir.unlabelled)
dir.create(outputdir)
#'# LaTeX Configuration
#+
#'### Construct LaTeX Definitions
latexdefs <- c("%===========================\n% Definitions\n%===========================",
"\n% NOTE: This file was created automatically during the compilation process.\n",
"\n%-----Version-----",
paste0("\\newcommand{\\version}{",
datestamp,
"}"),
"\n%-----Titles-----",
paste0("\\newcommand{\\datatitle}{",
config$project$fullname,
"}"),
paste0("\\newcommand{\\datashort}{",
config$project$shortname,
"}"),
paste0("\\newcommand{\\softwaretitle}{Source Code for the \\enquote{",
config$project$fullname,
"}}"),
paste0("\\newcommand{\\softwareshort}{",
config$project$shortname,
"-Source}"),
"\n%-----Data DOIs-----",
paste0("\\newcommand{\\dataconceptdoi}{",
config$doi$data$concept,
"}"),
paste0("\\newcommand{\\dataversiondoi}{",
config$doi$data$version,
"}"),
paste0("\\newcommand{\\dataconcepturldoi}{https://doi.org/",
config$doi$data$concept,
"}"),
paste0("\\newcommand{\\dataversionurldoi}{https://doi.org/",
config$doi$data$version,
"}"),
"\n%-----Software DOIs-----",
paste0("\\newcommand{\\softwareconceptdoi}{",
config$doi$software$concept,
"}"),
paste0("\\newcommand{\\softwareversiondoi}{",
config$doi$software$version,
"}"),
paste0("\\newcommand{\\softwareconcepturldoi}{https://doi.org/",
config$doi$software$concept,
"}"),
paste0("\\newcommand{\\softwareversionurldoi}{https://doi.org/",
config$doi$software$version,
"}"))
#'\newpage
#'### Write LaTeX Definitions
writeLines(latexdefs,
"temp/CD-ICJ_Source_TEX_Definitions.tex")
#'## Write Package Citations
write_bib(c(.packages()),
"temp/packages.bib")
#'# Parallelization
#' Parallelization is used for many tasks in this script, e.g. for accelerating the conversion from PDF to TXT, OCR, analysis with **quanteda** and with **data.table**. The maximum number of cores will automatically be detected and used.
#'
#' The download of decisions from the ICJ website is not parallelized to ensure respectful use of the Court's bandwidth.
#'
#' The use of **fork clusters** is significantly more efficient than PSOCK clusters, although it restricts use of this script to Linux systems.
#+
#'## Detect Number of Logical Cores
#' This will detect the maximum number of threads (= logical cores) available on the system or set them according to the config file.
if(config$cores$max == TRUE){
fullCores <- detectCores()
}else{
fullCores <- config$cores$number
}
print(fullCores)
#'## Set Number of OCR Control Cores
#' **Note:** Reduced number of control cores for OCR, as Tesseract calls up to four threads by itself.
ocrCores <- round((fullCores / 4)) + 1
print(ocrCores)
#'## Data.table
setDTthreads(threads = fullCores)
#'## Quanteda
quanteda_options(threads = fullCores)
#'# Visualize Corpus Creation Process
#+
#'## Workflow Part 1
workflow1 <- "
digraph workflow {
# a 'graph' statement
graph [layout = dot, overlap = false]
# Legend
subgraph cluster1{
peripheries=1
9991 [label = 'Data Nodes', shape = 'ellipse', fontsize = 22]
9992 [label = 'Action Nodes', shape = 'box', fontsize = 22]
}
# Data Nodes
node[shape = 'ellipse', fontsize = 22]
100 [label = 'www.icj-cij.org']
101 [label = 'Links to Raw PDF Files']
102 [label = 'Unlabelled Files']
103 [label = 'Labelling Information']
104 [label = 'Labelled PDF Files']
105 [label = 'Handcoded Case Names']
106 [label = 'EN_PDF_ORIGINAL_FULL']
107 [label = 'EN_TXT_EXTRACTED']
108 [label = 'EN_TXT_TESSERACT_max2004']
109 [label = 'EN_PDF_ENHANCED_Max2004']
110 [label = 'EN_TXT_BEST']
111 [label = 'EN_PDF_BEST_FULL']
112 [label = 'EN_PDF_BEST_MajorityOpinions']
113 [label = 'FR_PDF_ORIGINAL_FULL']
114 [label = 'FR_TXT_EXTRACTED']
115 [label = 'FR_TXT_TESSERACT_max2004']
116 [label = 'FR_PDF_ENHANCED_Max2004']
117 [label = 'FR_TXT_BEST']
118 [label = 'FR_PDF_BEST_FULL']
119 [label = 'FR_PDF_BEST_MajorityOpinions']
# Action Nodes
node[shape = 'box', fontsize = 22]
200 [label = 'Extract Links from HTML']
201 [label = 'Detect Unlabelled Files']
202 [label = 'Download Unlabelled Files']
203 [label = 'Handcoding of Labels']
204 [label = 'Apply Labelling']
205 [label = 'Strict REGEX Validation: ICJ File Name Schema']
206 [label = 'Download Module']
207 [label = 'File Split Module']
208 [label = 'Filename Enhancement Module']
209 [label = 'Strict REGEX Validation: Codebook File Name Schema']
210 [label = 'Detect Missing Language Counterparts']
211 [label = 'Text Extraction Module']
212 [label = 'Tesseract OCR Module']
213 [label = 'Create Majority Variant']
# Edge Statements
100 -> 200 -> 101 -> 201 -> 202 -> 102
102 -> 203 -> 103
{101, 103} -> 204 -> 205 -> 206 -> 104 -> 207 -> 208 -> 209 -> {106,113} -> 210 -> {211, 212}
105 -> 208
211 -> {107, 114}
212 -> {108, 109, 115, 116}
{107, 108} -> 110
{106, 109} -> 111
{114, 115} -> 117
{113, 115} -> 118
111 -> 213 -> 112
118 -> 213 -> 119
}
"
grViz(workflow1) %>% export_svg %>% charToRaw %>% rsvg_pdf("ANALYSIS/CD-ICJ_Workflow_1.pdf")
grViz(workflow1) %>% export_svg %>% charToRaw %>% rsvg_png("ANALYSIS/CD-ICJ_Workflow_1.png")
#' \begin{sidewaysfigure}
#'\includegraphics{ANALYSIS/CD-ICJ_Workflow_1.pdf}
#' \caption{Workflow Part 1: Download, Labelling, Conversion and Sorting of Documents}
#' \end{sidewaysfigure}
#+
#'## Workflow Part 2
workflow2 <- "
digraph workflow {
# Graph statement
graph [layout = dot, overlap = false]
# Data Nodes
node[shape = 'ellipse', fontsize = 22]
100 [label = 'EN_TXT_BEST']
101 [label = 'FR_TXT_BEST']
102 [label = 'EN_TXT_EXTRACTED']
103 [label = 'FR_TXT_EXTRACTED']
104 [label = 'EN_CSV_BEST_FULL']
105 [label = 'FR_CSV_BEST_FULL']
106 [label = 'EN_CSV_BEST_META']
107 [label = 'FR_CSV_BEST_META']
108 [label = 'ANALYSIS']
109 [label = 'Frequency Tables']
# Action Nodes
node[shape = 'box', fontsize = 22]
200 [label = 'OCR Quality Control Module']
201 [label = 'Clean Texts']
202 [label = 'Language Purity Module']
203 [label = 'Add Metadata']
204 [label = 'Calculate Frequency Tables']
205 [label = 'Visualize Frequency Tables']
206 [label = 'Calculate and Add Summary Statistics']
207 [label = 'Calculate Token Frequencies']
208 [label = 'Calculate Document Similarity']
209 [label = 'Write CSV Files']
# Edge Statements
{100, 101, 102, 103} -> 200
{100, 101} -> 201 -> 202 -> 203
203 -> 204 -> 109 -> 205
203 -> 206 -> 209
203 -> {207, 208}
{109, 204, 205, 206, 207, 208} -> 108
209 -> {104, 105, 106, 107}
}
"
grViz(workflow2) %>% export_svg %>% charToRaw %>% rsvg_pdf("ANALYSIS/CD-ICJ_Workflow_2.pdf")
grViz(workflow2) %>% export_svg %>% charToRaw %>% rsvg_png("ANALYSIS/CD-ICJ_Workflow_2.png")
#' \begin{sidewaysfigure}
#'\includegraphics{ANALYSIS/CD-ICJ_Workflow_2.pdf}
#' \caption{Workflow Part 2: Ingestion, Pre-Processing, Analysis and Creation of CSV Files}
#' \end{sidewaysfigure}
#+
#'# Prepare Download
#+
#'## Define Download Scope
caseno.full <- setdiff(caseno.begin:caseno.end,
caseno.exclude)
#'## Debugging Mode --- Reduced Scope
if(mode.debug.toggle == TRUE){
caseno.full <- c(sample(3:41,
mode.debug.sample),
116,
146,
150,
153,
156,
sample(157:caseno.end,
mode.debug.sample),
175)
caseno.full <- sort(unique(caseno.full))
}
#'## Show Function: f.linkextract
print(f.linkextract)
#'## Show Function: f.selectpdflinks
print(f.selectpdflinks)
#'## Prepare Empty Link List
links.list <- vector("list",
caseno.end)
#'## Acquire Download Links
for (caseno in caseno.full) {
URL.JUD <- sprintf("https://www.icj-cij.org/en/case/%d/judgments",
caseno)
volatile <- f.linkextract(URL.JUD)
links.jud <- f.selectpdflinks(volatile)
URL.ORD <- sprintf("https://www.icj-cij.org/en/case/%d/orders",
caseno)
volatile <- f.linkextract(URL.ORD)
links.ord <- f.selectpdflinks(volatile)
URL.ADV <- sprintf("https://www.icj-cij.org/en/case/%d/advisory-opinions",
caseno)
volatile <- f.linkextract(URL.ADV)
links.adv <- f.selectpdflinks(volatile)
links.list[[caseno]] <- c(links.jud,
links.ord,
links.adv)
print(caseno)
Sys.sleep(runif(1, 0.5, 1.5))
}
#'## Clean Links
links <- unlist(links.list)
links.download <- unique(links)
#'## Remove Specific Links
#' **Note 1:** All files related to the advisory opinion in Case 146 are bilingual, even the supposedly monolingual variants. This removes the monolingual variants without replacement. True monolingual variants will be generated via splitting the bilingual variants at a later stage.
#'
#' **Note 2:** The French files for cases 89, 125 and 156 are in fact mislabelled English variants. No French variants of the document are available on the website and even the bilingual variants are in fact entirely in English.
f1 <- "(089-19990629-ORD-01-00-FR)"
f2 <- "(125-20040709-ORD-01-00-FR)"
f3 <- "(146-20120201-ADV-01-00)"
f4 <- "(156-20150422-ORD-01-01-FR)"
links.download <- grep(paste(f1, f2, f3, f4, sep = "|"),
links.download,
invert = TRUE,
value = TRUE)
#'## Add Specific Links
#' All files related to the advisory opinion in Case 146 are bilingual, even the supposedly monolingual variants. This adds the official bilingual advisory opinion and adds the bilingual appended opinions which were not included in the original link list. These files will be split into monolingual variants at a later stage of the script.
links.download <- c(links.download,
"https://www.icj-cij.org/public/files/case-related/146/146-20120201-ADV-01-00-BI.pdf",
"https://www.icj-cij.org/public/files/case-related/146/146-20120201-ADV-01-01-BI.pdf",
"https://www.icj-cij.org/public/files/case-related/146/146-20120201-ADV-01-02-BI.pdf")
#'# Labelling Module
#' Almost two dozen ICJ documents are unlabelled, i.e. they are provided with a computer-generated number only. Their filenames encode no semantic information. This module corrects the filenames and applies the standard naming scheme employed by the ICJ.
#+
#'## List Unlabelled Files
unlabelled.temp <- grep("EN|FR|BI",
links.download,
invert = TRUE,
value = TRUE,
ignore.case = TRUE)
unlabelled.out <- data.table(sort(unlabelled.temp),
sort(unlabelled.temp))
print(unlabelled.temp)
#'## Write to Disk
fwrite(unlabelled.out,
paste0(dir.unlabelled,
"/",
datashort,
"_",
datestamp,
"_",
"UnlabelledFiles.csv"))
#'## Download Unlabelled Files
#' This is to prepare manual inspection and coding of unlabelled files.
#+
#'### Prepare
unlabelled.download.url <- unlabelled.temp
unlabelled.download.name <- gsub("\\/", "\\_",
unlabelled.temp)
unlabelled.download.name <- sub("\\_", "",
unlabelled.download.name)
dt <- data.table(unlabelled.download.url,
unlabelled.download.name)
#'### Number of Unlabelled Files to Download
dt[,.N]
#'### Timestamp (Unlabelled Download Begin)
begin.download <- Sys.time()
print(begin.download)
#'### Execute Download
#' **Note:** There is no download retry for this section, as these files are always inspected manually.
for (i in sample(dt[,.N])){
download.file(dt$unlabelled.download.url[i],
dt$unlabelled.download.name[i])
Sys.sleep(runif(1, 0.5, 1.5))
}
#'### Timestamp (Unlabelled Download End)
end.download <- Sys.time()
print(end.download)
#'### Duration (Download)
end.download - begin.download
#'## Download Result
#+
#'### Number of Files to Download
download.expected.N <- dt[,.N]
print(download.expected.N)
#'### Number of Files Successfully Downloaded
files.pdf <- list.files(pattern = "\\.pdf",
ignore.case = TRUE)
download.success.N <- length(files.pdf)
print(download.success.N)
#'### Number of Missing Files
missing.N <- download.expected.N - download.success.N
print(missing.N)
#'### Names of Missing Files
missing.names <- setdiff(dt$unlabelled.download.name,
files.pdf)
print(missing.names)
#'## Store Unlabelled Files
file_move(files.pdf,
dir.unlabelled)
#'## Manual Coding
#+
#########################################
### HANDCODING OF UNLABELLED FILES
##########################################
#'## Read in Corrected Labels
unlabelled.in <- fread("data/CD-ICJ_Source_UnlabelledFilesHandcoded.csv",
header = TRUE)
#'## Apply Correct Labels to Link List
links.corrected <- mgsub(links.download,
unlabelled.in$old,
unlabelled.in$new)
#'## Correct Underscores
links.corrected <- gsub("_", "-", links.corrected)
#'## Correct Date Error
links.corrected <- gsub("202206613", "20220613", links.corrected)
#'## Correct lowercasing
links.corrected <- gsub("adv", "ADV", links.corrected)
links.corrected <- gsub("ord", "ORD", links.corrected)
links.corrected <- gsub("jud", "JUD", links.corrected)
links.corrected <- gsub("-en[1c]?\\.pdf", "-EN.pdf", links.corrected)
links.corrected <- gsub("-fr[c]?\\.pdf", "-FR.pdf", links.corrected)
links.corrected <- gsub("-bi[c]?\\.pdf", "-BI.pdf", links.corrected)
#'## REGEX VALIDATION 1: Strictly Validate Links against ICJ Naming Scheme
#' Test strict compliance of proposed download names with naming scheme used by ICJ. The result of a successful test should be an empty character vector!
#+
#'### Execute Validation
regex.test1 <- grep(paste0("^[0-9]{3}", # var: caseno
"-",
"[0-9]{8}", # var: date
"-",
"(JUD|ADV|ORD)", # var: doctype
"-",
"[0-9]{2}", # var: collision
"-",
"[0-9]{2}", # var: opinion
"-",
"(EN|FR|BI)", # var: language
".pdf$"), # file extension,
basename(links.corrected),
invert = TRUE,
value = TRUE)
#'### Results of Validation
print(regex.test1)
#'### Stop Script on Failure
if (length(regex.test1) != 0){
stop("REGEX VALIDATION 1 FAILED: LINKS NOT IN COMPLIANCE WITH ICJ SCHEMA!")
}
#'## Detect Duplicate Filenames
links.corrected[duplicated(links.corrected)]
#'## Detect Missing Counterparts for each Language Version
linknames.en <- grep("EN.pdf",
links.corrected,
value=TRUE)
linknames.fr <- grep("FR.pdf",
links.corrected,
value=TRUE)
#'## Difference in Number of Files
length(linknames.en) - length(linknames.fr)
#'## Show Missing French Documents
linknames.fr.temp <- gsub("FR",
"EN",
linknames.fr)
frenchmissing <- setdiff(linknames.en,
linknames.fr.temp)
frenchmissing <- gsub("EN",
"FR",
frenchmissing)
print(frenchmissing)
#'## Show Missing English Documents
linknames.en.temp <- gsub("EN",
"FR",
linknames.en)
englishmissing <- setdiff(linknames.fr,
linknames.en.temp)
englishmissing <- gsub("FR",
"EN",
englishmissing)
print(englishmissing)
#'# Download Module
#+
#'## Prepare Download Table
dt <- data.table(links.download = links.download,
names.download = basename(links.corrected))
#'## Timestamp (Download Begin)
begin.download <- Sys.time()
print(begin.download)
#'## Execute Download (All Files)
result <- f.download(url = dt$links.download,
filename = dt$names.download,
dir = ".",
clean = FALSE,
sleep.min = 0.5,
sleep.max = 1,
retries = 3,
retry.sleep.min = 2,
retry.sleep.max = 5,
timeout = config$download$timeout,
debug.toggle = FALSE,
debug.files = 500)
#'## Timestamp (Download End)
end.download <- Sys.time()
print(end.download)
#'## Duration (Download)
end.download - begin.download