-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert_starxml_to_bf.py
2470 lines (2215 loc) · 115 KB
/
convert_starxml_to_bf.py
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
# Purpose: Convert STAR XML to Bibframe RDF
import csv # for looking up institutes from our csv of luxembourg authority institutes
# import datetime
import html
import logging
import re
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta
import dateparser
import requests
import requests_cache
from decouple import config
# old fuzzy compare for reconciliations: using fuzzywuzzy
from fuzzywuzzy import fuzz, process
from rdflib import BNode, Graph, Literal, URIRef
from rdflib.namespace import RDF, RDFS, SKOS, XSD
from tqdm.auto import tqdm
import modules.abstract as abstract
import modules.helpers as helpers
import modules.instance_source_ids as instance_source_ids
import modules.instance_sources as instance_sources
import modules.local_api_lookups as localapi
import modules.mappings as mappings
import modules.namespace as ns
import modules.publication_types as publication_types
import modules.research_info as research_info
import modules.terms as terms
# import modules.contributions as contributions
# import modules.open_science as open_science
logging.basicConfig(
filename=datetime.now().strftime("logs/convert-starxml-to-bf-%Y_%m_%d_%H%M%S.log"),
level=logging.INFO,
)
RECORDS_FILE = config("RECORDS_FILE")
RECORDS_START = int(config("RECORDS_START"))
RECORDS_END = int(config("RECORDS_END"))
MAX_WORKERS = int(config("MAX_WORKERS"))
# TODO: new fuzzy compare: using the faster rapidfuzz as a drop-in replacement for fuzzywuzzy:
# from rapidfuzz import fuzz
# from rapidfuzz import process
# ror lookup api url for looking up organization contributors and the affiliations of persons:
# ROR_API_URL = f"{config('ROR_API_URL')}/organizations?affiliation="
ROR_API_URL = config("ROR_API_URL")
## crossref api stuff for looking up funders:
# set up friendly session by adding mail in request:
CROSSREF_FRIENDLY_MAIL = f"&mailto={config('CROSSREF_FRIENDLY_MAIL')}"
# for getting a list of funders from api ():
CROSSREF_API_URL = f"{config('CROSSREF_API_URL')}/funders?query="
## Caching requests:
urls_expire_after = {
# Custom cache duration per url, 0 means "don't cache"
# f'{SKOSMOS_URL}/rest/v1/label?uri=https%3A//w3id.org/zpid/vocabs/terms/09183&lang=de': 0,
# f'{SKOSMOS_URL}/rest/v1/label?uri=https%3A//w3id.org/zpid/vocabs/terms/': 0,
}
# a cache for ror requests
session_ror = requests_cache.CachedSession(
cache_name="requests_ror",
backend="redis",
allowable_codes=[200, 404],
expire_after=timedelta(days=30),
urls_expire_after=urls_expire_after,
)
# and a cache for the crossref api:
session_fundref = requests_cache.CachedSession(
cache_name="requests_fundref",
backend="redis",
allowable_codes=[200, 404],
expire_after=timedelta(days=30),
urls_expire_after=urls_expire_after,
)
# import csv of LUX authority institutes:
with open("institute_lux.csv", newline="") as csvfile:
reader = csv.DictReader(csvfile)
# save it in a list:
lux_institutes = list(reader)
# split string "known_names" into a list of strings on "##":
for institute in lux_institutes:
institute["known_names"] = institute["known_names"].split(" ## ")
# print("Und die ganze Tabelle:")
# print(dachlux_institutes)
# Create an "element tree" from the records in my selected xml file so we can loop through them and do things with them:
root = ET.parse(RECORDS_FILE)
# To see the source xml's structure, uncomment this function:
# def print_element(element, depth=0):
# print("\t"*depth, element.tag, element.attrib, element.text)
# for child in element:
# print_element(child, depth+1)
# for child in root.getroot()[:2]:
# print_element(child)
# We first set a few namespace objects for bibframe, schema.org and for our resources (the works and instances) themselves.
#
# Then, we create two graphs from the xml source file, one to generate triples for our bibframe profile output, and the other for the simplified schema.org profile.
#
# Finally, we bind the prefixes with their appropriate namespaces to the graphs.
# graph for bibframe profile:
records_bf = Graph()
# make the graph named for the records: just for clarity in the output:
records_bf = Graph(identifier=URIRef("https://w3id.org/zpid/bibframe/records/"))
# import the graph for kerndaten.ttl from PsychAuthors - we'll need it for
# matching person names to ids when the names in the records are unmatchable
# - we'll try to match alternate names from kerndaten:
kerndaten = Graph()
kerndaten.parse("ttl-data/kerndaten.ttl", format="turtle")
# Bind the namespaces to the prefixes we want to see in the output:
records_bf.bind("bf", ns.BF)
records_bf.bind("bflc", ns.BFLC)
records_bf.bind("works", ns.WORKS)
# records_schema.bind("works", WORKS)
records_bf.bind("instances", ns.INSTANCES)
records_bf.bind("pxc", ns.PXC)
records_bf.bind("pxp", ns.PXP)
records_bf.bind("lang", ns.LANG)
records_bf.bind("schema", ns.SCHEMA)
records_bf.bind("locid", ns.LOCID)
records_bf.bind("mads", ns.MADS)
records_bf.bind("roles", ns.ROLES)
records_bf.bind("relations", ns.RELATIONS)
records_bf.bind("genres", ns.GENRES)
records_bf.bind("contenttypes", ns.CONTENTTYPES)
records_bf.bind("issuances", ns.ISSUANCES) # issuance types
records_bf.bind("pmt", ns.PMT) # mediacarriers
records_bf.bind("licenses", ns.LICENSES) # licenses
# # Functions to do all the things
#
# We need functions for the different things we will do - to avoid one long monolith of a loop.
#
# This is where they will go. Examples: Create nodes for Idebtifiers, create nested contribution objects from disparate person entries in AUP, AUK, CS and COU fields, merge PAUP (psychauthor person names and ids) with the person's name in AUP...
#
# These functions will later be called at the bottom of the program, in a loop over all the xml records.
# Define a function to convert a string to camel case
def camel_case(s):
# Use regular expression substitution to replace underscores and hyphens with spaces,
# then title case the string (capitalize the first letter of each word), and remove spaces
s = re.sub(r"(_|-)+", " ", s).title().replace(" ", "")
# Join the string, ensuring the first letter is lowercase
return "".join([s[0].lower(), s[1:]])
def get_ror_org_country(affiliation_ror_id):
# given a ror id, get the country of the organization from the ror api:
# first, use only the last part of the ror id, which is the id itself:
affiliation_ror_id = affiliation_ror_id.split("/")[-1]
# the country name is in country.name in the json response
ror_request = session_ror.get(
f"{config('ROR_API_URL')}/v1/organizations/" + affiliation_ror_id,
timeout=20,
)
if ror_request.status_code == 200:
ror_response = ror_request.json()
if "country" in ror_response:
return ror_response["country"]["name"]
else:
logging.info("no country found for " + affiliation_ror_id)
return None
def add_instance_license(resource_uri, record):
"""Reads field COPR and generates a bf:usageAndAccessPolicy node for the resource_uri based on it. Includes a link to the vocabs/licenses/ vocabulary in our Skosmos. We'll probably only use the last subfield (|c PUBL) and directly build a skosmos-uri from it (and pull the label from there?). There are more specific notes in the migration aection of each license concept in Skosmos. Note: the license always applies to an instance (or an instancebundle), not to a work, since the license is about the publication, not the content of the publication - the work content might be published elsewhere with a different license. Manuel mentioned something like that already about being confused about different licenses for different versions at Crossref.
Args:
resource_uri (_type_): The node to which the usageAndAccessPolicy node will be added.
record (_type_): The PSYNDEX record from which the COPR field will be read.
"""
if record.find("COPR") is not None:
# get the last subfield of COPR:
try:
license_code = helpers.get_subfield(record.find("COPR").text, "c")
# get the german_label from |d:
license_german_label = helpers.get_subfield(record.find("COPR").text, "d")
# create a skosmos uri for the license:
SKOSMOS_LICENSES_PREFIX = "https://w3id.org/zpid/vocabs/licenses/"
# license_uri = URIRef(LICENSES + license_code)
# several cases and the different uris for the licenses:
if license_code == "CC":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "C00_1.0")
elif license_code == "PDM":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "PDM_1.0")
# CC BY 4.0
elif license_code == "CC BY 4.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY_4.0")
# CC BY-SA 4.0
elif license_code == "CC BY-SA 4.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-SA_4.0")
# CC BY-NC-ND 3.0
elif license_code == "CC BY-NC-ND 3.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC-ND_3.0")
# CC BY-NC-ND 4.0
elif license_code == "CC BY-NC-ND 4.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC-ND_4.0")
elif license_code == "CC BY-NC 1.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC_1.0")
elif license_code == "CC BY-NC 4.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC_4.0")
# CC BY-NC-ND 2.5
elif license_code == "CC BY-NC-ND 2.5":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC-ND_2.5")
# CC BY-NC-SA 4.0
elif license_code == "CC BY-NC-SA 4.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC-SA_4.0")
# CC BY-ND 4.0
elif license_code == "CC BY-ND 4.0":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-ND_4.0")
# CC BY-ND 2.5
elif license_code == "CC BY-ND 2.5":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-ND_2.5")
# CC BY (unknown version)
elif license_code == "CC BY":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY")
# CC BY-NC (unknown version)
elif license_code == "CC BY-NC":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC")
# CC BY-NC-SA (unknown version)
elif license_code == "CC BY-NC-SA":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC-SA")
# CC BY-SA (unknown version)
elif license_code == "CC BY-SA":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-SA")
# CC BY-NC-ND (unknown version)
elif license_code == "CC BY-NC-ND":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-NC-ND")
# CC BY-ND (unknown version)
elif license_code == "CC BY-ND":
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "CC_BY-ND")
# starts with "AUTH":
elif license_code.startswith("AUTH"):
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "AUTH")
# starts with "PUBL" or license_german_label starts with "Volles Urheberrecht des Verlags" > PUBL:
elif license_code.startswith("PUBL") or license_german_label.startswith(
"Volles Urheberrecht des Verlags"
):
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "PUBL")
# starts with starts with "Hogrefe OpenMind" -> HogrefeOpenMind
elif license_code.startswith("Hogrefe OpenMind"):
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "HogrefeOpenMind")
# contains contains "Springer"-> ExclusiveSpringer:
elif "Springer" in license_code:
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "ExclusiveSpringer")
# starts with "OTHER" -> UnspecifiedOpenLicense
elif license_code.startswith("OTHER"):
license_uri = URIRef(SKOSMOS_LICENSES_PREFIX + "UnspecifiedOpenLicense")
else:
logging.info(
f"no license uri found for {license_code} in record {record.find('DFK').text}"
)
license_uri = None
if license_uri is not None:
# add the license uri from skosmos directly:
license_node = license_uri
records_bf.set((license_node, RDF.type, ns.BF.UsePolicy))
records_bf.add((resource_uri, ns.BF.usageAndAccessPolicy, license_node))
# Get the label from skosmos:
try:
german_preflabel = localapi.get_preflabel_from_skosmos(
license_uri, "licenses", "de"
)
except:
logging.warning(
f"failed getting prefLabels for license {license_uri}"
)
german_preflabel = None
try:
english_preflabel = localapi.get_preflabel_from_skosmos(
license_uri, "licenses", "en"
)
except:
logging.warning(
f"failed getting prefLabels for license {license_uri}"
)
english_preflabel = None
# add the prefLabels to the license node:
if german_preflabel is not None:
records_bf.add(
(
license_node,
SKOS.prefLabel,
Literal(german_preflabel, lang="de"),
)
)
else:
logging.warning(f"no german prefLabel found for {license_uri}")
if english_preflabel is not None:
records_bf.add(
(
license_node,
SKOS.prefLabel,
Literal(english_preflabel, lang="en"),
)
)
records_bf.set(
(license_node, RDFS.label, Literal(english_preflabel))
)
else:
logging.warning(f"no english prefLabel found for {license_uri}")
# english_preflabel = localapi.get_preflabel_from_skosmos(license_uri, "licenses", "en")
# TODO: get url for license itself from skosmos (e.g. creative commons deed url)
except:
logging.warning(
f"no valid license found for record {record.find('DFK').text}: {record.find('COPR').text}"
)
else:
logging.warning(f"record {record.find('DFK').text} has no license!")
def add_work_classification(work_uri, record):
pass
def add_additional_descriptor(work_uri, record):
"""Reads any fields `IT` and adds the descriptor as a bf_subject > bf:Topic. Looks up the URI of that concept using the Skomos API. Note that the IT will be added like any other PSYNDEX (APA) Term. We may add the IT vocab as a different "source" to tell them apart. In the furture, these two vocabs will be integrated, and there is already only one input field in PSYNDEXER for it.
TODO: May merge this functionality into the subject function, so that it can be used for both IT and CT fields.
Args:
work_uri (_type_): The work to which the subject/topics will be added.
record (_type_): The record from which the IT fields will be read.
"""
def get_publication_date(record):
"""Get the publication date from the record's PHIST or PY field and return it as a Literal.
Args:
record (_type_): The record from which the publication date will be read.
Returns:
_type_: The publication date as a Literal, either YYYY or, if from PHIST, YYYY-MM-DD.
"""
# from field PHIST or PY, get pub date and return this as a Literal
# get date from PHIST field, it exists, otherwise from P> field:
if record.find("PHIST") is not None and record.find("PHIST").text != "":
try:
date = helpers.get_subfield(record.find("PHIST").text, "o")
# clean up anything that's not a digit at the start, such as ":" - make sure with a regex that date starts with a digit:
date.strip()
# parse the date: it can be either "8 June 2021" or "08.06.2021"
# parse and convert this to the yyyy-mm-dd format:
date = dateparser.parse(date).strftime("%Y-%m-%d")
except:
logging.warning(
f"parsedate: couldn't parse ${str(date)} for record ${record.find('DFK').text}"
)
logging.warning(
"Data in PHIST looks like an unsalvagable mess, using PY insead!"
)
try:
date = record.find("PY").text
except:
logging.warning(
f"record ${record.find('DFK').text} has no valid publication date!"
)
date = None
else:
# print("no date found in PHIST, using PY")
try:
date = record.find("PY").text
except:
logging.warning(
f"record ${record.find('DFK').text} has no valid publication date!"
)
date = None
return date
def add_isbns(record, instancebundle_uri):
"""Reads the record's PU field and adds any ISBNs found in it as bf:identifiedBy nodes to the instancebundle_uri.
Args:
record (_type_): _description_
instancebundle_uri (_type_): _description_
"""
# if there is a PU, find subfield |i and e
try:
pu = record.find("PU")
except:
pu = None
if pu is not None and pu.text != "":
try:
isbn_print = helpers.get_subfield(pu.text, "i")
except:
isbn_print = None
try:
isbn_ebook = helpers.get_subfield(pu.text, "e")
except:
isbn_ebook = None
if isbn_print is not None:
isbn_print_node = URIRef(str(instancebundle_uri) + "#isbn_print")
records_bf.set((isbn_print_node, RDF.type, ns.BF.Isbn))
records_bf.set((isbn_print_node, RDF.value, Literal(isbn_print)))
records_bf.add((instancebundle_uri, ns.BF.identifiedBy, isbn_print_node))
if isbn_ebook is not None:
isbn_ebook_node = URIRef(str(instancebundle_uri) + "#isbn_ebook")
records_bf.set((isbn_ebook_node, RDF.type, ns.BF.Isbn))
records_bf.set((isbn_ebook_node, RDF.value, Literal(isbn_ebook)))
records_bf.add((instancebundle_uri, ns.BF.identifiedBy, isbn_ebook_node))
# Adding isbns by type to their repsective instance - by mediaCarrier. TODO: Make this actually work!
# Check all the instances of this work whether they are print or online mediacarrier. If so, add appropriate isbn to them:
# for instance in records_bf.objects(work_uri, ns.BF.hasInstance):
# if isbn_print is not None:
# if records_bf.value(instance, RDF.type) == ns.BF.Print:
# isbn_print_node = URIRef(str(instance) + "_isbn")
# records_bf.set((isbn_print_node, RDF.type, ns.BF.Isbn))
# records_bf.set((isbn_print_node, RDF.value, Literal(isbn_print)))
# records_bf.add((instance, ns.BF.identifiedBy, isbn_print_node))
# else:
# print("found no place for print isbn: " + isbn_print)
# # try:
# # instance_bundle = records_bf.value(work_uri, PXP.hasInstanceBundle)
# # isbn_print_node = URIRef(str(instance_bundle) + "_isbn")
# # records_bf.set((isbn_print_node, RDF.type, ns.BF.Isbn))
# # records_bf.set(
# # (isbn_print_node, RDF.value, Literal(isbn_print))
# # )
# # records_bf.add((instance_bundle, ns.BF.identifiedBy, isbn_print_node))
# # except:
# # print("failed adding print isbn")
# # why are they not being added? maybe we should try to add singletons to singleton Instances, at least?
# if isbn_ebook is not None:
# if records_bf.value(instance, RDF.type) == ns.BF.Electronic:
# isbn_ebook_node = URIRef(str(instance) + "_isbn")
# records_bf.set((isbn_ebook_node, RDF.type, ns.BF.Isbn))
# records_bf.set((isbn_ebook_node, RDF.value, Literal(isbn_ebook)))
# records_bf.add((instance, ns.BF.identifiedBy, isbn_ebook_node))
# else:
# print("found no place for e-issn: " + isbn_ebook)
def match_paups_to_contribution_nodes(work_uri, record):
# go through all PAUP fields and get the id:
for paup in record.findall("PAUP"):
paup_id = helpers.get_subfield(paup.text, "n")
paup_name = helpers.get_mainfield(paup.text)
# get the given and family part of the paup name:
paup_split = paup_name.split(",")
paup_familyname = paup_split[0].strip()
paup_givenname = paup_split[1].strip()
paupname_normalized = normalize_names(paup_familyname, paup_givenname)
# print("paupname_normalized: " + paupname_normalized)
# go through all bf:Contribution nodes of this work_uri, and get the given and family names of the agent, if it is a person:
for contribution in records_bf.objects(work_uri, ns.BF.contribution):
# get the agent of the contribution:
agent = records_bf.value(contribution, ns.BF.agent)
# if the agent is a person, get the given and family names:
if records_bf.value(agent, RDF.type) == ns.BF.Person:
# get the given and family names of the agent:
givenname = records_bf.value(agent, ns.SCHEMA.givenName)
familyname = records_bf.value(agent, ns.SCHEMA.familyName)
aupname_normalized = normalize_names(familyname, givenname)
# print("aupname_normalized: " + aupname_normalized)
# if the paupname_normalized matches the agent's name, add the paup_id as an identifier to the agent:
# if paupname_normalized == aupname_normalized:
# check using fuzzywuzzy:
# use partial_ratio for a more lenient comparison - so we can check if one of the them is a substring of the other - for double names, etc.:
if fuzz.partial_ratio(paupname_normalized, aupname_normalized) > 80:
# create a fragment uri node for the identifier:
paup_id_node = URIRef(str(agent) + "_psychauthorsid")
# make it a locid:psychAuthorsID:
records_bf.set((paup_id_node, RDF.type, ns.PXC.PsychAuthorsID))
# add the paup id as a literal to the identifier node:
records_bf.add((paup_id_node, RDF.value, Literal(paup_id)))
# add the identifier node to the agent node:
records_bf.add((agent, ns.BF.identifiedBy, paup_id_node))
# print("paup_id added to agent: " + paup_id)
# and break the loop:
break
# after all loops, print a message if no match was found:
else:
logging.info(
"no match found for paup_id "
+ paup_id
+ " ("
+ paup_name
+ ")"
+ " in record "
+ record.find("DFK").text
+ ". Checking name variants found in kerndaten for this id..."
)
# loop through the contribtors again, and check if any of the alternate names from psychauthors kerndaten match a person's name from AUP:
for contribution in records_bf.objects(work_uri, ns.BF.contribution):
# get the agent of the contribution:
agent = records_bf.value(contribution, ns.BF.agent)
# if the agent is a person, get the given and family names:
if records_bf.value(agent, RDF.type) == ns.BF.Person:
# get the given and family names of the agent:
givenname = records_bf.value(agent, ns.SCHEMA.givenName)
familyname = records_bf.value(agent, ns.SCHEMA.familyName)
aupname_normalized = normalize_names(familyname, givenname)
# try to match the paup_id to a uri in kerndaten.ttl and check if any of the alternate names match the agent's name:
person_uri = URIRef("https://w3id.org/zpid/person/" + paup_id)
for alternatename in kerndaten.objects(
person_uri, ns.SCHEMA.alternateName
):
# split the alternatename into family and given name:
alternatename_split = alternatename.split(",")
alternatename_familyname = alternatename_split[0].strip()
alternatename_givenname = alternatename_split[1].strip()
# normalize the name:
alternatename_normalized = normalize_names(
alternatename_familyname, alternatename_givenname
)
# if the alternatename matches the agent's name, add the paup_id as an identifier to the agent: again using fuzzywuzzy'S partial ratio to also match substrings of the name inside each other:
if (
fuzz.partial_ratio(
alternatename_normalized, aupname_normalized
)
> 80
):
# create a fragment uri node for the identifier:
paup_id_node = URIRef(str(agent) + "_psychauthorsid")
# make it a locid:psychAuthorsID:
records_bf.set(
(paup_id_node, RDF.type, ns.PXC.PsychAuthorsID)
)
# add the paup id as a literal to the identifier node:
records_bf.add((paup_id_node, RDF.value, Literal(paup_id)))
# add the identifier node to the agent node:
records_bf.add((agent, ns.BF.identifiedBy, paup_id_node))
logging.info("paup_id added to agent: " + paup_id)
def match_orcids_to_contribution_nodes(work_uri, record):
# go through all ORCID fields and get the id:
for orcid in record.findall("ORCID"):
# print("orcid: " + orcid.text)
orcid_id = helpers.get_subfield(orcid.text, "u")
orcid_name = helpers.get_mainfield(orcid.text)
# is the orcid well formed?
# clean up the orcid_id by removing spaces that sometimes sneak in when entering them in the database:
if orcid_id is not None and " " in orcid_id:
logging.warning(
"warning: orcid_id contains spaces, cleaning it up: " + orcid_id
)
orcid_id = orcid_id.replace(" ", "")
# by the way, here is a regex pattern for valid orcids:
orcid_pattern = re.compile(
r"^(https?:\/\/(orcid\.)?org\/)?(orcid\.org\/)?(\/)?([0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X])$"
)
if orcid_pattern.match(orcid_id):
# remove the prefixes and slashes from the orcid id:
orcid_id = orcid_pattern.match(orcid_id).group(5)
else:
# warn if it doesn't match the pattern for well-formed orcids:
logging.warning(f"warning: invalid orcid: {orcid_id}")
# get the given and family part of the orcid name:
# make sure we give an error message when we can't split:
try:
orcid_split = orcid_name.split(",")
orcid_familyname = orcid_split[0].strip()
orcid_givenname = orcid_split[1].strip()
orcidname_normalized = normalize_names(orcid_familyname, orcid_givenname)
except:
logging.info(
"couldn't split orcid name into given and family name: "
+ orcid_name
+ " in record "
+ record.find("DFK").text
+ ". Using the full name as a fallback."
)
orcidname_normalized = (
orcid_name # if we can't split, just try the full name
)
# go through all bf:Contribution nodes of this work_uri, and get the given and family names of the agent, if it is a person - and match names to those in the orcid field:
for contribution in records_bf.objects(work_uri, ns.BF.contribution):
# get the agent of the contribution:
agent = records_bf.value(contribution, ns.BF.agent)
# if the agent is a person, get the given and family names:
if records_bf.value(agent, RDF.type) == ns.BF.Person:
# get the given and family names of the agent:
givenname = records_bf.value(agent, ns.SCHEMA.givenName)
familyname = records_bf.value(agent, ns.SCHEMA.familyName)
aupname_normalized = normalize_names(familyname, givenname)
# if the orcidname_normalized matches the agent's name, add the orcid_id as an identifier to the agent:
# check using fuzzywuzzy - use partial_ratio to check if one of the them is a substring of the other:
if fuzz.partial_ratio(aupname_normalized, orcidname_normalized) > 80:
# create a fragment uri node for the identifier:
orcid_id_node = URIRef(str(agent) + "_orcid")
# make it a locid:orcid:
records_bf.set((orcid_id_node, RDF.type, ns.LOCID.orcid))
# add the orcid id as a literal to the identifier node:
records_bf.add((orcid_id_node, RDF.value, Literal(orcid_id)))
# add the identifier node to the agent node:
records_bf.add((agent, ns.BF.identifiedBy, orcid_id_node))
# print("orcid_id added to agent: " + orcid_id)
# and break the loop:
break
# after all loops, print a message if no match was found:
else:
logging.info(
"no match found for orcid_id "
+ orcid_id
+ " ("
+ orcid_name
+ ") in record "
+ record.find("DFK").text
)
def match_CS_COU_affiliations_to_first_contribution(work_uri, record):
# get the content of CS:
try:
affiliation = record.find("CS").text
except:
affiliation = ""
# get the country from COU:
try:
country = record.find("COU").text
except:
country = ""
#
# if there is a CS field, add the affiliation to the first contribution node:
if affiliation is not None and country is not None:
# get the first contribution node:
for contribution in records_bf.objects(work_uri, ns.BF.contribution):
agent_node = records_bf.value(
contribution, ns.BF.agent
) # get the agent of the contribution
# dont get the agent at all, but just the position of the contribution:
position = records_bf.value(contribution, ns.PXP.contributionPosition)
if (
int(position) == 1
and records_bf.value(agent_node, RDF.type) == ns.BF.Person
):
# add the affiliation to the contribution node using the function we already have for it:
records_bf.add(
(
contribution,
ns.MADS.hasAffiliation,
build_affiliation_nodes(agent_node, affiliation, country),
)
)
break
def match_email_to_contribution_nodes(work_uri, record):
# there is only ever one email field in a record, so we can just get it.
# unless there is also a field emid, the email will be added to the first contribution node.
# if there is an emid, the email will be added to the person with a name matching the name in emid.
# fortunately, the name in EMID should always be exactly the same as the one in an AUP field
# (unlike for PAUP and ORCID, :eyeroll:) so matching the names is pretty easy.
# First get the email:
if record.find("EMAIL") is not None:
# cleaning up the horrible mess that star makes of any urls and email
# addresses (it replaces _ with space, but there is no way to
# differentiate between an underscore-based space and a real one...):
email = html.unescape(
mappings.replace_encodings(record.find("EMAIL").text.strip())
)
# replace spaces with _, but only if it doesnt come directly before a dot:
email = re.sub(r"\s(?=[^\.]*\.)", "_", email)
# if a space comes directly before a dot or after a dot, remove it:
email = re.sub(r"\s\.", ".", email)
email = re.sub(r"\.\s", ".", email)
# check if this is a valid email:
email_pattern = re.compile(
r"^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$"
)
# check if email matches the regex in email_pattern:
if email_pattern.match(email):
email = "mailto:" + email
# if there is an emid, the email will be added to the person with a name matching the name in emid.
# get the emid:
try:
emid_name = record.find("EMID").text
except:
emid_name = None
if emid_name is not None:
# go through all bf:Contribution nodes of this work_uri, and get the given and family names of the agent, if it is a person:
for contribution in records_bf.objects(work_uri, ns.BF.contribution):
# get the agent of the contribution:
agent = records_bf.value(contribution, ns.BF.agent)
# if the agent is a person, get the given and family names:
if records_bf.value(agent, RDF.type) == ns.BF.Person:
# get the given and family names of the agent:
name = records_bf.value(agent, RDFS.label)
emid_name = mappings.replace_encodings(emid_name).strip()
# if the emid_name matches the agent's name, add the email as a mads:email to the agent:
if fuzz.partial_ratio(emid_name, name) > 80:
# add to contribution node:
records_bf.add((contribution, ns.MADS.email, URIRef(email)))
# and break the loop, since we only need to add the email to one person:
break
# if after all loops, no match was found for EMID in the AUP-based name,
# add the email to the first contribution node:
else:
# finding the contribution node from those the work_uri has that has pxp:contributionPosition 1:
for contribution in records_bf.objects(work_uri, ns.BF.contribution):
# dont get the agent at all, but just the position of the contribution:
position = records_bf.value(
contribution, ns.PXP.contributionPosition
)
if int(position) == 1:
# add to contribution node:
records_bf.add((contribution, ns.MADS.email, URIRef(email)))
# break after position 1 - since we only need the first contribution node:
break
else:
logging.warning(
f"invalid email found in record {record.find('DFK').text}: {email}, discarding email"
)
def extract_contribution_role(contributiontext):
role = helpers.get_subfield(contributiontext, "f")
if role is not None:
# if we find a role, return it:
return role
else:
# if none is found, add the default role AU:
return "AU"
def generate_bf_contribution_node(work_uri, record, contribution_counter):
# will be called by functions that add AUPs and AUKS
# adds a bf:Contribution node, adds the position from a counter, and returns the node.
contribution_qualifier = None
# make the node and add class:
contribution_node = URIRef(work_uri + "#contribution" + str(contribution_counter))
records_bf.add((contribution_node, RDF.type, ns.BF.Contribution))
# add author positions:
records_bf.add(
(
contribution_node,
ns.PXP.contributionPosition,
Literal(contribution_counter),
)
)
# if we are in the first loop, set contribution's bf:qualifier" to "first":
if contribution_counter == 1:
contribution_qualifier = "first"
records_bf.add((contribution_node, RDF.type, ns.BFLC.PrimaryContribution))
# if we are in the last loop, set "contribution_qualifier" to "last":
elif contribution_counter == len(record.findall("AUP")) + len(
record.findall("AUK")
):
contribution_qualifier = "last"
# if we are in any other loop but the first or last, set "contribution_qualifier" to "middle":
else:
contribution_qualifier = "middle"
# add the contribution qualifier to the contribution node:
records_bf.add(
(contribution_node, ns.BF.qualifier, Literal(contribution_qualifier))
)
# finally, return the finished contribution node so we can add our agent and affiliation data to it in their own functions:
return contribution_node
def add_bf_contributor_corporate_body(work_uri, record):
# adds all corporate body contributors from any of the record's AUK fields as contributions.
contribution_counter = len(record.findall("AUP"))
for org in record.findall("AUK"):
# count up the contribution_counter:
contribution_counter += 1
# generate a contribution node, including positions, and return it:
contribution_node = generate_bf_contribution_node(
work_uri, record, contribution_counter
)
# do something:
# read the text in AUK and add it as a label:
# create a fragment uri node for the agent:
org_node = URIRef(str(contribution_node) + "_orgagent")
records_bf.add((org_node, RDF.type, ns.BF.Organization))
## extracting the role:
role = extract_contribution_role(org.text)
# check if there is a role in |f subfield and add as a role, otherwise set role to AU
records_bf.set((contribution_node, ns.BF.role, add_bf_contribution_role(role)))
try:
# get the name (but exclude any subfields - like role |f, affiliation |i and country |c )
org_name = mappings.replace_encodings(helpers.get_mainfield(org.text))
# org_name = mappings.replace_encodings(org.text).strip()
except:
logging.warning(
f"{record.find('DFK').text}: skipping malformed AUK: {org.text}"
)
continue
# get ror id of org from api:
org_ror_id = get_ror_id_from_api(org_name)
# if there is a ror id, add the ror id as an identifier:
if org_ror_id is not None and org_ror_id != "null":
# create a fragment uri node fore the identifier:
org_ror_id_node = URIRef(str(org_node) + "_rorid")
# make it a locid:ror:
records_bf.set((org_ror_id_node, RDF.type, ns.LOCID.ror))
# add the ror id as a literal to the identifier node:
records_bf.add((org_ror_id_node, RDF.value, Literal(org_ror_id)))
records_bf.add((org_node, ns.BF.identifiedBy, org_ror_id_node))
# else:
# print("ror-api: no ror id found for " + org_name)
# get any affiliation in |i and add it to the name:
try:
org_affiliation_name = helpers.get_subfield(org.text, "i")
# print("org affiliation:" + org_affiliation_name)
except:
org_affiliation_name = None
# print("AUK subfield i: no affiliation for org " + org_name)
if org_affiliation_name is not None:
org_name = org_name + "; " + org_affiliation_name
# # get country name in |c, if it exists:
try:
org_country = helpers.get_subfield(org.text, "c")
# print("AUK subfield c: org country:" + org_country)
except:
org_country = None
# print("AUK subfield c: no country for org " + org_name)
if org_country is not None:
# generate a node for the country, clean up the label, look up the geonames id and then add both label and geonamesid node to the org node!
affiliation_node = build_affiliation_nodes(org_node, "", org_country)
# add the affiliation node to the contribution node:
records_bf.add(
(contribution_node, ns.MADS.hasAffiliation, affiliation_node)
)
# TODO: we should probably check for affiliations and countries in fields CS and COU for records that have only AUKS or AUK as first contribution? we already did the same for persons.
# add the name as the org node label:
records_bf.add((org_node, RDFS.label, Literal(org_name)))
## --- Add the contribution node to the work node:
records_bf.add((work_uri, ns.BF.contribution, contribution_node))
# add the org node to the contribution node as a contributor:
records_bf.add((contribution_node, ns.BF.agent, org_node))
# %% [markdown]
# ## Function: Create Person Contribution nodes from Fields AUP, EMID, EMAIL, AUK, PAUP, CS and COU
#
# Use this scheme:
#
# ```turtle
# works:0123456_work a bf:Work;
# bf:contribution works:0123456_work#contribution1
# .
# works:0123456_work#contribution1 a bf:Contribution, bflc:PrimaryContribution;
# # the Bibframe Contribution includes, as usual, an agent and their role,
# # but is supplemented with an Affiliation (in the context of that work/while it was written),
# # and a position in the author sequence.
# bf:agent
# [
# a bf:Person, schema:Person;
# rdfs:label "Trillitzsch, Tina"; # name when creating work
# schema:givenName "Tina"; schema:familyName "Trillitzsch";
# # owl:sameAs <https://w3id.org/zpid/person/tt_0000001>, <https://orcid.org/0000-0001-7239-4844>; # authority uris of person (local, orcid)
# bf:identifiedBy [a pxc:PsychAuthorsID; rdf:value "p01979TTR"; #legacy authority ID
# ];
# bf:identifiedBy [a locid:orcid; rdf:value "0000-0001-7239-4844"; # ORCID
# ];
# ]
# # we use a model inspired by Option C in Osma Suominen'a suggestion for https://github.com/dcmi/dc-srap/issues/3
# # adding the Affiliation into the Contribution, separate from the agent itself, since the affiliation
# # is described in the context of this work, not not as a statement about the person's
# # current affiliation:
# mads:hasAffiliation [
# a mads:Affiliation;
# # Affiliation blank node has info about the affiliation org (including persistent identifiers),
# # the address (country with geonames identifier),
# # and the person's email while affiliated there.
# mads:organization [
# a bf:Organization;
# rdfs:label "Leibniz Institute of Psychology (ZPID); Digital Research Development Services"; # org name when work was created
# # owl:sameAs <https://w3id.org/zpid/org/zpid_0000001>, <https://ror.org/0165gz615>; # authority uris of org (local, ror)
# # internal id and ror id as literal identifiers:
# bf:identifiedBy [a pxc:ZpidCorporateBodyId; rdf:value "0000001"; ];
# bf:identifiedBy [a locid:ror; rdf:value "0165gz615"; ];
# ];
# mads:hasAffiliationAddress [a mads:Address;
# mads:country [
# a mads:Country;
# rdfs:label "Germany";
# bf:identifiedBy [a locid:geonames; rdf:value "2921044"; ];
# # owl:sameAs <https://w3id.org/zpid/place/country/ger>;
# ]
# ];
# mads:email <mailto:ttr@leibniz-psychology.org>; # correspondence author email
# ];
# bf:role <http://id.loc.gov/vocabulary/relators/aut>;
# pxp:contributionPosition 1; bf:qualifier "first"; # first author in sequence: our own subproperty of bf:qualifier & schema:position (also: middle, last)
# ].
# ```
#
# Todos:
# - [x] create blank node for contribution and add agent of type bf:Person
# - [x] add author position (first, middle, last plus order number) to the contribution
# - [x] make first author a bflc:PrimaryContribution
# - [x] match AUP with PAUP to get person names and ids (normalize first)
# - [x] extend AUP-PAUP match with lookup in kerndaten table/ttl to compare schema:alternatename of person with name in AUP (but first before normalization)
# - [x] add ORCID to the person's blank node (doesn't add 4 ORCIDs for unknown reason - maybe duplicates?)
# - [x] add EMAIL to person's blank node (either to person in EMID or to first author)
# - [x] add affiliation from CS field and COU field to first author
# - [x] add Affiliation blank node with org name, country to each author that has these subfields in their AUP (|i and |c)
# - [x] add role from AUP subfield |f
# - [x] add country geonames id using lookup table
# - [ ] move mads:email Literal from bf:Contribution to mads:Affiliation
# - [x] later: reconcile affiliations to add org id, org ror id (once we actually have institution authority files)
#
# %%
from modules.mappings import geonames_countries
def country_geonames_lookup(country):
for case in geonames_countries:
if case[0].casefold() == str(country).casefold():
return case[0], case[1]
return None
# %%
def sanitize_country_names(country_name):
if country_name == "COSTA":
country_name = "Costa Rica"
elif country_name == "CZECH":
country_name = "Czech Republic"
elif country_name == "NEW":
country_name = "New Zealand"
elif country_name == "SAUDI":
country_name = "Saudi Arabia"
elif country_name == "PEOPLES":
country_name = "People's Republic of China"
return country_name
# %%
def add_bf_contribution_role(role):
# # return role_uri,
# # generate a node of type bf:Role:
# records_bf.add((role, RDF.type, ns.BF.Role))
# # construct the uri for the bf:Role object:
# role_uri = URIRef(ROLES + role)
# # add the uri to the role node:
# records_bf.add((role, RDF.value, role_uri))
# # return the new node:
# return role
return URIRef(ns.ROLES + role)
def normalize_names(familyname, givenname):
# given a string such as "Forkmann, Thomas"
# return a normalized version of the name by
# replacing umlauts and ß with their ascii equivalents and making all given names abbreviated:
familyname_normalized = (
familyname.replace("ä", "ae")
.replace("ö", "oe")
.replace("ü", "ue")
.replace("Ä", "Ae")
.replace("Ö", "Oe")
.replace("Ü", "Ue")
.replace("ß", "ss")
)
# generate an abbreviated version of givenname (only the first letter),
# (drop any middle names or initials, but keep the first name):
fullname_normalized = familyname_normalized
if givenname:
givenname_abbreviated = givenname[0] + "."
# generate a normalized version of the name by concatenating the two with a comma as the separator: