forked from OpenAPC/openapc-de
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openapc_toolkit.py
1881 lines (1737 loc) · 80.6 KB
/
openapc_toolkit.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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import csv
from collections import OrderedDict
from html import unescape
from http.client import RemoteDisconnected
import json
import locale
import logging
from logging.handlers import MemoryHandler
import os
import re
from shutil import copyfileobj
import sys
from urllib.parse import quote_plus, urlencode
from urllib.request import build_opener, urlopen, urlretrieve, HTTPErrorProcessor, Request
from urllib.error import HTTPError, URLError
import requests
import xml.etree.ElementTree as ET
import mappings
try:
import chardet
except ImportError:
chardet = None
print("WARNING: 3rd party module 'chardet' not found - character " +
"encoding guessing will not work")
try:
import Levenshtein
except ImportError:
chardet = None
print("WARNING: 3rd party module 'Levenshtein' not found - title " +
"search in Crossref will not work")
# Identifying User Agent header for metadata API requests
USER_AGENT = ("OpenAPC Toolkit (https://github.com/OpenAPC/openapc-de/blob/master/python/openapc_toolkit.py;"+
" mailto:openapc@uni-bielefeld.de)")
# regex for detecing DOIs
DOI_RE = re.compile(r"^(((https?://)?(dx.)?doi.org/)|(doi:))?(?P<doi>10\.[0-9]+(\.[0-9]+)*\/\S+)", re.IGNORECASE)
# regex for detecting shortDOIs
SHORTDOI_RE = re.compile(r"^(https?://)?(dx.)?doi.org/(?P<shortdoi>[a-z0-9]+)$", re.IGNORECASE)
ISSN_RE = re.compile(r"^(?P<first_part>\d{4})\-(?P<second_part>\d{3})(?P<check_digit>[\dxX])$")
OAI_COLLECTION_CONTENT = OrderedDict([
("institution", "intact:institution"),
("period", "intact:period"),
("euro", "intact:euro"),
("doi", "intact:id_number[@type='doi']"),
("is_hybrid", "intact:is_hybrid"),
("publisher", "intact:publisher"),
("journal_full_title", "intact:journal_full_title"),
("issn", "intact:issn"),
("license_ref", "intact:licence"),
("pmid", "intact:id_number[@type='pubmed']"),
("url", None),
("local_id", "intact:id_number[@type='local']")
])
MESSAGES = {
"num_columns": "Syntax: The number of values in this row (%s) " +
"differs from the number of columns (%s). Line left " +
"unchanged, the resulting CSV file will not be valid.",
"locale": "Error: Could not process the monetary value '%s' in " +
"column %s. Usually this happens due to one of two reasons:\n1) " +
"The value does not represent a number.\n2) The value " +
"represents a number, but its format differs from your " +
"current system locale - the most common source of error " +
"is the decimal mark (1234.56 vs 1234,56). Try using " +
"another locale with the -l option.",
"unify": "Normalisation: Crossref-based {} changed from '{}' to '{}' " +
"to maintain consistency.",
"digits_error": "Monetary value %s has more than 2 digits after " +
"the decimal point. If this is just a formatting issue (from automated " +
"conversion for example) you may call the enrichment script with the -r " +
"option to round such values to 2 digits automatically.",
"digits_norm": "Normalisation: Monetary value %s rounded to 2 digits after " +
"decimal mark (%s -> %s)",
"doi_norm": "Normalisation: DOI '{}' normalised to pure form ({}).",
"springer_distinction": "publisher 'Springer Nature' found " +
"for a pre-2015 article - publisher " +
"changed to '%s' based on prefix " +
"discrimination ('%s')",
"unknown_prefix": "publisher 'Springer Nature' found for a " +
"pre-2015 article, but discrimination was " +
"not possible - unknown prefix ('%s')",
"issn_hyphen_fix": "Normalisation: Added hyphen to %s value (%s -> %s)",
"period_format": "Normalisation: Date format in period column changed to year only (%s -> %s)",
"unknown_hybrid_identifier": "Unknown identifier in 'is_hybrid' column ('%s').",
"hybrid_normalisation": "Normalisation: is_hybrid status changed from '%s' to '%s'.",
"no_hybrid_identifier": "Empty value in 'is_hybrid' column.",
"empty_row": "Row is empty."
}
# Do not quote the values in the 'period' and 'euro' columns
OPENAPC_STANDARD_QUOTEMASK = [
True,
False,
False,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True
]
COLUMN_SCHEMAS = {
"journal_article": [
"institution",
"period",
"euro",
"doi",
"is_hybrid",
"publisher",
"journal_full_title",
"issn",
"issn_print",
"issn_electronic",
"issn_l",
"license_ref",
"indexed_in_crossref",
"pmid",
"pmcid",
"ut",
"url",
"doaj"
],
"journal_article_transagree": [
"institution",
"period",
"euro",
"doi",
"is_hybrid",
"publisher",
"journal_full_title",
"issn",
"issn_print",
"issn_electronic",
"issn_l",
"license_ref",
"indexed_in_crossref",
"pmid",
"pmcid",
"ut",
"url",
"doaj",
"agreement"
],
"book_title": [
"institution",
"period",
"euro",
"doi",
"backlist_oa",
"publisher",
"book_title",
"isbn",
"isbn_print",
"isbn_electronic",
"license_ref",
"indexed_in_crossref",
"doab"
]
}
INSTITUTIONS_FILE = "../data/institutions.csv"
INSTITUTIONS_MAP = None
class OpenAPCUnicodeWriter(object):
"""
A customized CSV Writer.
A custom CSV writer. Encodes output in Unicode and can be configured to
follow the open APC CSV quotation standards. A quote mask can also be
provided to enable or disable value quotation in distinct CSV columns.
Attributes:
quotemask: A quotemask is a list of boolean values which should have
the same length as the number of columns in the csv file.
On writing, the truth values in the codemask will determine
if the values in the according column will be quoted. If no
quotemask is provided, every field will be quoted.
openapc_quote_rules: Determines if the special openapc quote rules
should be applied, meaning that the keywords
NA, TRUE and FALSE will never be quoted. This
always takes precedence over a quotemask.
has_header: Determines if the csv file has a header. If that's the case,
The values in the first row will all be quoted regardless
of any quotemask.
minimal_quotes: Quote values containing a comma even if a quotemask
is False for that column (Might produce a malformed
csv file otherwise).
"""
def __init__(self, f, quotemask=None, openapc_quote_rules=True,
has_header=True, minimal_quotes=True):
self.outfile = f
self.quotemask = quotemask
self.openapc_quote_rules = openapc_quote_rules
self.has_header = has_header
self.minimal_quotes = minimal_quotes
def _prepare_row(self, row, use_quotemask):
for index in range(len(row)):
if self.openapc_quote_rules and row[index] in ["TRUE", "FALSE", "NA"]:
# Never quote these keywords
continue
if not use_quotemask or not self.quotemask:
# Always quote without a quotemask
row[index] = row[index].replace('"', '""')
row[index] = '"' + row[index] + '"'
continue
if index < len(self.quotemask):
if self.quotemask[index] or "," in row[index] and self.minimal_quotes:
row[index] = row[index].replace('"', '""')
row[index] = '"' + row[index] + '"'
return row
def _write_row(self, row):
line = ",".join(row) + "\n"
self.outfile.write(line)
def write_rows(self, rows):
if self.has_header:
self._write_row(self._prepare_row(rows.pop(0), False))
for row in rows:
self._write_row(self._prepare_row(row, True))
class DOAJAnalysis(object):
def __init__(self, doaj_csv_file, update=False):
self.doaj_issn_map = {}
self.doaj_eissn_map = {}
if not os.path.isfile(doaj_csv_file) or update :
doaj_csv_file = self.download_doaj_csv(doaj_csv_file)
handle = open(doaj_csv_file, "r")
reader = csv.DictReader(handle)
for line in reader:
journal_title = line["Journal title"]
issn = line["Journal ISSN (print version)"]
eissn = line["Journal EISSN (online version)"]
if issn:
self.doaj_issn_map[issn] = journal_title
if eissn:
self.doaj_eissn_map[eissn] = journal_title
def lookup(self, any_issn):
if any_issn in self.doaj_issn_map:
return self.doaj_issn_map[any_issn]
elif any_issn in self.doaj_eissn_map:
return self.doaj_eissn_map[any_issn]
return None
def download_doaj_csv(self, filename):
request = Request("https://doaj.org/csv")
request.add_header("User-Agent", USER_AGENT)
with urlopen(request) as source:
with open(filename, "wb") as dest:
copyfileobj(source, dest)
return filename
class EZBSrcaping(object):
"""
Contains methods to scrap journal information from the Regensburg
Electronic Journals Library ("Elektronische Zeitschriftenbibliothek")
(https://ezb.uni-regensburg.de/)
"""
EZB_SEARCH_URL = ("https://ezb.uni-regensburg.de/searchres.phtml?" +
"bibid=AAAAA&colors=7&lang=de&jq_type1=QS&jq_term1=")
EZB_ID_URL = ('https://ezb.uni-regensburg.de/detail.phtml?')
JOURNAL_PAGE_INDICATOR = re.compile(r'<h1\s+class="detail_heading"\s*>')
JOURNAL_ACCESS = re.compile(r'<h1\s+class="detail_heading"\s*>\s*<div\s+class="filter-container-mid"\s+title="(?P<access_msg>.*?)">\s*<span\s+class="filter-light\s+(?P<green>.*?)"\s*>\s*</span>\s*<span\s+class="filter-light\s+(?P<yellow>.*?)"\s*>\s*</span>\s*<span\s+class="filter-light\s+(?P<red>.*?)"\s*>')
JOURNAL_TITLE = re.compile(r'<dd\s+id="title"\s+class="defListContentDefinition"\s*>\s*(?P<title>.*?)\s*</dd\s*>')
JOURNAL_REMARKS = re.compile(r'<dt\s+class="defListContentTitle"\s*>\s*Bemerkung:\s*</dt\s*>\s*<dd\s+class="defListContentDefinition"\s*>\s*(?P<remarks>.*?)\s*</dd\s*>')
RESULT_LINKS = re.compile(r'<a\s+href="warpto.phtml\?(?P<url_params>.*?)"\s+title="Direktlink zur Zeitschrift"\s*>')
def _get_journal_details(self, content):
res = {
"errors": [],
"access_msg" : None,
"access_color": None,
"title": None,
"remarks": None
}
access_mo = re.search(self.JOURNAL_ACCESS, content)
if access_mo:
access_dict = access_mo.groupdict()
res["access_msg"] = access_dict["access_msg"]
if access_dict["green"] == "green":
res["access_color"] = "green"
elif access_dict["yellow"] == "yellow":
res["access_color"] = "yellow"
elif access_dict["red"] == "red":
res["access_color"] = "red"
else:
res["errors"].append("Could not scrap journal access information (RE 'JOURNAL_ACCESS' did not find anything)")
title_mo = re.search(self.JOURNAL_TITLE, content)
if title_mo:
title_dict = title_mo.groupdict()
res["title"] = title_dict["title"]
else:
res["errors"].append("Could not scrap journal title information (RE 'JOURNAL_TITLE' did not find anything)")
remarks_mo = re.search(self.JOURNAL_REMARKS, content)
if remarks_mo:
remarks_dict = remarks_mo.groupdict()
res["remarks"] = remarks_dict["remarks"]
else:
res["errors"].append("Could not scrap journal remarks information (RE 'JOURNAL_REMARKS' did not find anything)")
return res
def _request_ezb_page(self, url):
request = Request(url)
request.add_header("User-Agent", USER_AGENT)
ret_value = {'success': True}
try:
ret = urlopen(request)
content_bytes = ret.read()
content = content_bytes.decode("latin-1")
ret_value["content"] = content
except HTTPError as httpe:
ret_value['success'] = False
ret_value['error_msg'] = "HTTPError: {} - {}".format(httpe.code, httpe.reason)
except URLError as urle:
ret_value['success'] = False
ret_value['error_msg'] = "URLError: {}".format(urle.reason)
return ret_value
def get_ezb_info(self, issn):
ret_value = {"success": True, "data": []}
url = self.EZB_SEARCH_URL + issn
answer = self._request_ezb_page(url)
if not answer['success']:
return answer
# When querying the EZB, it may either lead us directly to a journal detail
# page or to a results page if there's more than one search result
content = answer["content"]
if re.search(self.JOURNAL_PAGE_INDICATOR, content):
ret_value["data"].append(self._get_journal_details(content))
else:
link_params = re.findall(self.RESULT_LINKS, content)
for params in link_params:
url = self.EZB_ID_URL + unescape(params)
answer = self._request_ezb_page(url)
if answer['success']:
ret_value["data"].append(self._get_journal_details(answer["content"]))
if not ret_value["data"]:
ret_value["success"] = False
return ret_value
class DOABAnalysis(object):
# Priority mappings from DOAB fields to OpenAPC values. Unfortuately, the current DOAB CSV file is a real mess...
MAPPINGS = {
"book_title": ["dc.title", "dc.subject.other"],
"publisher": ["oapen.relation.isPublishedBy_publisher.name", "oapen.relation.isPublishedBy", "oapen.relation.isPartOfBook_dc.title", "oapen.imprint"],
"license_ref": ["BITSTREAM License"]
}
ISBN_FIELDS = ["oapen.relation.isPublishedBy_publisher.name",
"oapen.relation.isPublisherOf",
"oapen.relation.isbn"]
DOAB_ISBN_RE = re.compile(r"97[89]\d{10}")
def __init__(self, isbn_handling, doab_csv_file, update=False, verbose=False):
self.isbn_map = {}
self.isbn_handling = isbn_handling
if not os.path.isfile(doab_csv_file) or update:
self.download_doab_csv(doab_csv_file)
lines = []
# The file might contain NUL bytes, we need to get rid of them before
# handing the lines to a DictReader
with open(doab_csv_file, "r") as handle:
for line in handle:
if "\x00" in line:
continue
lines.append(line)
duplicate_isbns = []
reader = csv.DictReader(lines)
for line in reader:
# ATM we focus on books only
if line["dc.type"] != "book" and line["dc.title.alternative"] != "book":
continue
isbn_string = " ".join([line[field] for field in self.ISBN_FIELDS])
# may contain multi-values split by a whitespace, semicolon or double vbar...
isbn_string = isbn_string.replace(";", " ")
isbn_string = isbn_string.replace("||", " ")
isbn_string = isbn_string.strip()
if len(isbn_string) == 0:
continue
while " " in isbn_string:
isbn_string = isbn_string.replace(" ", " ")
isbns = isbn_string.split(" ")
# ...which may also contain duplicates
for isbn in list(set(isbns)):
result = self.isbn_handling.test_and_normalize_isbn(isbn)
if not result["valid"]:
if verbose:
msg = "Line {}: ISBN normalization failure ({}): {}"
msg = msg.format(reader.line_num, result["input_value"],
ISBNHandling.ISBN_ERRORS[result["error_type"]])
print_r(msg)
continue
else:
isbn = result["normalised"]
if isbn not in self.isbn_map:
new_line = self._extract_line_data(line)
if verbose:
for field in ["publisher", "book_title"]:
if not has_value(new_line[field]):
msg = "Line {}: No '{}' value found for ISBN {}"
print_r(msg.format(reader.line_num, field, isbn))
self.isbn_map[isbn] = new_line
else:
if isbn not in duplicate_isbns:
duplicate_isbns.append(isbn)
if verbose:
print_y("ISBN duplicate found in DOAB: " + isbn)
for duplicate in duplicate_isbns:
# drop duplicates alltogether
del(self.isbn_map[duplicate])
if verbose:
print_b("ISBN map created, contains " + str(len(self.isbn_map)) + " entries")
def _extract_line_data(self, line):
new_line = {key: "" for key in self.MAPPINGS.keys()}
for key, prio_list in self.MAPPINGS.items():
for field in prio_list:
if has_value(line[field]) and not self.DOAB_ISBN_RE.search(line[field]):
new_line[key] = line[field]
break
return new_line
def lookup(self, isbn):
result = self.isbn_handling.test_and_normalize_isbn(isbn)
if result["valid"]:
norm_isbn = result["normalised"]
return self.isbn_map.get(norm_isbn)
return None
def download_doab_csv(self, target):
urlretrieve("https://directory.doabooks.org/download-export?format=csv", target)
class ISBNHandling(object):
# regex for 13-digit, unsplit ISBNs
ISBN_RE = re.compile(r"^97[89]\d{10}$")
# regex for 13-digit ISBNs split with hyphens
ISBN_SPLIT_RE = re.compile(r"^97[89]\-\d{1,5}\-\d{1,7}\-\d{1,6}\-\d{1}$")
ISBN_ERRORS = {
0: "Input is neither a valid split nor a valid unsplit 13-digit ISBN",
1: "Too short (Must be 17 chars long including hyphens)",
2: "Too long (Must be 17 chars long including hyphens)",
3: "Input ISBN was split, but the segmentation is invalid"
}
def __init__(self, range_file_path, range_file_update=False):
if not os.path.isfile(range_file_path) or range_file_update:
self.download_range_file(range_file_path)
with open(range_file_path, "r") as range_file:
range_file_content = range_file.read()
range_file_root = ET.fromstring(range_file_content)
self.ean_elements = range_file_root.findall("./EAN.UCCPrefixes/EAN.UCC")
self.registration_groups = range_file_root.findall("./RegistrationGroups/Group")
def download_range_file(self, target):
urlretrieve("http://www.isbn-international.org/export_rangemessage.xml", target)
def test_and_normalize_isbn(self, isbn):
"""
Take a string input and try to normalize it to a 13-digit, split ISBN.
This method takes a string which is meant to represent a split or unsplit 13-digit ISBN. It
applies a range of tests to verify its validity and then returns a normalized, split variant.
The following tests will be applied:
- Syntax (Regex)
- Re-split and segmentation comparison (if input was split already)
Args:
isbn: A string potentially representing a 13-digit ISBN (split or unsplit).
Returns:
A dict with 3 keys:
'valid': A boolean indicating if the input passed all tests.
'input_value': The original input value
'normalised': The normalised, split result. Will be present if 'valid' is True.
'error_type': An int indicating why a test failed. Will be present if 'valid'
is False. Corresponds to a key in the ISBN_ERRORS dict.
"""
ret = {"valid": False, "input_value": str(isbn)}
stripped_isbn = isbn.strip()
unsplit_isbn = stripped_isbn.replace("-", "")
split_on_input = False
if self.ISBN_SPLIT_RE.match(stripped_isbn):
if len(stripped_isbn) < 17:
ret["error_type"] = 1
return ret
elif len(stripped_isbn) > 17:
ret["error_type"] = 2
return ret
else:
split_on_input = True
if self.ISBN_RE.match(unsplit_isbn):
split_isbn = self.split_isbn(unsplit_isbn)["value"]
if split_on_input and split_isbn != stripped_isbn:
ret["error_type"] = 3
return ret
ret["normalised"] = split_isbn
ret["valid"] = True
return ret
ret["error_type"] = 0
return ret
def isbn_has_valid_check_digit(self, isbn):
"""
Take a string representing a 13-digit ISBN (without hyphens) and test if its check digit is
correct.
"""
if not self.ISBN_RE.match(isbn):
raise ValueError(str(isbn) + " is no valid 13-digit ISBN!")
checksum = 0
for index, digit in enumerate(isbn):
if index % 2 == 0:
checksum += int(digit)
else:
checksum += 3 * int(digit)
return checksum % 10 == 0
def _get_range_length_from_rules(self, isbn_fragment, rules_element):
value = int(isbn_fragment[:7])
range_re = re.compile(r"(?P<min>\d{7})-(?P<max>\d{7})")
for rule in rules_element.findall("Rule"):
range_text = rule.find("Range").text
range_match = range_re.match(range_text)
if int(range_match["min"]) <= value <= int(range_match["max"]):
length = rule.find("Length").text
return int(length)
# Shouldn't happen as the range file is meant to be comprehensive. Undefined ranges are marked
# with a length of 0 instead.
msg = ('Could not find a length definition for fragment "' + isbn_fragment + '" in the ISBN ' +
'range file.')
raise ValueError(msg)
def split_isbn(self, isbn):
"""
Take an unsplit, 13-digit ISBN and insert hyphens to correctly separate its parts.
This method takes a 13-digit ISBN and returns a hyphenated variant (Example: 9782753518278 ->
978-2-7535-1827-8). Since the segments of an ISBN may vary in length (except for the EAN prefix
and the check digit), the official "RangeMessage" XML file provided by the ISBN organization is
needed for reference.
Args:
isbn: A string representing a 13-digit ISBN.
Returns:
A dict with two keys: 'success' and 'result'. If the process was successful, 'success'
will be True and 'result' will contain the hyphenated result string. Otherwise, 'success'
will be False and 'result' will contain an error message stating the reason.
"""
ret_value = {
'success': False,
'value': None
}
split_isbn = ""
remaining_isbn = isbn
if not self.ISBN_RE.match(isbn):
ret_value['value'] = '"' + str(isbn) + '" is no valid 13-digit ISBN!'
return ret_value
for ean in self.ean_elements:
prefix = ean.find("Prefix").text
if remaining_isbn.startswith(prefix):
split_isbn += prefix
remaining_isbn = remaining_isbn[len(prefix):]
rules = ean.find("Rules")
length = self._get_range_length_from_rules(remaining_isbn, rules)
if length == 0:
msg = ('Invalid ISBN: Remaining fragment "{}" for EAN prefix "{}" is inside a ' +
'range which is not marked for use yet')
ret_value['value'] = msg.format(remaining_isbn, prefix)
return ret_value
group = remaining_isbn[:length]
split_isbn += "-" + group
remaining_isbn = remaining_isbn[length:]
break
else:
msg = 'ISBN "{}" does not seem to have a valid prefix.'
ret_value['value'] = msg.format(isbn)
return ret_value
for group in self.registration_groups:
prefix = group.find("Prefix").text
if split_isbn == prefix:
rules = group.find("Rules")
length = self._get_range_length_from_rules(remaining_isbn, rules)
if length == 0:
msg = ('Invalid ISBN: Remaining fragment "{}" for registration group "{}" is ' +
'inside a range which is not marked for use yet')
ret_value['value'] = msg.format(remaining_isbn, split_isbn)
return ret_value
registrant = remaining_isbn[:length]
split_isbn += "-" + registrant
remaining_isbn = remaining_isbn[length:]
check_digit = remaining_isbn[-1:]
publication_number = remaining_isbn[:-1]
split_isbn += "-" + publication_number + "-" + check_digit
ret_value['success'] = True
ret_value['value'] = split_isbn
return ret_value
else:
msg = 'ISBN "{}" does not seem to have a valid registration group element.'
ret_value['value'] = msg.format(isbn)
return ret_value
class CSVAnalysisResult(object):
def __init__(self, blanks, dialect, has_header, enc, enc_conf):
self.blanks = blanks
self.dialect = dialect
self.has_header = has_header
self.enc = enc
self.enc_conf = enc_conf
def __str__(self):
ret = "*****CSV file analysis*****\n"
if self.dialect is not None:
quote_consts = ["QUOTE_ALL", "QUOTE_MINIMAL", "QUOTE_NONE",
"QUOTE_NONNUMERIC"]
quoting = self.dialect.quoting
for const in quote_consts:
# Seems hacky. Is there a more pythonic way to determine a
# member const by its value?
if hasattr(csv, const) and getattr(csv, const) == self.dialect.quoting:
quoting = const
ret += ("CSV dialect sniffing:\ndelimiter => {dlm}\ndoublequote " +
"=> {dbq}\nescapechar => {esc}\nquotechar => {quc}\nquoting " +
"=> {quo}\nskip initial space => {sis}\n\n").format(
dlm=self.dialect.delimiter,
dbq=self.dialect.doublequote,
esc=self.dialect.escapechar,
quc=self.dialect.quotechar,
quo=quoting,
sis=self.dialect.skipinitialspace)
if self.has_header:
ret += "CSV file seems to have a header.\n\n"
else:
ret += "CSV file doesn't seem to have a header.\n\n"
if self.blanks:
ret += "Found " + str(self.blanks) + " empty lines in CSV file.\n\n"
if self.enc:
ret += ("Educated guessing of file character encoding: {} with " +
"a confidence of {}%\n").format(
self.enc,
int(self.enc_conf * 100))
ret += "***************************"
return ret
class ANSIColorFormatter(logging.Formatter):
"""
A simple logging formatter using ANSI codes to colorize messages
"""
def __init__(self):
super().__init__(fmt="%(levelname)s: %(message)s", datefmt=None, style="%")
FORMATS = {
logging.ERROR: "\033[91m%(levelname)s: %(message)s\033[0m",
logging.WARNING: "\033[93m%(levelname)s: %(message)s\033[0m",
logging.INFO: "\033[94m%(levelname)s: %(message)s\033[0m",
"DEFAULT": "%(levelname)s: %(message)s"
}
def format(self, record):
self._style._fmt = self.FORMATS.get(record.levelno, self.FORMATS["DEFAULT"])
return logging.Formatter.format(self, record)
class BufferedErrorHandler(MemoryHandler):
"""
A modified MemoryHandler without automatic flushing.
This handler serves the simple purpose of buffering error and critical
log messages so that they can be shown to the user in collected form when
the enrichment process has finished.
"""
def __init__(self, target):
MemoryHandler.__init__(self, 100000, target=target)
self.setLevel(logging.ERROR)
def shouldFlush(self, record):
return False
class NoRedirection(HTTPErrorProcessor):
"""
A dummy processor to suppress HTTP redirection.
This handler serves the simple purpose of stopping redirection for
easy extraction of shortDOI redirect targets.
"""
def http_response(self, request, response):
return response
https_response = http_response
class UnsupportedDoiTypeError(ValueError):
"""
An exception indicating an unsupported DOI type while looking up Crossref metadata
Its main purpose is to store already obtained Crossref data (type + title)
for later error handling, avoiding double lookups
"""
def __init__(self, doi_type, unsupported_doi_types, crossref_title):
self.doi_type = doi_type
self.crossref_title = crossref_title
msg = ('Unsupported DOI type "{}" (OpenAPC only supports the following types: {})')
msg = msg.format(doi_type, ", ".join(unsupported_doi_types))
super().__init__(msg)
def get_normalised_DOI(doi_string):
doi_string = doi_string.strip()
doi_match = DOI_RE.match(doi_string)
if doi_match:
doi = doi_match.groupdict()["doi"]
return doi.lower()
shortdoi_match = SHORTDOI_RE.match(doi_string)
if shortdoi_match:
# Extract redirect URL to obtain original DOI
shortdoi = shortdoi_match.groupdict()["shortdoi"]
url = "https://doi.org/" + shortdoi
opener = build_opener(NoRedirection)
try:
res = opener.open(url)
if res.code == 301:
doi_match = DOI_RE.match(res.headers["Location"])
if doi_match:
doi = doi_match.groupdict()["doi"]
return doi.lower()
return None
except (HTTPError, URLError):
return None
return None
def is_wellformed_ISSN(issn_string):
issn_match = ISSN_RE.match(issn_string)
if issn_match is not None:
return True
return False
def is_valid_ISSN(issn_string):
issn_match = ISSN_RE.match(issn_string)
match_dict = issn_match.groupdict()
check_digit = match_dict["check_digit"]
if check_digit in ["X", "x"]:
check_digit = 10
else:
check_digit = int(check_digit)
digits = match_dict["first_part"] + match_dict["second_part"]
factor = 8
total = 0
for digit in digits:
total += int(digit) * factor
factor -= 1
mod = total % 11
if mod == 0 and check_digit == 0:
return True
else:
if 11 - mod == check_digit:
return True
return False
def analyze_csv_file(file_path, test_lines=1000, enc=None):
try:
csv_file = open(file_path, "rb")
except IOError as ioe:
error_msg = "Error: could not open file '{}': {}".format(file_path,
ioe.strerror)
return {"success": False, "error_msg": error_msg}
guessed_enc = None
guessed_enc_confidence = None
blanks = 0
if chardet:
byte_content = b"" # in python3 chardet operates on bytes
lines_processed = 0
for line in csv_file:
if line.strip(): # omit blank lines
lines_processed += 1
if lines_processed <= test_lines:
byte_content += line
else:
blanks += 1
chardet_result = chardet.detect(byte_content)
guessed_enc = chardet_result["encoding"]
guessed_enc_confidence = chardet_result["confidence"]
csv_file.close()
if enc is not None:
used_encoding = enc
elif guessed_enc is not None:
used_encoding = guessed_enc
else:
used_encoding = locale.getpreferredencoding()
text_content = ""
with open(file_path, "r", encoding=used_encoding) as csv_file:
try:
lines_processed = 0
for line in csv_file:
if line.strip(): # omit blank lines
lines_processed += 1
text_content += line
if lines_processed > test_lines:
break
except UnicodeError as ue:
error = ('A UnicodeError occured while trying to read the csv ' +
'file ("{}") - it seems the encoding we used ({}) is ' +
'not correct.')
error_msg = error.format(str(ue), used_encoding)
return {"success": False, "error_msg": error_msg}
sniffer = csv.Sniffer()
try:
dialect = sniffer.sniff(text_content)
has_header = sniffer.has_header(text_content)
except csv.Error as csve:
error_msg = ("Error: An error occured while analyzing the file: '" +
str(csve) + "'. Maybe it is no valid CSV file?")
return {"success": False, "error_msg": error_msg}
result = CSVAnalysisResult(blanks, dialect, has_header, guessed_enc, guessed_enc_confidence)
return {"success": True, "data": result}
def get_csv_file_content(file_name, enc=None, force_header=False, print_results=True):
result = analyze_csv_file(file_name, enc=enc)
if result["success"]:
csv_analysis = result["data"]
if print_results:
print(csv_analysis)
else:
raise IOError(result["error_msg"])
if enc is None:
enc = csv_analysis.enc
if enc is None:
raise IOError("No encoding given for CSV file and automated detection failed.")
dialect = csv_analysis.dialect
csv_file = open(file_name, "r", encoding=enc)
content = []
reader = csv.reader(csv_file, dialect=dialect)
header = []
if csv_analysis.has_header or force_header:
header.append(next(reader))
for row in reader:
content.append(row)
csv_file.close()
return (header, content)
def has_value(field):
return len(field) > 0 and field != "NA"
def oai_harvest(basic_url, metadata_prefix=None, oai_set=None, processing=None, out_file_suffix=None):
"""
Harvest OpenAPC records via OAI-PMH
"""
collection_xpath = ".//oai_2_0:metadata//intact:collection"
record_xpath = ".//oai_2_0:record"
identifier_xpath = ".//oai_2_0:header//oai_2_0:identifier"
token_xpath = ".//oai_2_0:resumptionToken"
processing_regex = re.compile(r"'(?P<target>\w*?)':'(?P<generator>.*?)'")
variable_regex = re.compile(r"%(\w*?)%")
#institution_xpath =
namespaces = {
"oai_2_0": "http://www.openarchives.org/OAI/2.0/",
"intact": "http://intact-project.org"
}
url = basic_url + "?verb=ListRecords"
if metadata_prefix:
url += "&metadataPrefix=" + metadata_prefix
if oai_set:
url += "&set=" + oai_set
if processing:
match = processing_regex.match(processing)
if match:
groupdict = match.groupdict()
target = groupdict["target"]
generator = groupdict["generator"]
variables = variable_regex.search(generator).groups()
else:
print_r("Error: Unable to parse processing instruction!")
processing = None
print_b("Harvesting from " + url)
articles = []
file_output = ""
while url is not None:
try:
request = Request(url)
url = None
response = urlopen(request)
content_string = response.read()
if out_file_suffix:
file_output += content_string.decode()
root = ET.fromstring(content_string)
records = root.findall(record_xpath, namespaces)
counter = 0
for record in records:
article = {}
identifier = record.find(identifier_xpath, namespaces)
article["identifier"] = identifier.text
collection = record.find(collection_xpath, namespaces)
if collection is None:
# Might happen with deleted records
continue
for elem, xpath in OAI_COLLECTION_CONTENT.items():
article[elem] = "NA"
if xpath is not None:
result = collection.find(xpath, namespaces)
if result is not None and result.text is not None:
article[elem] = result.text
if processing:
target_string = generator
for variable in variables:
target_string = target_string.replace("%" + variable + "%", article[variable])
article[target] = target_string
if article["euro"] in ["NA", "0"]:
print_r("Article skipped, no APC amount found.")
continue
if article["doi"] != "NA":
norm_doi = get_normalised_DOI(article["doi"])
if norm_doi is None:
article["doi"] = "NA"
else:
article["doi"] = norm_doi
articles.append(article)
counter += 1
token = root.find(token_xpath, namespaces)
if token is not None and token.text is not None:
url = basic_url + "?verb=ListRecords&resumptionToken=" + token.text
print_g(str(counter) + " articles harvested.")
except HTTPError as httpe:
code = str(httpe.getcode())
print("HTTPError: {} - {}".format(code, httpe.reason))
except URLError as urle:
print("URLError: {}".format(urle.reason))
if out_file_suffix:
with open("raw_harvest_data_" + out_file_suffix, "w") as out:
out.write(file_output)
return articles
def find_book_dois_in_crossref(isbn_list):
"""
Take a list of ISBNs and try to obtain book/monograph DOIs from crossref.
Args:
isbn_list: A list of strings representing ISBNs (will not be tested for validity).
Returns:
A dict with a key 'success'. If the lookup was successful,
'success' will be True and the dict will have a second entry 'dois'
which contains a list of obtained DOIs as strings. The list may be empty if the lookup
returned an empty result.
If an error occured during lookup, 'success' will be False and the dict will
contain a second entry 'error_msg' with a string value
stating the reason.
"""
if type(isbn_list) != type([]) or len(isbn_list) == 0:
raise ValueError("Parameter must be a non-empty list!")
filter_list = ["isbn:" + isbn.strip() for isbn in isbn_list]
filters = ",".join(filter_list)
api_url = "https://api.crossref.org/works?filter="
url = api_url + filters + "&rows=500"
request = Request(url)
request.add_header("User-Agent", USER_AGENT)
ret_value = {
"success": False,