-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmdmanager.py
More file actions
executable file
·2496 lines (2184 loc) · 105 KB
/
mdmanager.py
File metadata and controls
executable file
·2496 lines (2184 loc) · 105 KB
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 python
# -*- coding: iso-8859-15 -*-
"""mdmanager.py
Management of metadata
Copyright (c) 2016 Heinrich Widmann (DKRZ) Licensed under AGPLv3.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os, optparse, sys, glob
import time, datetime
import simplejson as json
import logging
import traceback
#
import urllib2
import urllib, urllib2, socket
from itertools import tee
# needed for HARVESTER class:
import sickle as SickleClass
from sickle.oaiexceptions import NoRecordsMatch
from requests.exceptions import ConnectionError
import lxml.etree as etree
import uuid, hashlib
# needed for MAPPER :
from pyparsing import *
import Levenshtein as lvs
import iso639
import codecs
import re
import xml.etree.ElementTree as ET
import io
# needed for UPLOADER class:
from collections import OrderedDict
class HARVESTER(object):
"""
### HARVESTER - class
# Provides methods to harvest metadata records via protocols as OAI-PMH
#
# Parameters:
# -----------
# 1. (dict) pstat - dictionary with the states of every process (was built by main.pstat_init())
# 2. (path) rootdir - rootdir where the subdirs will be created and the harvested files will be saved.
# 3. (string) fromdate - filter for harvesting, format: YYYY-MM-DD
#
# Return Values:
# --------------
# 1. HARVESTER object
#
# Public Methods:
# ---------------
# .harvest(request) - harvest from a source via OAI-PMH using the python module 'Sickle'
#
# Usage:
# ------
# create HARVESTER object
HV = HARVESTER(pstat,rootdir,fromdate)
# harvest from a source via sickle module:
request = [
community,
source,
verb,
mdprefix,
mdsubset
]
results = HV.harvest(request)
"""
def __init__ (self, pstat, base_outdir, fromdate):
# choose the debug level:
## log.basicConfig(format='III')
## self.log_level = {
## 'log':log.INFO,
## 'err':log.ERROR,
## 'err':log.DEBUG,
## 'std':log.INFO,
## }
## self.logger = log.getLogger()
## self.logger.setLevel(log.DEBUG)
self.pstat = pstat
self.base_outdir = base_outdir
self.fromdate = fromdate
def harvest(self, nr, request):
## harvest (HARVESTER object, [community, source, verb, mdprefix, mdsubset]) - method
# Harvest all files with <mdprefix> and <mdsubset> from <source> via sickle module and store those to hard drive.
# Generate every N. file a new subset directory.
#
# Parameters:
# -----------
# (list) request - A request list with following items:
# 1. community
# 2. source
# 3. verb
# 4. mdprefix
# 5. mdsubset
#
# Return Values:
# --------------
# 1. (integer) is -1 if something went wrong
# create a request dictionary:
req = {
"community" : request[0],
"url" : request[1],
"lverb" : request[2],
"mdprefix" : request[3],
"mdsubset" : request[4] if len(request)>4 else None
}
# create dictionary with stats:
stats = {
"tottcount" : 0, # total number of all provided datasets
"totcount" : 0, # total number of all successful harvested datasets
"totecount" : 0, # total number of all failed datasets
"totdcount" : 0, # total number of all deleted datasets
"tcount" : 0, # number of all provided datasets per subset
"count" : 0, # number of all successful harvested datasets per subset
"ecount" : 0, # number of all failed datasets per subset
"dcount" : 0, # number of all deleted datasets per subset
"timestart" : time.time(), # start time per subset process
}
start=time.time()
sickle = SickleClass.Sickle(req['url'], max_retries=3, timeout=300)
outtypedir='xml'
outtypeext='xml'
oaireq=getattr(sickle,req["lverb"], None)
try:
records,rc=tee(oaireq(**{'metadataPrefix':req['mdprefix'],'set':req['mdsubset'],'ignore_deleted':True,'from':self.fromdate}))
except urllib2.HTTPError as e:
logging.error("[ERROR: %s ] Cannot harvest through request %s\n" % (e,req))
return -1
except ConnectionError as e:
logging.error("[ERROR: %s ] Cannot harvest through request %s\n" % (e,req))
return -1
except etree.XMLSyntaxError as e:
logging.error("[ERROR: %s ] Cannot harvest through request %s\n" % (e,req))
return -1
except Exception, e:
logging.error("[ERROR %s ] : %s" % (e,traceback.format_exc()))
return -1
ntotrecs=sum(1 for _ in rc)
print "\t|- Iterate through %d records in %d sec" % (ntotrecs,time.time()-start)
logging.debug(' | | %-4s | %-45s | %-45s |\n |%s|' % ('#','OAI Identifier','DS Identifier',"-" * 106))
# set subset:
if (not req["mdsubset"]):
subset = 'SET'
else:
subset = req["mdsubset"]
# make subset dir:
subsetdir = '/'.join([self.base_outdir,req['community']+'-'+req['mdprefix'],subset])
noffs=0 # set to number of record, where harvesting should start
start2=time.time()
fcount=0
oldperc=0
logging.info("\t|- Get records and store on disc ...")
for record in records:
stats['tcount'] += 1
## counter and progress bar
fcount+=1
if fcount <= noffs : continue
perc=int(fcount*100/ntotrecs)
bartags=perc/5 #HEW-D fcount/100
if perc%10 == 0 and perc != oldperc :
oldperc=perc
print "\r\t[%-20s] %5d (%3d%%) in %d sec" % ('='*bartags, fcount, perc, time.time()-start2 )
sys.stdout.flush()
if req["lverb"] == 'ListIdentifiers' :
if (record.deleted):
##HEW-??? deleted_metadata[record.identifier] =
stats['totdcount'] += 1
continue
else:
oai_id = record.identifier
record = sickle.GetRecord(**{'metadataPrefix':req['mdprefix'],'identifier':record.identifier})
elif req["lverb"] == 'ListRecords' :
if (record.header.deleted):
stats['totdcount'] += 1
continue
else:
oai_id = record.header.identifier
# generate a uniquely identifier for this dataset:
uid = str(uuid.uuid5(uuid.NAMESPACE_DNS, oai_id.encode('ascii','replace')))
xmlfile = subsetdir + '/xml/' + os.path.basename(uid) + '.xml'
try:
logging.debug(' | h | %-4d | %-45s | %-45s |' % (stats['count']+1,oai_id,uid))
## logging.debug('Harvested XML file written to %s' % xmlfile)
# get the raw xml content:
metadata = etree.fromstring(record.raw)
if (metadata is not None):
metadata = etree.tostring(metadata, pretty_print = True)
metadata = metadata.encode('ascii', 'ignore')
if (not os.path.isdir(subsetdir+'/xml')):
os.makedirs(subsetdir+'/xml')
# write metadata in file:
try:
f = open(xmlfile, 'w')
f.write(metadata)
f.close
except IOError, e:
logging.error("[ERROR] Cannot write metadata in xml file '%s': %s\n" % (xmlfile,e))
stats['ecount'] +=1
continue
stats['count'] += 1
## logging.debug('Harvested XML file written to %s' % xmlfile)
else:
stats['ecount'] += 1
logging.warning(' [WARNING] No metadata available for %s' % oai_id)
except TypeError as e:
logging.error(' [ERROR] TypeError: %s' % e)
stats['ecount']+=1
continue
except Exception as e:
logging.error(" [ERROR] %s and %s" % (e,traceback.format_exc()))
## logging.debug(metadata)
stats['ecount']+=1
continue
class MAPPER():
"""
### MAPPER - class
# Parameters:
# -----------
#
# Return Values:
# --------------
# MAPPER object
#
# Public Methods:
# ---------------
# map(community, mdprefix, path) - maps all files in <path> to JSON format by using community and md format specific
# mapfiles in md-mapping and stores those files in subdirectory '../json'
#
# Usage:
# ------
# create MAPPER object:
MP = MAPPER(OUT)
path = 'oaidata/enes-iso/subset1'
community = 'enes'
mdprefix = 'iso'
# map all files of the 'xml' dir in <path> by using mapfile which is defined by <community> and <mdprefix>
results = MP.map(community,mdprefix,path)
"""
def __init__ (self):
self.logger = logging.getLogger()
# B2FIND metadata fields
self.b2findfields =["title","notes","tags","url","DOI","PID","Checksum","Rights","Discipline","author","Publisher","PublicationYear","PublicationTimestamp","Language","TemporalCoverage","SpatialCoverage","Format","Contact","MetadataAccess"]
self.ckan2b2find = OrderedDict()
self.ckan2b2find={
"title" : "title",
"notes" : "description",
"tags" : "tags",
"url" : "Source",
"DOI" : "DOI",
### "IVO" : "IVO",
"PID" : "PID",
"Checksum" : "checksum",
"Rights" : "rights",
## "Community" : "community",
"Discipline" : "discipline",
"author" : "Creator",
"Publisher" : "Publisher",
"PublicationYear" : "PublicationYear",
"PublicationTimestamp" : "PublicationTimestamp",
"Language" : "language",
"TemporalCoverage" : "temporalcoverage",
"SpatialCoverage" : "spatialcoverage",
"spatial" : "spatial",
"Format" : "format",
"Contact" : "contact",
"MetadataAccess" : "metadata"
}
## settings for pyparsing
nonBracePrintables = ''
unicodePrintables = u''.join(unichr(c) for c in xrange(65536)
if not unichr(c).isspace())
for c in unicodePrintables: ## printables:
if c not in '(){}[]':
nonBracePrintables = nonBracePrintables + c
self.enclosed = Forward()
value = Combine(OneOrMore(Word(nonBracePrintables) ^ White(' ')))
nestedParens = nestedExpr('(', ')', content=self.enclosed)
nestedBrackets = nestedExpr('[', ']', content=self.enclosed)
nestedCurlies = nestedExpr('{', '}', content=self.enclosed)
self.enclosed << OneOrMore(value | nestedParens | nestedBrackets | nestedCurlies)
class cv_disciplines(object):
"""
This class represents the closed vocabulary used for the mapoping of B2FIND discipline mapping
Copyright (C) 2014 Heinrich Widmann.
"""
def __init__(self):
self.discipl_list = self.get_list()
@staticmethod
def get_list():
import csv
import os
discipl_file = '%s/mapfiles/b2find_disciplines.tab' % (os.getcwd())
disctab = []
with open(discipl_file, 'r') as f:
## define csv reader object, assuming delimiter is tab
tsvfile = csv.reader(f, delimiter='\t')
## iterate through lines in file
for line in tsvfile:
disctab.append(line)
return disctab
def str_equals(self,str1,str2):
"""
performs case insensitive string comparison by first stripping trailing spaces
"""
return str1.strip().lower() == str2.strip().lower()
def date2UTC(self,old_date):
"""
changes date to UTC format
"""
# UTC format = YYYY-MM-DDThh:mm:ssZ
try:
utc = re.compile(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z')
utc_day1 = re.compile(r'\d{4}-\d{2}-\d{2}') # day (YYYY-MM-DD)
utc_day = re.compile(r'\d{8}') # day (YYYYMMDD)
utc_year = re.compile(r'\d{4}') # year (4-digit number)
if utc.search(old_date):
new_date = utc.search(old_date).group()
return new_date
elif utc_day1.search(old_date):
day = utc_day1.search(old_date).group()
new_date = day + 'T11:59:59Z'
return new_date
elif utc_day.search(old_date):
rep=re.findall(utc_day, old_date)[0]
new_date = rep[0:4]+'-'+rep[4:6]+'-'+rep[6:8] + 'T11:59:59Z'
return new_date
elif utc_year.search(old_date):
year = utc_year.search(old_date).group()
new_date = year + '-07-01T11:59:59Z'
return new_date
else:
return '' # if converting cannot be done, make date empty
except Exception, e:
logging.error('[ERROR] : %s - in date2UTC replace old date %s by new date %s' % (e,old_date,new_date))
return ''
else:
return new_date
def map_identifiers(self, invalue):
"""
Convert identifiers to data access links, i.e. to 'Source' (ds['url']) or 'PID','DOI' etc. pp
Copyright (C) 2015 by Heinrich Widmann.
Licensed under AGPLv3.
"""
try:
## idarr=invalue.split(";")
iddict=dict()
favurl=invalue[0] ### idarr[0]
for id in invalue :
if id.startswith('http://data.theeuropeanlibrary'):
iddict['url']=id
elif id.startswith('ivo:'):
iddict['IVO']='http://registry.euro-vo.org/result.jsp?searchMethod=GetResource&identifier='+id
favurl=iddict['IVO']
elif id.startswith('10.'): ##HEW-??? or id.startswith('10.5286') or id.startswith('10.1007') :
iddict['DOI'] = self.concat('http://dx.doi.org/',id)
favurl=iddict['DOI']
elif 'dx.doi.org/' in id:
iddict['DOI'] = id
favurl=iddict['DOI']
elif 'doi:' in id: ## and 'DOI' not in iddict :
iddict['DOI'] = 'http://dx.doi.org/doi:'+re.compile(".*doi:(.*)\s?.*").match(id).groups()[0].strip(']')
favurl=iddict['DOI']
elif 'hdl.handle.net' in id:
iddict['PID'] = id
favurl=iddict['PID']
elif 'hdl:' in id:
iddict['PID'] = id.replace('hdl:','http://hdl.handle.net/')
favurl=iddict['PID']
## elif 'url' not in iddict: ##HEW!!?? bad performance --> and self.check_url(id) :
## iddict['url']=id
if 'url' not in iddict :
iddict['url']=favurl
except Exception, e:
logging.error('[ERROR] : %s - in map_identifiers %s can not converted !' % (e,invalue))
return None
else:
return iddict
def map_lang(self, invalue):
"""
Convert languages and language codes into ISO names
Copyright (C) 2014 Mikael Karlsson.
Adapted for B2FIND 2014 Heinrich Widmann
Licensed under AGPLv3.
"""
def mlang(language):
if '_' in language:
language = language.split('_')[0]
if ':' in language:
language = language.split(':')[1]
if len(language) == 2:
try: return iso639.languages.get(alpha2=language.lower())
except KeyError: pass
elif len(language) == 3:
try: return iso639.languages.get(alpha3=language.lower())
except KeyError: pass
except AttributeError: pass
try: return iso639.languages.get(terminology=language.lower())
except KeyError: pass
try: return iso639.languages.get(bibliographic=language.lower())
except KeyError: pass
else:
try: return iso639.languages.get(name=language.title())
except KeyError: pass
for l in re.split('[,.;: ]+', language):
try: return iso639.languages.get(name=l.title())
except KeyError: pass
newvalue=list()
for lang in invalue:
mcountry = mlang(lang)
if mcountry:
newvalue.append(mcountry.name)
return newvalue
def map_temporal(self,invalue):
"""
Map date-times to B2FIND start and end time
Copyright (C) 2015 Heinrich Widmann
Licensed under AGPLv3.
"""
desc=''
try:
if type(invalue) is list:
invalue=invalue[0]
if type(invalue) is dict :
if '@type' in invalue :
if invalue['@type'] == 'single':
if "date" in invalue :
desc+=' %s : %s' % (invalue["@type"],invalue["date"])
return (desc,self.date2UTC(invalue["date"]),self.date2UTC(invalue["date"]))
else :
desc+='%s' % invalue["@type"]
return (desc,None,None)
elif invalue['@type'] == 'verbatim':
if 'period' in invalue :
desc+=' %s : %s' % (invalue["type"],invalue["period"])
else:
desc+='%s' % invalue["type"]
return (desc,None,None)
elif invalue['@type'] == 'range':
if 'start' in invalue and 'end' in invalue :
desc+=' %s : ( %s - %s )' % (invalue['@type'],invalue["start"],invalue["end"])
return (desc,self.date2UTC(invalue["start"]),self.date2UTC(invalue["end"]))
else:
desc+='%s' % invalue["@type"]
return (desc,None,None)
elif 'start' in invalue and 'end' in invalue :
desc+=' %s : ( %s - %s )' % ('range',invalue["start"],invalue["end"])
return (desc,self.date2UTC(invalue["start"]),self.date2UTC(invalue["end"]))
else:
return (desc,None,None)
else:
outlist=list()
invlist=invalue.split(';')
if len(invlist) == 1 :
try:
desc+=' point in time : %s' % self.date2UTC(invlist[0])
return (desc,self.date2UTC(invlist[0]),self.date2UTC(invlist[0]))
except ValueError:
return (desc,None,None)
## else:
## desc+=': ( %s - %s ) ' % (self.date2UTC(invlist[0]),self.date2UTC(invlist[0]))
## return (desc,self.date2UTC(invlist[0]),self.date2UTC(invlist[0]))
elif len(invlist) == 2 :
try:
desc+=' period : ( %s - %s ) ' % (self.date2UTC(invlist[0]),self.date2UTC(invlist[1]))
return (desc,self.date2UTC(invlist[0]),self.date2UTC(invlist[1]))
except ValueError:
return (desc,None,None)
else:
return (desc,None,None)
except Exception, e:
logging.debug('[ERROR] : %s - in map_temporal %s can not converted !' % (e,invalue))
return (None,None,None)
else:
return (desc,None,None)
def is_float_try(self,str):
try:
float(str)
return True
except ValueError:
return False
def map_spatial(self,invalue):
"""
Map coordinates to spatial
Copyright (C) 2014 Heinrich Widmann
Licensed under AGPLv3.
"""
desc=''
pattern = re.compile(r";|\s+")
try:
if type(invalue) is not list :
invalue=invalue.split() ##HEW??? [invalue]
coordarr=list()
nc=0
for val in invalue:
if type(val) is dict :
coordict=dict()
if "description" in val :
desc=val["description"]
if "boundingBox" in val :
coordict=val["boundingBox"]
desc+=' : [ %s , %s , %s, %s ]' % (coordict["minLatitude"],coordict["maxLongitude"],coordict["maxLatitude"],coordict["minLongitude"])
return (desc,coordict["minLatitude"],coordict["maxLongitude"],coordict["maxLatitude"],coordict["minLongitude"])
else :
return (desc,None,None,None,None)
else:
valarr=val.split()
for v in valarr:
if self.is_float_try(v) is True :
coordarr.append(v)
nc+=1
else:
desc+=' '+v
if len(coordarr)==2 :
desc+=' boundingBox : [ %s , %s , %s, %s ]' % (coordarr[0],coordarr[1],coordarr[0],coordarr[1])
return(desc,coordarr[0],coordarr[1],coordarr[0],coordarr[1])
elif len(coordarr)==4 :
desc+=' boundingBox : [ %s , %s , %s, %s ]' % (coordarr[0],coordarr[1],coordarr[2],coordarr[3])
return(desc,coordarr[0],coordarr[1],coordarr[2],coordarr[3])
except Exception, e:
logging.error('[ERROR] : %s - in map_spatial invalue %s can not converted !' % (e,invalue))
return (None,None,None,None,None)
def map_discipl(self,invalue,disctab):
"""
Convert disciplines along B2FIND disciplinary list
Copyright (C) 2014 Heinrich Widmann
Licensed under AGPLv3.
"""
retval=list()
if type(invalue) is not list :
inlist=re.split(r'[;&\s]\s*',invalue)
inlist.append(invalue)
else:
seplist=[re.split(r"[;&]",i) for i in invalue]
swlist=[re.findall(r"[\w']+",i) for i in invalue]
inlist=swlist+seplist
inlist=[item for sublist in inlist for item in sublist]
for indisc in inlist :
##indisc=indisc.encode('ascii','ignore').capitalize()
indisc=indisc.encode('utf8').replace('\n',' ').replace('\r',' ').strip().title()
maxr=0.0
maxdisc=''
for line in disctab :
try:
disc=line[2].strip()
r=lvs.ratio(indisc,disc)
except Exception, e:
logging.error('[ERROR] %s in map_discipl : %s can not compared to %s !' % (e,indisc,disc))
continue
if r > maxr :
maxdisc=disc
maxr=r
##HEW-T print '--- %s \n|%s|%s| %f | %f' % (line,indisc,disc,r,maxr)
if maxr == 1 and indisc == maxdisc :
logging.debug(' | Perfect match of %s : nothing to do' % indisc)
retval.append(indisc.strip())
elif maxr > 0.90 :
logging.debug(' | Similarity ratio %f is > 0.90 : replace value >>%s<< with best match --> %s' % (maxr,indisc,maxdisc))
##return maxdisc
retval.append(indisc.strip())
else:
logging.debug(' | Similarity ratio %f is < 0.90 compare value >>%s<< and discipline >>%s<<' % (maxr,indisc,maxdisc))
continue
if len(retval) > 0:
retval=list(OrderedDict.fromkeys(retval)) ## this elemenates real duplicates
return ';'.join(retval)
else:
return 'Not stated'
def cut(self,invalue,pattern,nfield=None):
"""
Invalue is expected as list. Loop over invalue and for each elem :
- If pattern is None truncate characters specified by nfield (e.g. ':4' first 4 char, '-2:' last 2 char, ...)
else if pattern is in invalue, split according to pattern and return field nfield (if 0 return the first found pattern),
else return invalue.
Copyright (C) 2015 Heinrich Widmann.
Licensed under AGPLv3.
"""
outvalue=list()
if not isinstance(invalue,list): invalue = invalue.split()
for elem in invalue:
if pattern is None :
if nfield :
outvalue.append(elem[nfield])
else:
outvalue.append(elem)
else:
rep=re.findall(pattern, elem)
if len(rep) > 0 :
outvalue.append(rep[nfield])
else:
outvalue.append(elem)
##else:
## log.error('[ERROR] : cut expects as invalue (%s) a list' % invalue)
## return None
return outvalue
def list2dictlist(self,invalue,valuearrsep):
"""
transfer list of strings/dicts to list of dict's { "name" : "substr1" } and
- eliminate duplicates, numbers and 1-character- strings, ...
"""
dictlist=[]
valarr=[]
bad_chars = '(){}<>:'
if isinstance(invalue,dict):
invalue=invalue.values()
elif not isinstance(invalue,list):
invalue=invalue.split(';')
invalue=list(OrderedDict.fromkeys(invalue)) ## this eliminates real duplicates
for lentry in invalue :
try:
if type(lentry) is dict :
if "value" in lentry:
valarr.append(lentry["value"])
else:
valarr=lentry.values()
else:
##valarr=filter(None, re.split(r"([,\!?:;])+",lentry)) ## ['name']))
valarr=re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+',lentry)
for entry in valarr:
entry="". join(c for c in entry if c not in bad_chars)
if isinstance(entry,int) or len(entry) < 2 : continue
entry=entry.encode('utf-8').strip()
dictlist.append({ "name": entry.replace('/','-') })
except AttributeError, err :
log.error('[ERROR] %s in list2dictlist of lentry %s , entry %s' % (err,lentry,entry))
continue
except Exception, e:
log.error('[ERROR] %s in list2dictlist of lentry %s, entry %s ' % (e,lentry,entry))
continue
return dictlist[:12]
def uniq(self,input,joinsep=None):
uniqset = set(input)
##if joinsep :
## return joinsep.join(list(set))
##else :
return list(uniqset)
def concat(self,str1,str2):
"""
concatenete given strings
Copyright (C) 2015 Heinrich Widmann.
Licensed under AGPLv3.
"""
return str1+str2
def utc2seconds(self,dt):
"""
converts datetime to seconds since year 0
Copyright (C) 2015 Heinrich Widmann.
Licensed under AGPLv3.
"""
year1epochsec=62135600400
utc1900=datetime.datetime.strptime("1900-01-01T11:59:59Z", "%Y-%m-%dT%H:%M:%SZ")
utc=self.date2UTC(dt)
try:
##utctime=datetime.datetime(utc).isoformat()
##print 'utctime %s' % utctime
utctime = datetime.datetime.strptime(utc, "%Y-%m-%dT%H:%M:%SZ") ##HEW-?? .isoformat()
diff = utc1900 - utctime
diffsec= int(diff.days) * 24 * 60 *60
if diff > datetime.timedelta(0): ## date is before 1900
sec=int(time.mktime((utc1900).timetuple()))-diffsec+year1epochsec
else:
sec=int(time.mktime(utctime.timetuple()))+year1epochsec
except Exception, e:
logging.error('[ERROR] : %s - in utc2seconds date-time %s can not converted !' % (e,utc))
return None
return sec
def evalxpath(self, obj, expr, ns):
# returns list of selected entries from xml obj using xpath expr
flist=re.split(r'[\(\),]',expr.strip()) ### r'[(]',expr.strip())
retlist=list()
for func in flist:
func=func.strip()
if func.startswith('//'):
fxpath= '.'+re.sub(r'/text()','',func)
try:
for elem in obj.findall(fxpath,ns):
if elem.text :
retlist.append(elem.text)
except Exception as e:
print 'ERROR %s : during xpath extraction of %s' % (e,fxpath)
return []
elif func == '/':
try:
for elem in obj.findall('.//',ns):
retlist.append(elem.text)
except Exception as e:
print 'ERROR %s : during xpath extraction of %s' % (e,'./')
return []
return retlist
def xpathmdmapper(self,xmldata,xrules,namespaces):
# returns list or string, selected from xmldata by xpath rules (and namespaces)
logging.debug(' | %10s | %10s | %10s | \n' % ('Field','XPATH','Value'))
jsondata=dict()
for line in xrules:
try:
m = re.match(r'(\s+)<field name="(.*?)">', line)
if m:
field=m.group(2)
if field in ['Discipline','oai_set']: ## HEW!!! expand to all mandatory fields !!
retval=['Not stated']
else:
xpath=''
r = re.compile('(\s+)(<xpath>)(.*?)(</xpath>)')
m2 = r.search(line)
rs = re.compile('(\s+)(<string>)(.*?)(</string>)')
m3 = rs.search(line)
if m3:
xpath=m3.group(3)
retval=xpath
elif m2:
xpath=m2.group(3)
retval=self.evalxpath(xmldata, xpath, namespaces)
else:
continue
if retval and len(retval) > 0 :
jsondata[field]=retval ### .extend(retval)
logging.debug(' | %-10s | %10s | %20s | \n' % (field,xpath,retval[:20]))
elif field in ['Discipline','oai_set']:
jsondata[field]=['Not stated']
except Exception as e:
logging.error(' | [ERROR] : %s in xpathmdmapper processing\n\tfield\t%s\n\txpath\t%s\n\tretvalue\t%s' % (e,field,xpath,retval))
continue
return jsondata
def map(self,nr,community,mdprefix,path,target_mdschema):
## map(MAPPER object, community, mdprefix, path) - method
# Maps the XML files in directory <path> to JSON files
# For each file two steps are performed
# 1. select entries by Python XPATH converter according
# the mapfile [<community>-]<mdprefix>.xml .
# 2. perform generic and semantic mapping versus iso standards and closed vovabularies ...
#
# Parameters:
# -----------
# 1. (string) community - B2FIND community of the files
# 2. (string) mdprefix - Metadata prefix which was used by HARVESTER class for harvesting these files
# 3. (string) path - path to directory of harvested records (without 'xml' rsp. 'hjson' subdirectory)
#
# Return Values:
# --------------
# 1. (dict) results statistics
results = {
'count':0,
'tcount':0,
'ecount':0,
'time':0
}
# settings according to md format (xml or json processing)
if mdprefix == 'json' :
mapext='conf' ##HEW!! --> json !!!!
insubdir='/hjson'
infformat='json'
else:
mapext='xml'
insubdir='/xml'
infformat='xml'
# check input and output paths
if not os.path.exists(path):
logging.error('[ERROR] The directory "%s" does not exist! No files to map !' % (path))
return results
elif not os.path.exists(path + insubdir) or not os.listdir(path + insubdir):
logging.error('[ERROR] The input directory "%s%s" does not exist or no %s-files to convert are found !\n(Maybe your convert list has old items?)' % (path,insubdir,insubdir))
return results
# make output directory for mapped json's
if (target_mdschema and not target_mdschema.startswith('#')):
outpath=path+'-'+target_mdschema+'/json'
else:
outpath=path+'/json'
if (not os.path.isdir(outpath)):
os.makedirs(outpath)
# check and read rules from mapfile
if (target_mdschema and not target_mdschema.startswith('#')):
mapfile='%s/mapfiles/%s-%s.%s' % (os.getcwd(),community,target_mdschema,mapext)
else:
mapfile='%s/mapfiles/%s-%s.%s' % (os.getcwd(),community,mdprefix,mapext)
if not os.path.isfile(mapfile):
logging.error('[WARNING] Mapfile %s does not exist !' % mapfile)
mapfile='%s/mapfiles/%s.%s' % (os.getcwd(),mdprefix,mapext)
if not os.path.isfile(mapfile):
logging.error('[ERROR] Mapfile %s does not exist !' % mapfile)
return results
logging.debug(' |- Mapfile\t%s' % os.path.basename(mapfile))
mf = codecs.open(mapfile, "r", "utf-8")
maprules = mf.readlines()
maprules = filter(lambda x:len(x) != 0,maprules) # removes empty lines
# check namespaces
namespaces=dict()
for line in maprules:
ns = re.match(r'(\s+)(<namespace ns=")(\w+)"(\s+)uri="(.*)"/>', line)
if ns:
namespaces[ns.group(3)]=ns.group(5)
continue
logging.debug(' |- Namespaces\t%s' % json.dumps(namespaces,sort_keys=True, indent=4))
# check specific postproc mapping config file
subset=os.path.basename(path).split('_')[0]
specrules=None
ppconfig_file='%s/mapfiles/mdpp-%s-%s.conf' % (os.getcwd(),community,mdprefix)
if os.path.isfile(ppconfig_file):
# read config file
f = codecs.open(ppconfig_file, "r", "utf-8")
specrules = f.readlines()[1:] # without the header
specrules = filter(lambda x:len(x) != 0,specrules) # removes empty lines
## filter out community and subset specific specrules
subsetrules = filter(lambda x:(x.startswith(community+',,'+subset)),specrules)
if subsetrules:
specrules=subsetrules
else:
specrules=filter(lambda x:(x.startswith('*,,*')),specrules)
# instance of B2FIND discipline table
disctab = self.cv_disciplines()
# instance of British English dictionary
##HEW-T dictEn = enchant.Dict("en_GB")
# loop over all files (harvested records) in input path ( path/xml or path/hjson)
##HEW-D results['tcount'] = len(filter(lambda x: x.endswith('.json'), os.listdir(path+'/hjson')))
files = filter(lambda x: x.endswith(infformat), os.listdir(path+insubdir))
results['tcount'] = len(files)
fcount = 0
oldperc=0
err = None
logging.debug(' %s INFO Processing of %s files in %s/%s' % (time.strftime("%H:%M:%S"),infformat,path,insubdir))
## start processing loop
start = time.time()
for filename in files:
## counter and progress bar
fcount+=1
perc=int(fcount*100/int(len(files)))
bartags=perc/5
##??? perc=int(fcount*100/int(100)) ##HEW-?? len(records) not known
if perc%10 == 0 and perc != oldperc:
oldperc=perc
print "\r\t[%-20s] %5d (%3d%%) in %d sec" % ('='*bartags, fcount, perc, time.time()-start )
sys.stdout.flush()
jsondata = dict()
infilepath=path+insubdir+'/'+filename
if ( os.path.getsize(infilepath) > 0 ):
## load and parse raw xml rsp. json
with open(infilepath, 'r') as f:
try:
if mdprefix == 'json':
jsondata=json.loads(f.read())
##HEW-D ???!!! hjsondata=json.loads(f.read())
else:
xmldata= ET.parse(infilepath)
except Exception as e:
logging.error(' | [ERROR] %s : Cannot load or parse %s-file %s' % (e,infformat,infilepath))
results['ecount'] += 1
continue
## XPATH rsp. JPATH converter
if mdprefix == 'json':
try:
logging.debug(' |- %s INFO %s to JSON FileProcessor - Processing: %s%s/%s' % (time.strftime("%H:%M:%S"),infformat,os.path.basename(path),insubdir,filename))
jsondata=self.jsonmdmapper(jsondata,maprules)
except Exception as e:
logging.error(' | [ERROR] %s : during %s 2 json processing' % (infformat,e) )
results['ecount'] += 1
continue
else:
try:
# Run Python XPATH converter
logging.debug(' | xpath | %-4d | %-45s |' % (fcount,os.path.basename(filename)))
jsondata=self.xpathmdmapper(xmldata,maprules,namespaces)
except Exception as e:
logging.error(' | [ERROR] %s : during XPATH processing' % e )
results['ecount'] += 1
continue
try:
## md postprocessor
if (specrules):
logging.debug(' [INFO]: Processing according specrules %s' % specrules)
jsondata=self.postprocess(jsondata,specrules)
except Exception as e:
logging.error(' [ERROR] %s : during postprocessing' % (e))
continue
iddict=dict()
blist=list()
spvalue=None
stime=None
etime=None
publdate=None
# loop over all fields
for facet in jsondata:
logging.debug('facet %s ...' % facet)
try:
if facet == 'author':
jsondata[facet] = self.uniq(self.cut(jsondata[facet],'\(\d\d\d\d\)',1),';')