-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocess.js
executable file
·2085 lines (1826 loc) · 79.4 KB
/
process.js
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
// ##### ==============================================================================
// ##### This script is the main conductor for the branch (https://github.com/InvasionBiologyHypotheses/enKORE-corpus-processor)
// ##### This branch is under the umbrella of enKORE-project
// ##### As the main outcome, XML files are generated for publications sourced from a
// ##### a SPARQL submitted to Wikidata
// ##### ==============================================================================
// ##### Comment about meta and source of input data
// ##### Name: process.js
// ##### Purpose: Create a corpus for the EndPoint source BASE (https://www.base-search.net/about/en/about_sources_data.php)
// ##### Author: Steph Tyszka et al. (https://github.com/bootsa)
// ##### Version: unknown and in progress
// ##### Version-date: 00/00/0000
// ##### Additional comments: This conductor manages other scripts collecting information from three main sources, listed as:
// ##### (1) Wikidata, (2) CrossRef, (3) PubMed, and (4) PubMedCentral
// ##### Additional comments: This code is currently running in Toolforge, but implementations mostly locally.
// ##### Additional comments: N/A
// ##### ==============================================================================
// ##### Comment about the main functions
// ##### (1) The code starts with main(), which will then call processArgs() to process initial information;
// ##### (2) processArgs() will read process settings such as batchsize, sleepingtime, delays and so on;
// ##### (3) processArgs() will make use of fetchURLEntries() and saveFileEntries(), or of fetchFileEntries() to obtain entries.json (or other filename);
// ##### (4) After using processArgs(), main() will call getItemData() to run remaining functions for other tasks (e.g. get meta from Wikidata, Abstracts from CrossRef, PubMed and PubMedCentral etc)
// ##### ==============================================================================
// ##### Comment before the initialisation
// ##### Notes: N/A
// ##### ==============================================================================
// ###########################################
// ##### Import required modules (START) #####
// ###########################################
import { config } from "dotenv";
import { parse } from "deno-std-flags";
import * as retried from "retried";
import { readJSON, readJSONFromURL, writeJSON, writeTXT } from "flat-data";
import * as citationJS from "@citation-js/core";
import "@enkore/citationjs-plugin"; // #####
//import 'https://raw.githubusercontent.com/InvasionBiologyHypotheses/enKORE-citation-js-plugin/main/src/index.js';
// ##### Note: function to provide date now in UTM
import { function_DateNow } from "./lib/DateNow.js";
// ##### Note: function to log in different files when needed
import { function_log_new } from "./lib/log.js";
import { function_log_append } from "./lib/log.js";
// ##### Note: xmlexporter is imported to save contents to file(XML)
import { generateXML } from "./lib/xmlexporter.js"; // ##### Note: get needed information and scripts from (xmlexporter.js)
// ##### Note: xmlvalidator is imported to assess contents from file(XML)
// import { XMLvalidation_All } from "./lib/xmlvalidator.js"; // ##### Note: requires adjustment of paths
import get from "just-safe-get";
import extend from "just-extend";
import * as log from "deno-std-log";
// ##### Note: information about API's sources, logging and additional settings
import { abstractSources, logging, settings } from "./config.js"; // ##### Note: get needed information and scripts from (config.js)
// ##### Note: It is needed to bring some standard modules from Node to process some information
// ##### Note: https://reflect.run/articles/how-to-use-node-modules-in-deno/#:~:text=The%20Deno%20std%2Fnode%20library,to%20import%20and%20use%20Node.
import { createRequire } from "https://deno.land/[email protected]/node/module.ts";
const require = createRequire(import.meta.url);
import {
cron,
daily,
monthly,
weekly,
} from "https://deno.land/x/[email protected]/cron.ts";
// #########################################
// ##### Import required modules (END) #####
// #########################################
// ######################################################
// ##### Information for console debugging purposes #####
// ######################################################
const filename_this = "Log(process.js): "; // ##### Note: not needed because process.js is currently using dl.debug("string"), you may see config.js for details;
const sleep = (time = 1000) =>
new Promise((resolve) => setTimeout(resolve, time));
// #####################################################
// ##### Function to process all arguments (START) #####
// #####################################################
// ##### Note: This function is called by main()
// ##### Note: This function calls fetchURLEntries(), saveFileEntries(), and fetchFileEntries()
async function processArgs(args) {
const parsedArgs = parse(args, {
string: ["entries", "filename"],
alias: {
pull: "p", // ##### Note: If pull (false), then a filename must be given in (deno.jsonc)
url: "u",
items: "i",
// read: "r", // #### Note: using filename (file) directly to read when pull is false
file: "f",
offset: "o",
size: "s",
delay: "d",
reduce: "r",
},
default: {
pull: settings?.data?.pull || true,
url: settings?.data?.url || null,
items: settings?.data?.items || null,
// read: settings?.data?.read || false,
file: settings?.data?.file || null,
offset: settings?.processing?.initialOffset || 0,
size: settings?.processing?.batchSize || 10,
delay: settings?.processing?.processingDelay || 5000,
reduce: settings?.data?.reduce || false,
},
boolean: ["pull", "read", "reduce"],
negatable: ["pull", "read", "reduce"],
});
// ###############################################################
// ##### Pull from Url or Read from file the entries (START) #####
// ###############################################################
let entries = {};
if (parsedArgs.pull) {
// ##### Note: If true use get entries from Wikidata with fetchURLEntries
dl.debug("Log(processArgs): Pulling entries from URL");
const retrieved = await fetchURLEntries(parsedArgs.url); // ##### Note: (await) pass with asynchronous function
extend(entries, retrieved);
if (parsedArgs.file) {
await saveFileEntries(parsedArgs.file, retrieved); // ##### Note: If filename to save entries is given in (deno.jsonc) or (config.js) then save entries to it
}
} else {
dl.debug("Log(processArgs): Pulling entries from provided file");
//if (parsedArgs.read && parsedArgs.file) { // ##### Note: If (No Pull) with read (true) and filename (given)
if (parsedArgs.file) {
// ##### Note: If (No Pull) and filename (given)
dl.debug(`Log(processArgs): Fetching file: ${parsedArgs.file}`);
const read = await fetchFileEntries(parsedArgs.file); // ##### Note: (await) pass with asynchronous function
extend(entries, read);
}
}
// #############################################################
// ##### Pull from Url or Read from file the entries (END) #####
// #############################################################
// #################################################
// ##### Re-processing list of entries (START) #####
// #################################################
// let reduce_entries = parsedArgs.reduce;
// ##### Note: If reduce_entries = true, then it cannot read from a given file
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
let reduce_entries = true; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (reduce_entries == true) {
// #############################################
// ##### Note:Generating reduced file
let file2reduce = "./corpus/entries_log1.json";
//let file2reduce = "./corpus/entries_test1.json";
if (parsedArgs.pull) {
let total_sleep = Math.round(
Number(`${entries?.results?.bindings?.length}`) / 1000,
);
dl.debug(
`Waiting [${total_sleep}] seconds to write file: ${file2reduce}`,
);
await sleep(total_sleep * 1000); // ##### Note: (await) pass with asynchronous function
}
let entries_json_obj = await readJSON(file2reduce).catch((error) => {
// ##### Note: ERROR-FETCH // ##### Note: (await) pass with asynchronous function
dl.error(`Log(fetchFileEntries): ERROR: ${error}`);
Deno.exit(1);
});
// ##### Note: Obtaining header and results objects
let json_head_obj = entries_json_obj.head;
let json_results_obj = entries_json_obj.results;
// ##### Note: Obtaining header and results strings
let json_head_string = '"head":' + JSON.stringify(json_head_obj);
let json_results_string = '"results":' + JSON.stringify(json_results_obj);
// dl.debug('{' + json_head_string + "," + json_results_string + '}'); // ##### Note: checking merged json-strings
let jsonAllObj_new = JSON.parse('{ "results":{"bindings":[]} }'); // ##### Note: Creating an empty object to be appended with unique elements
// dl.debug(``);
// dl.debug(`${JSON.stringify(jsonAllObj_new)}`);
let ii = 0; // ##### Note: index for the buiding jsonAllObj_new
for (let i = 0; i < entries_json_obj.results.bindings.length; i++) {
dl.debug(`Object-index obtained from original file of entries: [${i}]`); // ##### Note: index for the jsonAllObj_old
if (i == 0) {
ii++; // ##### Note: First element must be unique! Therefore, no checkig condition required.
// ##### Note: Below we append the information (only the URL is needed)
// let url2check = entries_json_obj.results.bindings[i].item;
// jsonAllObj_new.results.bindings[ii-1] = url2check;
const obj1 = JSON.parse(
'{ "item": ' +
JSON.stringify(entries_json_obj.results.bindings[i].item) +
" }",
);
jsonAllObj_new.results.bindings[ii - 1] = obj1;
// dl.debug(`Log(processArgs): url2check: ${JSON.stringify(url2check)}`); // ##### Note: This line can be removed, but visually better to keep.
} else if (i > 0) {
let jsonAllObj_old = entries_json_obj.results.bindings[i];
let url2check = jsonAllObj_old.item.value; // ##### Note: element to compare across growing-jsonAllOjb
dl.debug(
`Log(processArgs): URL (i.e. url2check): ${JSON.stringify(
url2check,
)}`,
);
if (JSON.stringify(jsonAllObj_new).includes(url2check)) {
// ##### NOTE: IMPORTANT!
// ##### NOTE: PIECE BELOW CAN BE ADJUSTED TO WRITE A NEW FILE CONTAINING INFORMATION WITHOUT REPETITIONS OF URLs
// ##### NOTE: HOWEVER, THE NEW FILE WOULD CONTAIN REPETITIONS OF KEYS CONTAINING SAME AND DIFFERENT VALUES
dl.debug(
`Log(processArgs): URL (i.e. url2check) exists: No URL to be appended.`,
); // ##### Note: Append only contents that are missing
// ##### Note: Finding the item inside jsonAllObj_new that contains url2check so it can be appended with extra missig information
// ##### Note: You cannot append the same URL twice to avoid redownloading it.
for (let j = 0; j < jsonAllObj_new.results.bindings.length; j++) {
if (
JSON.stringify(jsonAllObj_new.results.bindings[j]).includes(
url2check,
)
) {
// ##### Note: here we define index of jsonAllObj_new containing url2check
let Obj1 = jsonAllObj_new.results.bindings[j]; // ##### Note: Assign as an object
let Obj2 = jsonAllObj_old; // ##### Note: Retransmitting the object
delete Obj2.item; // ##### Note: Removing only the URL from retransmitted object
// ##### Note (ERROR): let Obj3 = Object.assign(Obj1, Obj2); Dos not preserve same key with different values. Therefore, working with strings.
let Obj1_str = JSON.stringify(Obj1); // ##### Note: Convert to string for a merge
let Obj2_str = JSON.stringify(Obj2); // ##### Note: Convert to string for a merge
let Obj3_str = (
Obj1_str.slice(0, -1) +
"," +
Obj2_str.slice(1, Obj2_str.length)
)
.replace(/\\/g, "")
.replace(/"/g, ""); // ##### Note: removing some characters
// ##### Note (ERROR) let Obj3 = JSON.parse(Obj3_str); it deletes identical keys that contain same values and different values
let Obj3 = {
Obj3_str,
};
// ##### Note: Line below are just for checking merged information into new appended object
// console.log(``);
// console.log(`OBJECT-1 (objnew): ${JSON.stringify(Obj1)}`);
// console.log(``);
// console.log(`OBJECT-2 (objold): ${JSON.stringify(Obj2)}`);
// console.log(``);
// console.log(`OBJECT-3 (merged): ${Obj3_str}`);
// console.log(``);
// console.log(`OBJECT-3 (merged): ${JSON.stringify(Obj3)}`);
// jsonAllObj_new.results.bindings[j] = Obj3; // ##### Note: To replace results with appended new result
}
}
} else {
dl.debug(
`Log(processArgs): URL (i.e. url2check) does not exist in buiding entries.json (here defined as jsonAllObj_new): Appending URL from (jsonAllObj_old) to (jsonAllObj_new).`,
); // ##### Note: Append all contents
ii++;
// ##### Note: Below we append the information (only the URL is needed)
// jsonAllObj_new.results.bindings[ii-1] = entries_json_obj.results.bindings[i].item;
const obj1 = JSON.parse(
'{ "item": ' +
JSON.stringify(entries_json_obj.results.bindings[i].item) +
" }",
);
jsonAllObj_new.results.bindings[ii - 1] = obj1;
}
}
dl.debug(``);
dl.debug(
`Given index number for the new reduced file of entries: [${ii}]`,
);
dl.debug(``);
dl.debug(
`(jsonAllObj_new) total URLs is: ${JSON.stringify(
jsonAllObj_new.results.bindings.length,
)}`,
);
dl.debug(``);
}
// Note: var/const jsonAllObj_new_str = JSON.stringify(jsonAllObj_new); does not allow beaultify json (Ctrl+Shift+I)
let jsonAllObj_new_str = JSON.stringify(jsonAllObj_new); // ##### Note: var
dl.debug(`Log(processArgs): New temporary reduced list of entries is:`);
dl.debug(`${jsonAllObj_new_str}`);
// ##### Note: To confirm that string to be saved is a valid json
// function_log_new('./corpus/','reduced_entries.json',jsonAllObj_new_str);
const fs = require("fs/promises");
// ##### Note (IMPORTANT): You must await here for file to be written!!!
await fs.writeFile("./corpus/reduced_entries.json", jsonAllObj_new_str); // ##### Note: (await) pass with asynchronous function
// #################################################
// ##### Note: Reading entries from new reduced file
function_log_append(
"./logs/",
"Log_entries.txt",
`Log(fetchFileEntries): Replacing entries sourced from above-defined with entries indicated below`,
);
// ##### Note: You must await for the new file below
const read = await fetchFileEntries("./corpus/reduced_entries.json"); // ##### Note: (await) pass with asynchronous function
extend(entries, read);
}
// ###############################################
// ##### Re-processing list of entries (END) #####
// ###############################################
// ##### Note: Below we will display URLs to be accessed (repetitions can occur depending on which entries.json is used) #####
let items = [];
if (parsedArgs.items) {
items = [...items, ...parsedArgs?.items?.split("|")];
dl.debug("Log(processArgs): Extracting entries from parsedArgs.items");
} else {
items = entries?.results?.bindings?.map((x) => x?.item?.value) || [];
dl.debug("Log(processArgs): Extracting entries from file");
}
// ##### Note: The repetitions of some URLs are not displayed in the total below.
// ##### Note: There may be repetitions depending on the entries.json
dl.debug(
`Log(processArgs): List of URLs for processing (further repetitions of URL-requesting can occur depending on which entries.json is used): ${items}`,
);
dl.debug(
`Log(processArgs): Total URLs for processing (further repetitions of URL-requesting can occur depending on which entries.json is used) = ${items.length}`,
);
// #################################################################
// ##### To empty files of WikidataItems not in SPARQL (START) #####
// #################################################################
const files_emptied = await checkWikidataItem(items); // ##### Note: (await) pass with asynchronous function
dl.debug(
`Log(processArgs) checking empty and non-empty items: ${files_emptied}!`,
);
// ###############################################################
// ##### To empty files of WikidataItems not in SPARQL (END) #####
// ###############################################################
return { parsedArgs, items };
}
// ###################################################
// ##### Function to process all arguments (END) #####
// ###################################################
// ##### Note: Function content transferred to ./lib
// ############################################
// ##### Function to get DateNow (START) #####
// ############################################
// ##### Note: To mostly get stamp-time for log-files
// async function function_DateNow() {
// }
// ##########################################
// ##### Function to get Date-now (END) #####
// ##########################################
// ##### Note: Function content transferred to ./lib
// ###################################
// ##### Function to log (START) #####
// ###################################
// ##### Note: To write logs in independent files
// async function function_log_append(dir,filename,c) {
// }
// #################################
// ##### Function to log (END) #####
// #################################
// ####################################################
// ##### Function to get URL entries-list (START) #####
// ####################################################
// ##### Note: Requesting information via SPARQL to Wikidata, which is used to create entries.json
// ##### Note: This function is called by processArgs()
async function fetchURLEntries(url) {
if (!url) {
function_log_append(
"./logs/",
"Log_entries.txt",
`Log(fetchURLEntries): No url: ${url}. Exiting...`,
);
dl.error(`Log(fetchURLEntries): No url: ${url}. Exiting...`); // ##### Note: ERROR-FETCH
Deno.exit(1);
return;
}
function_log_append(
"./logs/",
"Log_entries.txt",
`Log(fetchURLEntries): Fetching entries from ${url}`,
);
dl.debug(`Log(fetchURLEntries): Fetching entries from ${url}`);
const entries = await readJSONFromURL(url); // ##### Note: (await) pass with asynchronous function
dl.debug(
`Log(fetchURLEntries): Entries retrieved from url: ${entries?.results?.bindings?.length}`,
);
return entries;
}
// ##################################################
// ##### Function to get URL entries-list (END) #####
// ##################################################
// #################################################
// ##### Function to save entries.json (START) #####
// #################################################
// ##### Note: Saving information returned from fetchURLEntries
// ##### Note: This function is called by processArgs()
async function saveFileEntries(file, entries) {
const fileSave = await writeJSON(file, entries, null, 2); // ##### Note: (await) pass with asynchronous function
dl.debug(`Log(saveFileEntries): File written: ${file} - ${fileSave}`);
return fileSave;
}
// ###############################################
// ##### Function to save entries.json (END) #####
// ###############################################
// ################################################
// ##### Function to get URL contents (START) #####
// ################################################
// ##### Note: Requesting information for each files listed in entries.json
// ##### Note: This function is called by processArgs()
async function fetchFileEntries(file) {
if (!file) return; // ##### Note: VIP-Flag
const entries = await readJSON(file).catch((error) => {
// ##### Note: ERROR-FETCH // ##### Note: (await) pass with asynchronous function
dl.error(`Log(fetchFileEntries): ERROR: ${error}`);
Deno.exit(1);
});
//let total_entries = String(entries.length); // ##### Note: Total is not passing, but can be included in the string below.
function_log_append(
"./logs/",
"Log_entries.txt",
`Log(fetchFileEntries): Fetching entries retrieved from file: ${file}`,
);
dl.debug(
`Log(fetchFileEntries): Fetching entries retrieved from file: ${file}`,
);
return entries;
}
// ##############################################
// ##### Function to get URL contents (END) #####
// ##############################################
// ######################################################################
// ##### Function to check requested and saved WikidataItem (START) #####
// ######################################################################
// ##### Note: To check items not listed in entries, which must be emptied.
// ##### Note: Using Node.js module: fs.readdirSync and fs.readFile
// ##### Note: This function is called by processArgs()
async function checkWikidataItem(items) {
// ##### Note: For LOOP-1
const fs = require("fs");
const files = fs.readdirSync("./corpus/processed/"); // ##### Note: Existing XML files in directory (/corpus/processed)
const files_list = files;
let total_files = files_list.length;
// dl.debug("Log(checkWikidataItem): Existing files:");
// dl.debug(files); // ##### Note: Display files in directory (/corpus/processed)
// ##### Note: For LOOP-2
const str_replace1 = "http://www.wikidata.org/entity/"; // ##### Note: string to replace in list of URL
const str_replace2 = ""; // ##### Note: string to replace in list of URL
const items_list = items;
// ##### Note: Control for how many files were emptied and replaced
let total_files_emptied = 0;
let total_files_replaced = 0;
// ##### Note: loop over elements already saved in directory (/corpus/processed)
for (let i = 0; i < files_list.length; i++) {
const files_list_i = String(files_list[i]);
// dl.debug(files_list_i); // ##### Note: item already saved in directory (processed)
// dl.debug("============");
let keep_wikidataitem_saved = 0;
for (let j = 0; j < items_list.length; j++) {
const string_list_j = String(items_list[j]).replace(
str_replace1,
str_replace2,
);
// dl.debug(string_list_j); // ##### Note: ULR reduced to ID of WikidataItem
// dl.debug("= = = = =");
const string_list_j2 = `${string_list_j}.xml`; // ##### Note: appending extension to lock end of string.
if (files_list_i.includes(string_list_j2)) {
keep_wikidataitem_saved++;
}
}
if (keep_wikidataitem_saved == 0) {
const item1 = fs.statSync(`./corpus/processed/${files_list_i}`); // ##### Note: item-size
const item2 = fs.statSync("./corpus/Template_emptied_XML.txt"); // ##### Note: template-size
// dl.debug(`${item1.size}`); // ##### Note: item-size
// dl.debug(`${item2.size}`); // ##### Note: template-size
if (item1.size == item2.size) {
// ##### Note: Size must match size of the template
dl.debug(`Log(checkWikidataItem): Already empty file: ${files_list_i}`);
dl.debug("Log(checkWikidataItem): Not writting to log.");
} else {
total_files_emptied++;
function_log_append(
"./logs/",
"Log_emptied_files.txt",
`Log(checkWikidataItem): Emptying file: ${files_list_i}`,
);
dl.debug(`Log(checkWikidataItem): Emptying file: ${files_list_i}`);
}
// ##### Note: content to write inside file to be emptied
try {
const fs_p = require("fs").promises;
const content = await fs_p.readFile(
"./corpus/Template_emptied_XML.txt",
); // ##### Note: (await) pass with asynchronous function
const filename = `./corpus/processed/${files_list_i}`;
await writeTXT(filename, content); // ##### Note: (await) pass with asynchronous function
dl.debug(
`Log(checkWikidataItem): template given [./corpus/Template_emptied_XML.txt] and considered to write file [${files_list_i}]`,
);
} catch (err) {
const content = "DELETED";
const filename = `./corpus/processed/${files_list_i}`;
await writeTXT(filename, content); // ##### Note: (await) pass with asynchronous function
dl.debug(
`Log(checkWikidataItem): template missing [./corpus/Template_emptied_XML.txt], so we are using (NULL) to write file [${files_list_i}]`,
);
}
} else {
dl.debug(
`Log(checkWikidataItem): Replacing existing item: ${files_list_i}`,
);
total_files_replaced++;
}
}
dl.debug(
`Log(checkWikidataItem): total items XML-pre-saved [${total_files}], XML-emptied[${total_files_emptied}], XML-replaced[${total_files_replaced}]`,
);
function_log_append(
"./logs/",
"Log_emptied_files.txt",
`# Total XML-emptied: #v1[${total_files_emptied}]#v1`,
);
return "COMPLETE";
}
// ####################################################################
// ##### Function to check requested and saved WikidataItem (END) #####
// ####################################################################
// ################################
// ##### Validade XML (START) #####
// ################################
// ##### Note: Validation of the XML-file via checking 1) hearder, 2) footer, and 3) body.
// ##### Note: (POSSIBILITY-CONSIDERED) XMLvalidation_All() can be applied when all XML files are created near the end of main().
// ##### Note: (POSSIBILITY-AVAILABLE) XMLvalidaiton_Each(filename) can be applied inside processItem(), and it can use the return from generateXML().
// ##### Note: It is possible to check validation online: https://validator.w3.org/. However, headers may be an issue, though acceptable.
// ##### Note: Using Node.js module: fs.readdirSync, fs.readFile (fs.readFileSync optional)
// ##### Note: This function is called by main()
// ##### IMPORTANT: It may be better emptying files not listed in the SPARQL-query, and then calling this function.
// ##### REASON: Tthere is not need to spend more time checking a file which will be later emptied.
async function XMLvalidation_All() {
// ##### Note: (dl.debug) were changed to (console.log), so that this function can be further transferred into /lib
// ##### Note: To send this function into ./lib requires internal paths' adjustments (for reading/deleting files from /processed etc)
// ##### Note: Also remember to change from (async) to (export), which is similar to function_log
const fs = require("fs");
const files_list = fs.readdirSync("./corpus/processed/"); // ##### Note: Existing XML files in directory (/corpus/processed)
console.log("");
console.log(
"Log(XMLvalidation_All): = = = = = = = = = = = = = = = = = = = =",
);
console.log(files_list); // ##### Note: List of XML-files to be validated, and including the emptied ones.
console.log(
"Log(XMLvalidation_All): = = = = = = = = = = = = = = = = = = = =",
);
console.log("");
let total_files = files_list.length;
let total_files_passed_full = 0;
let total_files_passed_empty = 0;
let total_files_failed = 0;
// ##### Note: loop over elements already saved in directory (/corpus/processed)
for (let i = 0; i < files_list.length; i++) {
const files_list_i = String(files_list[i]);
console.log(
"============ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",
);
console.log(files_list_i); // ##### Note: item already saved in directory (processed)
console.log("============");
const filename = `./corpus/processed/${files_list_i}`;
console.log(
"Log(XMLvalidation_All): ===== I ===== T ===== E ===== M =====",
);
console.log(`Log(XMLvalidation_All): ${filename}`);
// ##### Note: Temporary txt file to store XML string content
const filename_temp = "./corpus/processed/TEMP.txt";
const fs = require("fs");
fs.copyFile(filename, filename_temp, (err) => {
if (err) throw err;
// console.log('Temporary file copied');
});
// ##### Note: Reading the string content from XML_converted_to_TXT
const fs_p = require("fs").promises;
// ####################
const content = await fs_p.readFile(filename); // Note: To be used with asynchronous function
// const content = fs_p.readFile(filename); // Note: To be used with synchronous function (also in export function)
// ####################
const content_string = String(content);
// console.log("= = = = = =");
// console.log(content_string);
// ##### Note: Delete temporary file because XML-string is stored in variable (content_string)
fs.unlink(filename_temp, (err) => {
if (err) {
// throw err;
// console.log("Delete file failed.");
}
// console.log("Delete file successfully.");
});
// ##### Note: String containing XML information is now created.
// ##### Note: We are now assessing its validation
// ##### Note: Variable (content_string)
// ##### https://learn.microsoft.com/en-us/dotnet/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset (For C#)
// #############################################################
// ##### Note: Creating functions for validating XML files #####
// #############################################################
function XML_validator_option1(filename, content_string) {
// ###################################
// ##### OPTION-1: XML validator #####
// ###################################
// ##### Note: Hand-implemented to deal with different headers
const filename_string = filename;
let content_string2 = content_string.split("\n"); // ##### Note: Converting string to list of string for individual line assessment
if (content_string2.length > 1) {
// ##### Note: XML-files not found in SPARQL will come empty! That is [""].
console.log("Log(XMLvalidation_All): = = = = = =");
console.log("Log(XMLvalidation_All): XML-CONTENT-BELOW");
// console.log(content_string2);
console.log("Log(XMLvalidation_All): = = = = = =");
// ##### Note: List of strings to be confirmed inside the XML-content
const XML_row_1 =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
const XML_row_2 =
'<oai_dc:dc xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd">';
const XML_row_end = "</oai_dc:dc>";
let XML_row_1_value = 0; // ##### Note: to be changed to 1 when passing the checking.
let XML_row_2_value = 0; // ##### Note: to be changed to 1 when passing the checking.
let XML_row_end_value = 0; // ##### Note: to be changed to 1 when passing the checking.
for (let j = 0; j < content_string2.length; j++) {
// ##### Note: loop through the rows of the XML file
const content_string2_j = String(content_string2[j]);
// ################################
// ##### Quality-Check: row_1 #####
// ################################
if (j == 0) {
// ##### Note: (includes) or (equal) may suit below. However, (equal) would not accept empty spaces starting and ending the string.
if (content_string2_j.includes(XML_row_1)) {
console.log(
"Log(XMLvalidation_All): Quality check of row_1: PASSED!",
);
XML_row_1_value++; // ##### Note: adding 1 because it is passed.
} else {
console.log(
"Log(XMLvalidation_All): Quality check of row_1: FAILED!",
);
}
}
// ################################
// ##### Quality-Check: row_2 #####
// ################################
if (j == 1) {
// ##### Note: (includes) or (equal) may suit below. However, (equal) would not accept empty spaces starting and ending the string.
if (content_string2_j.includes(XML_row_2)) {
console.log(
"Log(XMLvalidation_All): Quality check of row_2: PASSED!",
);
XML_row_2_value++; // ##### Note: adding 1 because it is passed.
} else {
console.log(
"Log(XMLvalidation_All): Quality check of row_2: FAILED!",
);
}
}
// ##################################
// ##### Quality-Check: row_end #####
// ##################################
if (j == content_string2.length - 1) {
// ##### Note: (includes) or (equal) may suit below. However, (equal) may complicate due to empty spaces starting and ending the string.
if (content_string2_j.includes(XML_row_end)) {
console.log(
"Log(XMLvalidation_All): Quality check of row_end: PASSED!",
);
XML_row_end_value++; // ##### Note: adding 1 because it is passed.
} else {
console.log(
"Log(XMLvalidation_All): Quality check of row_end: FAILED!",
);
}
}
// #########################
// ##### Save DOI list #####
// #########################
// ##### Note: Saving DOI list to Log to be further used for NLP processing
if (
j > 1 &&
content_string2_j.includes("<dc:identifier>") &&
content_string2_j.includes("doi:")
) {
let doi_string = content_string2_j
.replace("<dc:identifier>", "")
.replace("doi:", "https://doi.org/")
.replace("</dc:identifier>", "")
.replaceAll(" ", "");
function_log_append("./logs/", "Log_DOI_list.txt", `${doi_string}`);
} else {
// console.log("Doi not found inside XML-file");
}
}
// ###########################
// ##### To write result #####
// ###########################
const XML_result_write = `Quality check all rows: row_1: ${XML_row_1_value}; row_2: ${XML_row_2_value}; row_end: ${XML_row_end_value}`;
console.log(`Log(XMLvalidation_All): ${XML_result_write}`);
const XML_filename_result_write = ` ${filename_string}: ${XML_result_write}`; // ##### Note: adding filename to save quality save information.
function_log_append(
"./logs/",
"Log_XMLvalidation.txt",
XML_filename_result_write,
);
let XML_result_value =
XML_row_1_value + XML_row_2_value + XML_row_end_value;
if (XML_result_value == 3) {
return "Validator-1: passed all.";
} else {
return "Validator-1: failed one at least.";
}
} else {
return "Validator-1: empty file.";
}
}
function XML_validator_option2(content_string) {
// ###################################
// ##### OPTION-2: XML validator #####
// ###################################
// ##### Note: You must have jsdom for DOM checking (see error message).
// ##### https://stackoverflow.com/questions/6334119/check-for-xml-errors-using-javascript
const content_string2 = content_string;
// ##### Note: Once it runs fine, just place in function!
try {
const jsdom = require("jsdom");
console.log(
"Log(XMLvalidation_All): PASSED: Module (jsdom) is available.",
);
} catch (err) {
console.log(
"Log(XMLvalidation_All): FAILED: You must install module (jsdom), which is currently missing.",
);
console.log(
"Log(XMLvalidation_All): For Ubuntu (check your distribution), run the following lines.",
);
console.log("Log(XMLvalidation_All): Line: $ sudo apt install npm");
console.log("Log(XMLvalidation_All): Line: $ npm install jsdom");
console.log(
"Log(XMLvalidation_All): Line: $ npm install xmlhttprequest",
);
}
const XML_result = "Validator-2: passed all.";
return XML_result;
}
function XML_validator_option3(content_string) {
// ###################################
// ##### OPTION-3: XML validator #####
// ###################################
// ##### Note: You must have fast-xml-parse.
// ##### https://www.npmjs.com/package/fast-xml-parser
const content_string2 = content_string;
// ##### Note: Once it runs fine, just place in function!
try {
const {
XMLParser,
XMLBuilder,
XMLValidator,
} = require("fast-xml-parser");
const parser = new XMLParser();
let jObj = parser.parse(XMLdata);
const builder = new XMLBuilder();
const xmlContent = builder.build(jObj);
console.log(
"Log(XMLvalidation_All): PASSED: Module (fast-xml-parser) is available.",
);
} catch (err) {
console.log(
"Log(XMLvalidation_All): FAILED: You must install module (fast-xml-parser), which is currently missing.",
);
console.log(
"Log(XMLvalidation_All): For Ubuntu (check your distribution), run the following lines.",
);
console.log("Log(XMLvalidation_All): Line: $ sudo apt install npm");
console.log(
"Log(XMLvalidation_All): Line: $ npm install fast-xml-parser",
);
}
const XML_result = "Validator-3: passed all.";
return XML_result;
}
// #####################################
// ##### Section to call validator #####
// #####################################
try {
// ##### Note: Passing function for validation.
const XML_validation_result = XML_validator_option1(
filename,
content_string,
);
console.log(
`Log(XMLvalidation_All): XML-VALIDATOR could properly check file ${filename}`,
);
console.log(
`Log(XMLvalidation_All): XML-RESULT - ${XML_validation_result}`,
);
console.log(`\n`);
// ##### Note: To write result into log here.
// ##### Note: Counter for passed and failed XML-files
if (XML_validation_result.includes("passed all")) {
total_files_passed_full++;
} else if (XML_validation_result.includes("empty file")) {
total_files_passed_empty++;
} else if (XML_validation_result.includes("failed one at least")) {
total_files_failed++;
}
} catch (err) {
console.log(
`Log(XMLvalidation_All):XML-VALIDATOR could !NOT! properly check file ${filename}. ERROR!`,
);
console.log(`\n`);
}
}
// ##### Note: To save totals to log
function_log_append(
"./logs/",
"Log_XMLvalidation.txt",
`# Total XML (passed) #v1[${total_files_passed_full}]#v1; Total XML (empty): #v2[${total_files_passed_empty}]#v2; Total (failed): #v3[${total_files_failed}]#v3`,
);
return "COMPLETE"; // ##### Note: This result is returned to main()
}
// ##############################
// ##### Validade XML (END) #####
// ##############################
// #########################################################
// ##### Function to request URL with Abstract (START) #####
// #########################################################
// ##### Note: To download the abstract.
// ##### Note: This function is called by findAbstract()
async function getAbstract(src, service) {
dl.debug(`Log(getAbstract): Entering getAbstract ${service?.name}`);
const id = src[service.wikidataProperty.label];
if (id == null) {
return null;
}
const url = service.url(id);
try {
const res = await fetch(url); // ##### Note: (await) pass with asynchronous function
if (res.ok) {
const data = await res.json(); // ##### Note: (await) pass with asynchronous function
const out = get(data, service.path);
return out;
} else if (res.status == "404") {
// ##### Note: ERROR-NOT-FOUND
return null;
}
} catch (error) {
dl.error(`Log(getAbstract): Abstract fetch error: ${error} - ${url}`); // ##### Note: ERROR-FETCH
} finally {
dl.debug(`Log(getAbstract): Exiting getAbstract ${service?.name}`);
}
}
// #######################################################
// ##### Function to request URL with Abstract (END) #####
// #######################################################
// ##################################################################
// ##### Function to extract Abstract from WikidataItem (START) #####
// ##################################################################
// ##### Note: This function aims to find Abstract is available in Wikidata
// ##### Note: This function is called by getItemData()
// ##### Note: This function calls getAbstract()
async function findAbstract(wikidataItem) {
dl.debug(`Log(findAbstract): Entering findAbstract`);
for (const source of abstractSources) {
const foundAbstract = await getAbstract(wikidataItem, source); // ##### Note: (await) pass with asynchronous function
if (foundAbstract) {
return foundAbstract;
}
}
dl.debug(`Log(findAbstract): Exiting getItemData`);
return null;
}
// ################################################################
// ##### Function to extract Abstract from WikidataItem (END) #####
// ################################################################
// ###################################################################
// ##### Function to request URL from CrossRef using DOI (START) #####
// ###################################################################
// ##### Note: To request information from Crossref
// ##### Note: This function is called by itself and getItemData()
async function getCrossrefItem(DOI, retries = 4, delay = 0) {
dl.debug(`Log(getCrossrefItem): Entering getCrossrefItem ${DOI}`);
await delay; // ##### Note: (await) pass with asynchronous function
try {
const response = await fetch(
// ##### Note: (await) pass with asynchronous function
`https://api.crossref.org/works/${encodeURIComponent(DOI)}`,