-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmapping.py
2060 lines (1823 loc) · 89.4 KB
/
mapping.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
# -*- coding: utf-8 -*-
"""mapping.py - class for B2FIND mapping :
- Mapper maps harvested nad specific MD records onto B2FIND schema
Copyright (c) 2013 Heinrich Widmann (DKRZ)
Further contributions by
2013 John Mrziglod (DKRZ)
2014 Mikael Karlsson
2017 Claudia Martens
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.
"""
# from future
from __future__ import absolute_import
from __future__ import print_function
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
__author__ = "Heinrich Widmann"
# system relevant modules:
import os, glob, sys
import time, datetime, subprocess
# program relevant modules:
import logging
import traceback
import re
from output import Output
# needed for MAPPER :
import codecs
import xml.etree.ElementTree as ET
import simplejson as json
import io
from pyparsing import *
import Levenshtein as lvs
import iso639
from collections import OrderedDict, Iterable, Counter
PY2 = sys.version_info[0] == 2
if PY2:
from urllib2 import urlopen
from urllib2 import HTTPError,URLError
else:
from urllib.request import urlopen
from urllib.error import HTTPError,URLError
class Mapper(object):
"""
### MAPPER - class
# Parameters:
# -----------
# Public Methods:
# ---------------
# map(request) - maps records according to request on B21FIND schema
# using mapfiles in md-mapping and stores resulting files in subdirectory '../json'
#
"""
def __init__ (self, OUT, base_outdir,fromdate):
##HEW-D logging = logging.getLogger()
self.base_outdir = base_outdir
self.fromdate = fromdate
self.logger = logging.getLogger('root')
self.OUT = OUT
# Read in B2FIND metadata schema and fields
schemafile = '%s/mapfiles/b2find_schema.json' % (os.getcwd())
with open(schemafile, 'r') as f:
self.b2findfields=json.loads(f.read(), object_pairs_hook=OrderedDict)
## settings for pyparsing
nonBracePrintables = ''
if PY2:
unicodePrintables = u''.join(unichr(c) for c in range(65536)
if not unichr(c).isspace())
else:
unicodePrintables = u''.join(chr(c) for c in range(65536)
if not chr(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
disctab = []
discipl_file = '%s/mapfiles/b2find_disciplines.json' % (os.getcwd())
with open(discipl_file) as f:
disctab = json.load(f)['disciplines']
return disctab
class cv_geonames(object):
"""
This class represents the closed vocabulary used for the mapoping of B2FIND spatial coverage to coordinates
Copyright (C) 2016 Heinrich Widmann.
"""
def __init__(self):
self.geonames_list = self.get_list()
@staticmethod
def get_list():
import csv
import os
geonames_file = '%s/mapfiles/b2find_geonames.tab' % (os.getcwd())
geonamestab = []
with open(geonames_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:
geonamestab.append(line)
return geonamestab
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:
if type(old_date) is list:
inlist=old_date
else:
inlist=[old_date]
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)
new_date=None
for val in inlist:
if utc.search(val):
new_date = utc.search(val).group()
elif utc_day1.search(val):
day = utc_day1.search(val).group()
new_date = day + 'T11:59:59Z'
elif utc_day.search(val):
rep=re.findall(utc_day, val)[0]
new_date = rep[0:4]+'-'+rep[4:6]+'-'+rep[6:8] + 'T11:59:59Z'
elif utc_year.search(val):
year = utc_year.search(val).group()
new_date = year + '-07-01T11:59:59Z'
return new_date
except Exception :
logging.error('[ERROR] : %s - in date2UTC replace old date %s by new date %s' % (e,val,new_date))
return None
else:
return new_date
def replace(self,setname,dataset,facet,old_value,new_value):
"""
replaces old value - can be a regular expression - with new value for a given facet
"""
try:
old_regex = re.compile(old_value)
for key in dataset:
if key == facet :
if re.match(old_regex, dataset[key]):
dataset[key] = new_value
return dataset
except Exception :
logging.error('[ERROR] : %s - in replace of pattern %s in facet %s with new_value %s' % (e,old_value,facet,new_value))
return dataset
else:
return dataset
return dataset
def check_url(self,url):
## check_url (MAPPER object, url) - method
# Checks and validates a url via urllib module
#
# Parameters:
# -----------
# (url) url - Url to check
#
# Return Values:
# --------------
# 1. (boolean) result
try:
resp = urlopen(url, timeout=10).getcode()
except HTTPError as err:
if (err.code == 422):
self.logger.error('%s in check_url of %s' % (err.code,url))
return Warning
else :
return False
except URLError as err: ## HEW : stupid workaraound for SSL: CERTIFICATE_VERIFY_FAILED]
self.logger.warning('%s in check_url of %s' % (err,url))
if str(e.reason).startswith('[SSL: CERTIFICATE_VERIFY_FAILED]') :
return Warning
else :
return False
else:
return True
def map_url(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:
if type(invalue) is not list :
invalue=invalue.split(";")
iddict=dict()
self.logger.debug('invalue %s' % invalue)
for id in filter(None,invalue) :
self.logger.debug(' id\t%s' % id)
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
elif id.startswith('10.'): ##HEW-??? or id.startswith('10.5286') or id.startswith('10.1007') :
iddict['DOI'] = self.concat('http://dx.doi.org/doi:',id)
elif 'doi.org/' in id:
iddict['DOI'] = 'http://dx.doi.org/'+re.compile(".*doi.org/(.*)\s?.*").match(id).groups()[0].strip(']')
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(']')
elif 'hdl.handle.net' in id:
reurl = re.search("(?P<url>https?://[^\s<>]+)", id)
if reurl :
iddict['PID'] = reurl.group("url")
elif 'hdl:' in id:
iddict['PID'] = id.replace('hdl:','http://hdl.handle.net/')
elif 'http:' in id or 'https:' in id:
reurl = re.search("(?P<url>https?://[^\s<>]+)", id)
if reurl :
iddict['url'] = reurl.group("url")##[0]
except Exception as e :
self.logger.critical('%s - in map_identifiers %s can not converted !' % (e,invalue))
return {}
else:
if self.OUT.verbose > 3 :
for id in iddict :
self.logger.debug('iddict\t(%s,%s)' % (id,iddict[id]))
if self.check_url(iddict[id]):
self.logger.debug('Identifier %s checked successfully' % iddict[id])
else:
self.logger.crtitical('Identifier %s failed in url checker' % iddict[id])
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()
if type(invalue) == list :
for lang in invalue:
mcountry = mlang(lang)
if mcountry:
newvalue.append(mcountry.name)
else:
mcountry = mlang(invalue)
if mcountry:
newvalue.append(mcountry.name)
return newvalue
def map_geonames(self,invalue):
"""
Map geonames to coordinates
Copyright (C) 2014 Heinrich Widmann
Licensed under AGPLv3.
"""
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderQuotaExceeded
geolocator = Nominatim()
try:
location = geolocator.geocode(invalue.split(';')[0])
if not location :
return None ### (None,None)
if location.raw['importance'] < 0.9 :
return None
except GeocoderQuotaExceeded:
logging.error('%s can not converted !' % (invalue.split(';')[0]))
sleep(5)
return None
except Exception :
logging.error('[ERROR] : %s - in map_geonames %s can not converted !' % (e,invalue.split(';')[0]))
return None ### (None,None)
else:
return location ### (location.latitude, location.longitude)
def map_temporal(self,invalue):
"""
Map date-times to B2FIND start and end time
Copyright (C) 2015 Heinrich Widmann
Licensed under AGPLv3.
"""
desc=''
try:
logging.info('Invalue\t%s' % invalue)
if type(invalue) is not list:
invalue=invalue.split(';')
if type(invalue[0]) is dict :
invalue=invalue[0]
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()
if len(invalue) == 1 :
try:
desc+=' point in time : %s' % self.date2UTC(invalue[0])
return (desc,self.date2UTC(invalue[0]),self.date2UTC(invalue[0]))
except ValueError:
return (desc,None,None)
## else:
## desc+=': ( %s - %s ) ' % (self.date2UTC(invalue[0]),self.date2UTC(invalue[0]))
## return (desc,self.date2UTC(invalue[0]),self.date2UTC(invalue[0]))
elif len(invalue) == 2 :
try:
desc+=' period : ( %s - %s ) ' % (self.date2UTC(invalue[0]),self.date2UTC(invalue[1]))
return (desc,self.date2UTC(invalue[0]),self.date2UTC(invalue[1]))
except ValueError:
return (desc,None,None)
else:
return (desc,None,None)
except Exception :
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 flatten(self,l):
for el in l:
if isinstance(el, Iterable) and not isinstance(el, str):
for sub in flatten(el):
yield sub
else:
yield el
def check_spatial(self,invalue,geotab):
"""
Check spatial coverage and map to representiable form
Copyright (C) 2018 Heinrich Widmann
Licensed under AGPLv3.
"""
self.logger.debug('invalue %s' % (invalue,))
if not any(invalue) :
self.logger.warning('Coordinate list has only None entries : %s' % (invalue,))
return (desc,None,None,None,None)
desc=''
## check coordinates
if len(invalue) > 1 :
for lat in [invalue[1],invalue[3]]:
if float(lat) < -90. or float(lat) > 90. :
self.logger.error('Latitude %s is not in range [-90,90]' % lat)
for lon in [invalue[2],invalue[4]]:
if float(lon) < 0. or float(lon) > 360. :
self.logger.warning('Longitude %s is not in range [0,360]' % lon)
if float(lon) < -180. or float(lon) > 180 :
self.logger.critical('Longitude %s is not in range [-180,180] nor in [0,360]' % lon)
if invalue[1]==invalue[3] and invalue[2]==invalue[4] :
self.logger.info('[%s,%s] seems to be a point' % (invalue[1],invalue[2]))
if float(invalue[1]) > 0 : # northern latitude
desc+='(%-2.0fN,' % float(invalue[1])
else : # southern lat
desc+='(%-2.0fS,' % (float(invalue[1]) * -1.0)
if float(invalue[2]) >= 0 : # eastern longitude
desc+='%-2.0fE)' % float(invalue[2]) ## (float(invalue[2]) -180.)
else : # western longitude
desc+='%-2.0fW)' % (float(invalue[2]) * -1.0)
else:
self.logger.info('[%s,%s,%s,%s] seems to be a box' % (invalue[1],invalue[2],invalue[3],invalue[4]))
if float(invalue[1]) > 0 : # northern min latitude
desc+='(%-2.0fN-' % float(invalue[1])
else : # southern min lat
desc+='(%-2.0fS-' % (float(invalue[1]) * -1.0)
if float(invalue[3]) > 0 : # northern max latitude
desc+='%-2.0fN,' % float(invalue[3])
else : # southern max lat
desc+='%-2.0fS,' % (float(invalue[3]) * -1.0)
if float(invalue[2]) >= 0 : # eastern min longitude
desc+='%-2.0fE-' % float(invalue[2])
else : # western min longitude
desc+='%-2.0fW-' % (float(invalue[2]) * -1.0)
if float(invalue[4]) > 0 : # eastern max longitude
desc+='%-2.0fE)' % float(invalue[4])
else : # western max longitude
desc+='%-2.0fW)' % (float(invalue[4]) * -1.0)
self.logger.info('Spatial description %s' % desc)
return (desc,invalue[1],invalue[2],invalue[3],invalue[4])
def map_spatial(self,invalue,geotab):
"""
Map coordinates to spatial
Copyright (C) 2014 Heinrich Widmann
Licensed under AGPLv3.
"""
desc=''
pattern = re.compile(r";|\s+")
try:
self.logger.info(' | Invalue:\t%s' % invalue)
if isinstance(invalue,list) :
if len(invalue) == 1:
valarr=invalue[0].split()
else:
valarr=' '.join(invalue).split()
else:
valarr=invalue.split() ##HEW??? [invalue]
self.logger.info(' | Valarr:\t%s' % valarr)
coordarr=list()
nc=0
for val in valarr:
if type(val) is dict : ## special dict case
coordict=dict()
if "description" in val :
desc=val["description"]
if "boundingBox" in val :
coordict=val["boundingBox"]
retValue = (desc,coordict["minLatitude"],coordict["maxLongitude"],coordict["maxLatitude"],coordict["minLongitude"])
else :
retValue = (desc)
else:
self.logger.debug('value %s' % val)
if self.is_float_try(val) is True :
coordarr.append(val)
nc+=1
self.logger.debug('coordarr %s' % coordarr)
if nc==2 :
retValue = (desc,coordarr[0],coordarr[1],coordarr[0],coordarr[1])
elif nc>=4 :
retValue = (desc,coordarr[0],coordarr[1],coordarr[2],coordarr[3])
elif desc :
retValue = (desc,None,None,None,None)
else :
retValue = (None,None,None,None,None)
if len(coordarr)==2 :
retValue = (desc,coordarr[0],coordarr[1],coordarr[0],coordarr[1])
elif len(coordarr)==4 :
retValue = (desc,coordarr[0],coordarr[1],coordarr[2],coordarr[3])
except Exception as e :
self.logger.error('%s : %s can not converted !' % (e,retValue))
retValue = (None,None,None,None,None)
##print('KKKKKKKKKKKK %s' % (self.check_spatial(retValue,geotab)),)
return self.check_spatial(retValue,geotab)
def map_checksum(self,invalue):
"""
Filter out md checksum from value list
Copyright (C) 2016 Heinrich Widmann
Licensed under AGPLv3.
"""
if type(invalue) is not list :
inlist=re.split(r'[;&\s]\s*',invalue)
inlist.append(invalue)
else:
inlist=invalue
for inval in inlist:
if re.match("[a-fA-F0-9]{32}",inval) : ## checks for MD5 checksums !!!
return inval
return 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"[;&\xe2]",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 :
self.logger.debug('\t\t Next input discipline value %s of type %s' % (indisc,type(indisc)))
if PY2:
indisc=indisc.encode('utf8').replace('\n',' ').replace('\r',' ').strip().title()
else:
indisc=indisc.replace('\n',' ').replace('\r',' ').strip().title()
maxr=0.0
maxdisc=''
for line in disctab :
line=re.split(r'#', line)
try:
if len(line) < 3:
self.logger.critical('Missing base element in dicipline array %s' % line)
sys.exit(-2)
else:
disc=line[2].strip()
r=lvs.ratio(indisc,disc)
except Exception as e :
self.logger.error('%s : %s of type %s can not compared to %s of type %s' % (e,indisc,type(indisc),disc,type(disc)))
continue
if r > maxr :
maxdisc=disc
maxr=r
self.logger.debug('--- %s \n|%s|%s| %f | %f' % (line,indisc,disc,r,maxr))
rethier=line
if maxr == 1 and indisc == maxdisc :
self.logger.info(' | Perfect match of >%s< : nothing to do, DiscHier %s' % (indisc,line))
retval.append(indisc.strip())
elif maxr > 0.90 :
self.logger.info(' | Similarity ratio %f is > 0.90 : replace value >>%s<< with best match --> %s' % (maxr,indisc,maxdisc))
##return maxdisc
retval.append(indisc.strip())
else:
self.logger.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),rethier)
else:
return ('Not stated',list())
def cut(self,invalue,pattern,nfield=None):
"""
Invalue is expected as list (if is not, it is splitted).
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:
logging.debug('elem:%s\tpattern:%s\tnfield:%s' % (elem,pattern,nfield))
try:
if pattern is None :
if nfield :
outvalue.append(elem[nfield])
else:
outvalue.append(elem)
else:
rep=''
cpat=re.compile(pattern)
if nfield == 0 :
rep=re.findall(cpat,elem)[0]
elif len(re.split(cpat,elem)) > nfield-1 :
rep=re.split(cpat,elem)[nfield-1]
logging.debug('rep\t%s' % rep)
if rep :
outvalue.append(rep)
else:
outvalue.append(elem)
except Exception :
logging.error("%s in cut() with invalue %s" % (e,invalue))
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=[]
rm_chars = '@(){}<>;|`\'\"\\#' ## remove chars not allowed in CKAN tags
repl_chars = ':,=/?' ## replace chars not allowed in CKAN tags
# read in list of stopwords
swfile='%s/mapfiles/stopwords.txt' % os.getcwd()
with open(swfile) as sw:
stopwords = sw.read().splitlines()
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 :
self.logger.debug('lentry %s' % lentry)
try:
if type(lentry) is dict :
if "value" in lentry:
valarr.append(lentry["value"])
else:
valarr=lentry.values()
else:
valarr=re.split(r"[\n&,;+]+",lentry)
self.logger.debug('valarr %s' % valarr)
for entry in valarr:
if len(entry.split()) > 8 :
logging.debug('String has too many words : %s' % entry)
continue
entry="". join(c for c in entry if c not in rm_chars and not c.isdigit())
for c in repl_chars :
if c in entry:
entry = entry.replace(c,' ')
entry=entry.strip()
if isinstance(entry,int) or len(entry) < 2 : continue
entrywords = entry.split()
resultwords = [word for word in entrywords if word.lower() not in stopwords]
self.logger.debug("resultwords %s" % resultwords)
if resultwords :
entry=' '.join(resultwords).encode('ascii','ignore').strip()
self.logger.debug("entry %s" % entry)
dictlist.append({ "name": entry })
except (Exception,AttributeError) as err:
self.logger.error('%s in list2dictlist of lentry %s , entry %s' % (err,lentry,entry))
continue
return dictlist[:12]
def uniq(self,input):
## eleminates duplicates and removes words in blacklist from list
blacklist=["Unspecified"]
for string in blacklist :
if string in input : input.remove(string)
uniqset = set(input)
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.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")
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 as err :
logging.error('[ERROR] : %s - in utc2seconds date-time %s can not converted !' % (err,utc))
return None
return sec
def splitstring2dictlist(self,dataset,facetName,valuearrsep,entrysep):
"""
split string in list of string and transfer to list of dict's [ { "name1" : "substr1" }, ... ]
"""
# read in list of stopwords
swfile='%s/stopwords' % os.getcwd()
with open(swfile) as sw:
stopwords = sw.read().splitlines()
na_arr=['not applicable','Unspecified']
for facet in dataset:
if facet == facetName and len(dataset[facet]) == 1 :
valarr=dataset[facet][0]['name'].split(valuearrsep)
valarr=list(OrderedDict.fromkeys(valarr)) ## this elimintas real duplicates
dicttagslist=[]
for entry in valarr:
if entry in na_arr : continue
entrywords = entry.split()
resultwords = [word for word in entrywords if word.lower() not in stopwords]
print ('resultwords %s' % resultwords)
entrydict={ "name": ' '.join(resultwords).replace('/','-') }
dicttagslist.append(entrydict)
dataset[facet]=dicttagslist
return dataset
def changeDateFormat(self,dataset,facetName,old_format,new_format):
"""
changes date format from old format to a new format
current assumption is that the old format is anything (indicated in the
config file by * ) and the new format is UTC
"""
for facet in dataset:
if self.str_equals(facet,facetName) and old_format == '*':
if self.str_equals(new_format,'UTC'):
old_date = dataset[facet]
new_date = date2UTC(old_date)
dataset[facet] = new_date
return dataset
return dataset
def normalize(self,x):
"""normalize the path expression; outside jsonpath to allow testing"""
subx = []
# replace index/filter expressions with placeholders
# Python anonymous functions (lambdas) are cryptic, hard to debug
def f1(m):
n = len(subx) # before append
g1 = m.group(1)
subx.append(g1)
ret = "[#%d]" % n
return ret
x = re.sub(r"[\['](\??\(.*?\))[\]']", f1, x)
# added the negative lookbehind -krhodes
x = re.sub(r"'?(?<!@)\.'?|\['?", ";", x)
x = re.sub(r";;;|;;", ";..;", x)
x = re.sub(r";$|'?\]|'$", "", x)
# put expressions back
def f2(m):
g1 = m.group(1)
return subx[int(g1)]
x = re.sub(r"#([0-9]+)", f2, x)
return x
def jsonpath(self,obj, expr, result_type='VALUE', debug=0, use_eval=True):
"""traverse JSON object using jsonpath expr, returning values or paths"""
def s(x,y):
"""concatenate path elements"""
return str(x) + ';' + str(y)
def isint(x):
"""check if argument represents a decimal integer"""
return x.isdigit()
def as_path(path):
"""convert internal path representation to
"full bracket notation" for PATH output"""
p = '$'
for piece in path.split(';')[1:]:
# make a guess on how to index
# XXX need to apply \ quoting on '!!
if isint(piece):
p += "[%s]" % piece
else:
p += "['%s']" % piece
return p
def store(path, object):
if result_type == 'VALUE':
result.append(object)
elif result_type == 'IPATH': # Index format path (Python ext)
# return list of list of indices -- can be used w/o "eval" or split
result.append(path.split(';')[1:])
else: # PATH
result.append(as_path(path))
return path
def trace(expr, obj, path):
if debug: print ("trace", expr, "/", path)
if expr:
x = expr.split(';')
loc = x[0]
x = ';'.join(x[1:])
if debug: print ("\t", loc, type(obj))
if loc == "*":
def f03(key, loc, expr, obj, path):
if debug > 1: print ("\tf03", key, loc, expr, path)
trace(s(key, expr), obj, path)
walk(loc, x, obj, path, f03)
elif loc == "..":
trace(x, obj, path)
def f04(key, loc, expr, obj, path):
if debug > 1: print ("\tf04", key, loc, expr, path)
if isinstance(obj, dict):
if key in obj:
trace(s('..', expr), obj[key], s(path, key))
else:
if key < len(obj):
trace(s('..', expr), obj[key], s(path, key))
walk(loc, x, obj, path, f04)
elif loc == "!":
# Perl jsonpath extension: return keys
def f06(key, loc, expr, obj, path):
if isinstance(obj, dict):
trace(expr, key, path)
walk(loc, x, obj, path, f06)
elif isinstance(obj, dict) and loc in obj:
trace(x, obj[loc], s(path, loc))
elif isinstance(obj, list) and isint(loc):
iloc = int(loc)
if len(obj) >= iloc:
trace(x, obj[iloc], s(path, loc))
else:
# [(index_expression)]
if loc.startswith("(") and loc.endswith(")"):
if debug > 1: print ("index", loc)
e = evalx(loc, obj)
trace(s(e,x), obj, path)
return
# ?(filter_expression)
if loc.startswith("?(") and loc.endswith(")"):
if debug > 1: print ("filter", loc)
def f05(key, loc, expr, obj, path):
if debug > 1: print ("f05", key, loc, expr, path)
if isinstance(obj, dict):
eval_result = evalx(loc, obj[key])
else:
eval_result = evalx(loc, obj[int(key)])
if eval_result:
trace(s(key, expr), obj, path)
loc = loc[2:-1]
walk(loc, x, obj, path, f05)
return
m = re.match(r'(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$', loc)
if m:
if isinstance(obj, (dict, list)):
def max(x,y):
if x > y:
return x
return y
def min(x,y):
if x < y:
return x
return y
objlen = len(obj)
s0 = m.group(1)
s1 = m.group(2)
s2 = m.group(3)
# XXX int("badstr") raises exception
start = int(s0) if s0 else 0
end = int(s1) if s1 else objlen
step = int(s2) if s2 else 1
if start < 0:
start = max(0, start+objlen)
else:
start = min(objlen, start)
if end < 0:
end = max(0, end+objlen)
else:
end = min(objlen, end)
for i in xrange(start, end, step):
trace(s(i, x), obj, path)
return
# after (expr) & ?(expr)
if loc.find(",") >= 0:
# [index,index....]
for piece in re.split(r"'?,'?", loc):
if debug > 1: print ("piece", piece)
trace(s(piece, x), obj, path)
else:
store(path, obj)
def walk(loc, expr, obj, path, funct):
if isinstance(obj, list):
for i in xrange(0, len(obj)):
funct(i, loc, expr, obj, path)
elif isinstance(obj, dict):
for key in obj:
funct(key, loc, expr, obj, path)
def evalx(loc, obj):
"""eval expression"""
if debug: print ("evalx", loc)
# a nod to JavaScript. doesn't work for @.name.name.length
# Write len(@.name.name) instead!!!
loc = loc.replace("@.length", "len(__obj)")
loc = loc.replace("&&", " and ").replace("||", " or ")
# replace [email protected] with 'name' not in obj
# XXX handle [email protected]....
def notvar(m):
return "'%s' not in __obj" % m.group(1)
loc = re.sub("!@\.([a-zA-Z@_]+)", notvar, loc)
# replace @.name.... with __obj['name']....
# handle @.name[.name...].length
def varmatch(m):
def brackets(elts):
ret = "__obj"