forked from open-data/harvester-FGP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhnap2cc-json.py
executable file
·2838 lines (2524 loc) · 197 KB
/
hnap2cc-json.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 python
# -*- coding: utf-8 -*-
"""Usage: hnap2cc-json.py [-e Error file to generate]
Convert HNAP 2.3.1 XML from FGP platform CSW v1.6.2 to OGP Portal input
Accepts streamed HNAP xml input or a supplied HNAP xml filename
cat hnap.xml | hnap2cc-json.py [-e Error file to generate]
hnap2cc-json.py [-e Error file to generate] hnap.xml
Options:
-e Error file to generate
"""
from ResourceType import ResourceType
from CL_Formats import CL_Formats
import csv
from lxml import etree
import json
import datetime
import urllib2
from urlparse import urlparse
import sys
from io import StringIO, BytesIO
import time
import re
import codecs
import unicodedata
import docopt
MIN_TAG_LENGTH = 2
MAX_TAG_LENGTH = 140
##################################################
# TL err/dbg
error_output = []
error_records = {}
##################################################
# Process the command request
# #Default import location
# input_file = 'data/majechr_source.xml'
# input_file = 'data/hnap_import.xml'
input_file = None
# Use stdin if it's populated
if not sys.stdin.isatty():
input_file = BytesIO(sys.stdin.read())
# Otherwise, read for a given filename
if len(sys.argv) == 2:
input_file = sys.argv[1]
if input_file is None:
sys.stdout.write("""
Either stream HNAP in or supply a file
> cat hnap.xml | ./hnap2json.py
> ./hnap2json.py hnap.xml
""")
sys.exit()
##################################################
# Input can be multiple XML blocks
# Ensure to never try to be clever only taking the
# last XML record or reduce or sort or try to
# combine them. Each of these updates need to
# happen in the order they were supplied to ensure
# the order of changes.
# We can also not reprocess parts without all the
# subsequent records. You can't re-process data
# from a particular span of time, any historical
# re-procssing must continue to the current day.
input_data_blocks = []
active_input_block = ''
for line in input_file:
if not line.strip():
continue
if active_input_block == '':
active_input_block += line
elif re.search(r'^<\?xml', line):
input_data_blocks.append(active_input_block)
active_input_block = line
else:
active_input_block += line
input_data_blocks.append(active_input_block)
##################################################
# Extract the schema to convert to
schema_file = 'config/Schema--GC.OGS.TBS-CommonCore-OpenMaps.csv'
schema_ref = {}
with open(schema_file, 'rb') as f:
reader = csv.reader(f)
for row in reader:
if row[0] == 'Property ID':
continue
schema_ref[row[0]] = {}
schema_ref[row[0]]['Property ID'] = row[0]
schema_ref[row[0]]['CKAN API property'] = row[1]
schema_ref[row[0]]['Schema Name English'] = unicode(row[2], 'utf-8')
schema_ref[row[0]]['Schema Name French'] = unicode(row[3], 'utf-8')
schema_ref[row[0]]['Requirement'] = row[4]
schema_ref[row[0]]['Occurrences'] = row[5]
schema_ref[row[0]]['Reference'] = row[6]
schema_ref[row[0]]['Value Type'] = row[7]
schema_ref[row[0]]['FGP XPATH'] = unicode(row[8], 'utf-8')
schema_ref[row[0]]['RegEx Filter'] = unicode(row[9], 'utf-8')
records_root = ("/csw:GetRecordsResponse/"
"csw:SearchResults/"
"gmd:MD_Metadata")
source_hnap = ("csw.open.canada.ca/geonetwork/srv/"
"csw?service=CSW"
"&version=2.0.2"
"&request=GetRecordById"
"&outputSchema=csw:IsoRecord"
"&id=")
mappable_protocols = [
"OGC:WMS",
"ESRI REST: Map Service",
"ESRI REST: Map Server",
"ESRI REST: Feature Service",
"ESRI REST: Image Service",
"ESRI REST: Tiled Map Service",
"WMS de l'OGC",
"REST de L'ESRI : Service de cartes",
"REST de L'ESRI : Service d’entités géographiques",
"REST de L'ESRI : Service d’imagerie",
"REST de L'ESRI : Service de pavés cartographiques"
]
iso_time = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
def main():
output_jl = "harvested_records.jl"
output_err = "harvested_record_errors.csv"
num_rejects = 0
num_view_on_map = 0
# Is there a specified start date
if arguments['-e']:
output_err = arguments['-e']
json_records = []
for input_block in input_data_blocks:
if not input_block:
continue
# Read the file, should be a streamed input in the future
root = etree.XML(input_block)
# Parse the root and iterate over each record
records = fetchXMLArray(root, records_root)
for record in records:
json_record = {}
can_be_used_in_RAMP = False
json_record['display_flags'] = []
##################################################
# HNAP CORE LANGUAGE
##################################################
# Language is required, the rest can't be processed
# for errors if the primary language is not certain
tmp = fetchXMLValues(record, schema_ref["12"]['FGP XPATH'])
if sanitySingle('NOID', ['HNAP Priamry Language'], tmp) is False:
HNAP_primary_language = False
else:
HNAP_primary_language = sanityFirst(tmp).split(';')[0].strip()
if HNAP_primary_language == 'eng':
CKAN_primary_lang = 'en'
CKAN_secondary_lang = 'fr'
HNAP_primary_lang = 'English'
HNAP_secondary_lang = 'French'
else:
CKAN_primary_lang = 'fr'
CKAN_secondary_lang = 'en'
HNAP_primary_lang = 'French'
HNAP_secondary_lang = 'English'
##################################################
# Catalogue Metadata
##################################################
# CC::OpenMaps-01 Catalogue Type
json_record[schema_ref["01"]['CKAN API property']] = 'dataset'
# CC::OpenMaps-02 Collection Type
json_record[schema_ref["02"]['CKAN API property']] = 'fgp'
# CC::OpenMaps-03 Metadata Scheme
# CKAN defined/provided
# CC::OpenMaps-04 Metadata Scheme Version
# CKAN defined/provided
# CC::OpenMaps-05 Metadata Record Identifier
tmp = fetchXMLValues(record, schema_ref["05"]['FGP XPATH'])
if sanitySingle('NOID', ['fileIdentifier'], tmp) is False:
HNAP_fileIdentifier = False
else:
json_record[schema_ref["05"]['CKAN API property']] =\
HNAP_fileIdentifier =\
sanityFirst(tmp)
##################################################
# Point of no return
# fail out if you don't have either a primary language or ID
##################################################
if HNAP_primary_language is False or HNAP_fileIdentifier is False:
break
# From here on in continue if you can and collect as many errors as
# possible for FGP Help desk. We awant to have a full report of issues
# to correct, not piecemeal errors.
# It's faster for them to correct a batch of errors in parallel as
# opposed to doing them piecemeal.
# CC::OpenMaps-06 Metadata Contact (English)
primary_vals = []
# organizationName
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["06a"])
if value:
for single_value in value:
primary_vals.append(single_value)
# voice
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["06b"])
if value:
for single_value in value:
primary_vals.append(single_value)
# electronicMailAddress
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["06c"])
if value:
for single_value in value:
primary_vals.append(single_value)
json_record[schema_ref["06"]['CKAN API property']] = {}
json_record[
schema_ref["06"]['CKAN API property']
][CKAN_primary_lang] = ','.join(primary_vals)
# CC::OpenMaps-07 Metadata Contact (French)
second_vals = []
# organizationName
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["07a"])
if value:
for single_value in value:
second_vals.append(single_value)
# voice
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["07b"])
if value:
for single_value in value:
primary_vals.append(single_value)
# electronicMailAddress
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["07c"])
if value:
for single_value in value:
second_vals.append(single_value)
json_record[
schema_ref["06"]['CKAN API property']
][CKAN_secondary_lang] = ','.join(second_vals)
# CC::OpenMaps-08 Source Metadata Record Date Stamp
tmp = fetchXMLValues(record, schema_ref["08a"]['FGP XPATH'])
values = list(set(tmp))
if len(values) < 1:
tmp = fetchXMLValues(record, schema_ref["08b"]['FGP XPATH'])
if sanityMandatory(
HNAP_fileIdentifier,
[schema_ref["08"]['CKAN API property']],
tmp
):
if sanitySingle(
HNAP_fileIdentifier,
[schema_ref["08"]['CKAN API property']],
tmp
):
# Might be a iso datetime
date_str = sanityFirst(tmp)
if date_str.count('T') == 1:
date_str = date_str.split('T')[0]
if sanityDate(
HNAP_fileIdentifier,
[schema_ref["08"]['CKAN API property']],
date_str):
json_record[schema_ref["08"]['CKAN API property']] =\
date_str
# CC::OpenMaps-09 Metadata Contact (French)
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["09"])
if value:
json_record[schema_ref["09"]['CKAN API property']] = value
# CC::OpenMaps-10 Parent identifier
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["10"])
if value:
json_record[schema_ref["10"]['CKAN API property']] = value
# CC::OpenMaps-11 Hierarchy level
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["11"])
if value:
json_record[schema_ref["11"]['CKAN API property']] = value
# CC::OpenMaps-12 File Identifier
json_record[schema_ref["12"]['CKAN API property']] =\
HNAP_fileIdentifier
# CC::OpenMaps-13 Short Key
# Disabled as per the current install of RAMP
# json_record[schema_ref["13"]
# ['CKAN API property']] = HNAP_fileIdentifier[0:8]
# CC::OpenMaps-14 Title (English)
json_record[schema_ref["14"]['CKAN API property']] = {}
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["14"])
if value:
json_record[
schema_ref["14"]['CKAN API property']
][CKAN_primary_lang] = value
# CC::OpenMaps-15 Title (French)
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["15"])
if value:
json_record[
schema_ref["14"]['CKAN API property']
][CKAN_secondary_lang] = value
# CC::OpenMaps-16 Publisher - Current Organization Name
org_strings = []
org_string = ''
attempt = ''
if HNAP_primary_lang == 'English':
primary_lang_search_string = "^Government of Canada;"
secondary_lang_search_string = "^Government du Canada;"
else:
primary_lang_search_string = "^Government du Canada;"
secondary_lang_search_string = "^Government of Canada;"
value = fetch_FGP_value(
record, HNAP_fileIdentifier, schema_ref["16a"])
if not value or len(value) < 1:
attempt += "No primary language value"
else:
attempt += "Has primary language value ["+str(len(value))+"]"
for single_value in value:
if re.search(primary_lang_search_string, single_value):
org_strings.append(single_value)
else:
attempt += " but no GoC/GdC prefix ["+single_value+"]"
value = fetch_FGP_value(
record, HNAP_fileIdentifier, schema_ref["16b"])
if not value or len(value) < 1:
attempt += ", no secondary language value"
else:
attempt += ", secondary language ["+str(len(value))+"]"
for single_value in value:
if re.search(secondary_lang_search_string, single_value):
org_strings.append(single_value)
else:
attempt += " but no GoC/GdC ["+single_value+"]"
if len(org_strings) < 1:
reportError(
HNAP_fileIdentifier, [
schema_ref["16"]['CKAN API property'],
"Bad organizationName, no Government of Canada",
attempt
])
else:
valid_orgs = []
for org_string in org_strings:
GOC_Structure = org_string.strip().split(';')
del GOC_Structure[0]
# Append to contributor
contributor_english = []
contributor_french = []
# At ths point you have ditched GOC and your checking for good
# dept names
for GOC_Div in GOC_Structure:
# Are they in the CL?
termsValue = fetchCLValue(
GOC_Div, GC_Registry_of_Applied_Terms)
if termsValue:
contributor_english.append(termsValue[0])
contributor_french.append(termsValue[2])
if termsValue[1] == termsValue[3]:
valid_orgs.append(termsValue[1].lower())
else:
valid_orgs.append((termsValue[1]+"-"+termsValue[3]).lower())
break
# Unique the departments, don't need duplicates
valid_orgs = list(set(valid_orgs))
if len(valid_orgs) < 1:
reportError(
HNAP_fileIdentifier, [
schema_ref["16"]['CKAN API property'],
"No valid orgs found",
org_string.strip()
])
else:
json_record[schema_ref["16"]['CKAN API property']] = valid_orgs[0]
# Unique the departments, don't need duplicates
contributor_english = list(set(contributor_english))
contributor_french = list(set(contributor_french))
# Multiple owners, excess pushed to contrib
if len(valid_orgs) > 1:
del valid_orgs[0]
del contributor_english[0]
del contributor_french[0]
json_record[schema_ref["22"]['CKAN API property']] = {}
json_record[schema_ref["22"]['CKAN API property']]['en'] = []
json_record[schema_ref["22"]['CKAN API property']]['fr'] = []
for org in valid_orgs:
json_record[schema_ref["22"]['CKAN API property']]['en'] = ','.join(contributor_english)
json_record[schema_ref["22"]['CKAN API property']]['fr'] = ','.join(contributor_french)
# CC::OpenMaps-17 Publisher - Organization Name at Publication (English)
# CKAN defined/provided
# CC::OpenMaps-18 Publisher - Organization Name at Publication (French)
# CKAN defined/provided
# CC::OpenMaps-19 Publisher - Organization Section Name (English)
# CKAN defined/provided
# CC::OpenMaps-20 Publisher - Organization Section Name (French)
# CKAN defined/provided
# CC::OpenMaps-21 Creator
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["21"])
if value:
json_record[schema_ref["21"]['CKAN API property']] = ','.join(value)
# CC::OpenMaps-22 Contributor (English)
# Intentionally left blank, assuming singular contribution
# CC::OpenMaps-23 Contributor (French)
# Intentionally left blank, assuming singular contribution
# CC::OpenMaps-24 Position Name (English)
# CC::OpenMaps-25 Position Name (French)
json_record[schema_ref["24"]['CKAN API property']] = {}
schema_ref["24"]['Occurrences'] = 'R'
primary_data = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["24"])
if value:
for single_value in value:
primary_data.append(value)
if len(primary_data) > 0:
json_record[schema_ref["24"]['CKAN API property']][CKAN_primary_lang] = ','.join(value)
schema_ref["25"]['Occurrences'] = 'R'
primary_data = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["25"])
if value:
for single_value in value:
primary_data.append(value)
if len(primary_data) > 0:
json_record[schema_ref["24"]['CKAN API property']][CKAN_secondary_lang] = ','.join(value)
if len(json_record[schema_ref["24"]['CKAN API property']]) < 1:
del json_record[schema_ref["24"]['CKAN API property']]
# CC::OpenMaps-26 Role
# Single report out, multiple records combined
schema_ref["26"]['Occurrences'] = 'R'
primary_data = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["26"])
if value:
for single_value in value:
# Can you find the CL entry?
termsValue = fetchCLValue(single_value, napCI_RoleCode)
if not termsValue:
reportError(
HNAP_fileIdentifier, [
schema_ref["26"]['CKAN API property'],
'Value not found in '+schema_ref["26"]['Reference']
])
else:
primary_data.append(termsValue[0])
if len(primary_data) > 0:
json_record[schema_ref["26"]['CKAN API property']] = ','.join(value)
# CC::OpenMaps-27
# Undefined property number
# CC::OpenMaps-28
# Undefined property number
# CC::OpenMaps-29 Contact Information (English)
primary_vals = {}
primary_vals[CKAN_primary_lang] = {}
# HACK - find out of there is a pointOfContact role provided
ref = schema_ref["29a"]["FGP XPATH"].split("gmd:CI_ResponsibleParty")[0] + "gmd:CI_ResponsibleParty[gmd:role/gmd:CI_RoleCode[@codeListValue='RI_414']]"
tmp = fetchXMLValues(record, ref)
xpath_sub = ""
if len(tmp) > 0:
xpath_sub = "gmd:CI_ResponsibleParty[gmd:role/gmd:CI_RoleCode[@codeListValue='RI_414']]"
# deliveryPoint
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["29a"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["29a"]['Requirement'], "Occurrences": schema_ref["29a"]['Occurrences'],"FGP XPATH": schema_ref["29a"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["29a"]['Value Type'], "CKAN API property": schema_ref["29a"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_primary_lang]['delivery_point'] = single_value
# city
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["29b"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["29b"]['Requirement'], "Occurrences": schema_ref["29b"]['Occurrences'],"FGP XPATH": schema_ref["29b"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["29b"]['Value Type'], "CKAN API property": schema_ref["29b"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_primary_lang]['city'] = single_value
# administrativeArea
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["29c"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["29c"]['Requirement'], "Occurrences": schema_ref["29c"]['Occurrences'],"FGP XPATH": schema_ref["29c"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["29c"]['Value Type'], "CKAN API property": schema_ref["29c"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_primary_lang]['administrative_area'] = single_value
# postalCode
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["29d"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["29d"]['Requirement'], "Occurrences": schema_ref["29d"]['Occurrences'],"FGP XPATH": schema_ref["29d"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["29d"]['Value Type'], "CKAN API property": schema_ref["29d"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_primary_lang]['postal_code'] = single_value
# country
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["29e"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["29e"]['Requirement'], "Occurrences": schema_ref["29e"]['Occurrences'],"FGP XPATH": schema_ref["29e"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["29e"]['Value Type'], "CKAN API property": schema_ref["29e"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_primary_lang]['country'] = single_value
# electronicMailAddress
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["29f"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["29f"]['Requirement'], "Occurrences": schema_ref["29f"]['Occurrences'],"FGP XPATH": schema_ref["29f"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["29f"]['Value Type'], "CKAN API property": schema_ref["29f"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_primary_lang]['electronic_mail_address'] = single_value
if len(primary_vals[CKAN_primary_lang]) < 1:
reportError(
HNAP_fileIdentifier, [
schema_ref["29"]['CKAN API property'],
'Value not found in '+schema_ref["29"]['Reference']
])
# CC::OpenMaps-30 Contact Information (French)
primary_vals[CKAN_secondary_lang] = {}
# deliveryPoint
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["30a"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["30a"]['Requirement'], "Occurrences": schema_ref["30a"]['Occurrences'],"FGP XPATH": schema_ref["30a"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["30a"]['Value Type'], "CKAN API property": schema_ref["30a"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_secondary_lang]['delivery_point'] = single_value
# city
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["30b"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["30b"]['Requirement'], "Occurrences": schema_ref["30b"]['Occurrences'],"FGP XPATH": schema_ref["30b"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["30b"]['Value Type'], "CKAN API property": schema_ref["30b"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_secondary_lang]['city'] = single_value
# administrativeArea
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["30c"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["30c"]['Requirement'], "Occurrences": schema_ref["30c"]['Occurrences'],"FGP XPATH": schema_ref["30c"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["30c"]['Value Type'], "CKAN API property": schema_ref["30c"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_secondary_lang]['administrative_area'] = single_value
# postalCode
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["30d"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["30d"]['Requirement'], "Occurrences": schema_ref["30d"]['Occurrences'],"FGP XPATH": schema_ref["30d"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["30d"]['Value Type'], "CKAN API property": schema_ref["30d"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_secondary_lang]['postal_code'] = single_value
# country
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["30e"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["30e"]['Requirement'], "Occurrences": schema_ref["30e"]['Occurrences'],"FGP XPATH": schema_ref["30e"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["30e"]['Value Type'], "CKAN API property": schema_ref["30e"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_secondary_lang]['country'] = single_value
# electronicMailAddress
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["30f"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["30f"]['Requirement'], "Occurrences": schema_ref["30f"]['Occurrences'],"FGP XPATH": schema_ref["30f"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["30f"]['Value Type'], "CKAN API property": schema_ref["30f"]['CKAN API property']})
if value:
for single_value in value:
primary_vals[CKAN_secondary_lang]['electronic_mail_address'] = single_value
if len(primary_vals[CKAN_secondary_lang]) < 1:
reportError(
HNAP_fileIdentifier,[
schema_ref["30"]['CKAN API property'],
'Value not found in '+schema_ref["30"]['Reference']
])
json_record[schema_ref["29"]['CKAN API property']] = json.dumps(primary_vals)
# CC::OpenMaps-31 Contact Email
# Single report out, multiple records combined
schema_ref["31"]['Occurrences'] = 'R'
json_record[schema_ref["31"]['CKAN API property']] = {}
# HACK - find out of there is a pointOfContact role provided
ref = schema_ref["31"]["FGP XPATH"].split("gmd:CI_ResponsibleParty")[0] + "gmd:CI_ResponsibleParty[gmd:role/gmd:CI_RoleCode[@codeListValue='RI_414']]"
tmp = fetchXMLValues(record, ref)
xpath_sub = ""
if len(tmp) > 0:
xpath_sub = "gmd:CI_ResponsibleParty[gmd:role/gmd:CI_RoleCode[@codeListValue='RI_414']]"
# value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["31"])
value = fetch_FGP_value(record, HNAP_fileIdentifier, {"Requirement": schema_ref["31"]['Requirement'], "Occurrences": schema_ref["31"]['Occurrences'],"FGP XPATH": schema_ref["31"]["FGP XPATH"].replace("gmd:CI_ResponsibleParty", xpath_sub), "Value Type": schema_ref["31"]['Value Type'], "CKAN API property": schema_ref["31"]['CKAN API property']})
# primary_data = []
# if value:
# for single_value in value:
# primary_data.append(single_value)
# if len(primary_data) > 0:
# json_record[schema_ref["31"]['CKAN API property']] = ','.join(value)
# Check for valid email
if value:
isValidEmail = re.match(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', value[0])
if not isValidEmail or isValidEmail == None:
reportError(
HNAP_fileIdentifier, [
schema_ref["31"]['CKAN API property'],
"Invalid Email",
value[0]
])
else:
json_record[schema_ref["31"]['CKAN API property']] = value[0]
else:
reportError(
HNAP_fileIdentifier, [
schema_ref["31"]['CKAN API property'],
"Invalid Email",
''
])
# CC::OpenMaps-32 Description (English)
json_record[schema_ref["32"]['CKAN API property']] = {}
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["32"])
if value:
# format line breaks
value = value.replace('\n', ' \n \n ')
json_record[
schema_ref["32"]['CKAN API property']
][CKAN_primary_lang] = value
# XXX Check that there are values
# CC::OpenMaps-33 Description (French)
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["33"])
if value:
# format line breaks
value = value.replace('\n', ' \n \n ')
json_record[
schema_ref["32"]['CKAN API property']
][CKAN_secondary_lang] = value
# XXX Check that there are values
# CC::OpenMaps-34 Keywords (English)
primary_vals = []
json_record[schema_ref["34"]['CKAN API property']] = {}
json_record[schema_ref["34"]['CKAN API property']][CKAN_primary_lang] = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["34"])
if value:
for single_value in value:
p = re.compile('^[A-Z][A-Z] [^>]+ > ')
single_value = p.sub('', single_value)
single_value = single_value.strip()
# ADAPTATION #4
# 2016-05-27 - call
# Alexandre Bolieux asked I replace commas with something valid. I'm replacing them with semi-colons
# which can act as a seperator character like the comma but get past that reserved character
single_value = single_value.replace(',', ';')
# END ADAPTATION
# remove multiple spaces
single_value = re.sub(r'\s+', ' ', single_value)
keyword_error = canada_tags(single_value).replace('"', '""')
# ADAPTATION #5
# 2016-05-27 - call
# Alexandre Bolieux asked if I could replace commas with something valid. I'm
# replacing them with semi-colons which can act as a seperator character like
# the comma but get past that reserved character
if re.search('length is more than maximum 140', keyword_error, re.UNICODE):
pass
else:
# END ADAPTATION
if not keyword_error == '':
#if not re.search(schema_ref["34"]['RegEx Filter'], single_value,re.UNICODE):
reportError(
HNAP_fileIdentifier, [
schema_ref["34"]['CKAN API property']+'-'+CKAN_primary_lang,
"Invalid Keyword",
keyword_error
#"Must be alpha-numeric, space or '-_./>+& ["+single_value+']'
])
else:
if single_value not in json_record[schema_ref["34"]['CKAN API property']][CKAN_primary_lang]:
json_record[schema_ref["34"]['CKAN API property']][CKAN_primary_lang].append(single_value)
# if not len(json_record[schema_ref["34"]['CKAN API property']][CKAN_primary_lang]):
# reportError(
# HNAP_fileIdentifier,[
# schema_ref["34"]['CKAN API property']+'-'+CKAN_primary_lang,
# "No keywords"
# ])
# CC::OpenMaps-35 Keywords (French)
json_record[schema_ref["34"]['CKAN API property']][CKAN_secondary_lang] = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["35"])
if value:
for single_value in value:
p = re.compile('^[A-Z][A-Z] [^>]+ > ')
single_value = p.sub('', single_value)
# ADAPTATION #4
# 2016-05-27 - call
# Alexandre Bolieux asked if I could replace commas with something valid. I'm
# replacing them with semi-colons which can act as a seperator character like
# the comma but get past that reserved character
single_value = single_value.replace(',', ';')
# END ADAPTATION
single_value = re.sub(r'\s+', ' ', single_value)
keyword_error = canada_tags(single_value).replace('"', '""')
# ADAPTATION #5
# 2016-05-27 - call
# Alexandre Bolieux asked I drop keywords that exceed 140 characters
if re.search('length is more than maximum 140', keyword_error, re.UNICODE):
pass
else:
# END ADAPTATION
if not keyword_error == '':
#if not re.search(schema_ref["34"]['RegEx Filter'], single_value,re.UNICODE):
reportError(
HNAP_fileIdentifier, [
schema_ref["34"]['CKAN API property']+'-'+CKAN_secondary_lang,
"Invalid Keyword",
keyword_error
#'Must be alpha-numeric, space or -_./>+& ['+single_value+']'
])
else:
if single_value not in json_record[schema_ref["34"]['CKAN API property']][CKAN_secondary_lang]:
json_record[schema_ref["34"]['CKAN API property']][CKAN_secondary_lang].append(single_value)
# if not len(json_record[schema_ref["34"]['CKAN API property']][CKAN_secondary_lang]):
# reportError(
# HNAP_fileIdentifier,[
# schema_ref["34"]['CKAN API property']+'-'+CKAN_secondary_lang,
# "No keywords"
# ])
# CC::OpenMaps-36 Subject
subject_values = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["36"])
if value:
for subject in value:
termsValue = fetchCLValue(
subject.strip(), CL_Subjects)
if termsValue:
for single_item in termsValue[3].split(','):
subject_values.append(single_item.strip().lower())
if len(subject_values) < 1:
reportError(
HNAP_fileIdentifier,[
schema_ref["36"]['CKAN API property'],
'Value not found in '+schema_ref["36"]['Reference']
])
else:
json_record[schema_ref["36"]['CKAN API property']] = list(set(subject_values))
# CC::OpenMaps-37 Topic Category
topicCategory_values = []
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["37"])
if value:
for topicCategory in value:
termsValue = fetchCLValue(
topicCategory.strip(), napMD_KeywordTypeCode)
if termsValue:
topicCategory_values.append(termsValue[0])
if len(topicCategory_values) < 1:
reportError(
HNAP_fileIdentifier,[
schema_ref["37"]['CKAN API property'],
'Value not found in '+schema_ref["37"]['Reference']
])
else:
json_record[schema_ref["37"]['CKAN API property']] = topicCategory_values
# CC::OpenMaps-38 Audience
# TBS 2016-04-13: Not in HNAP, we can skip
# CC::OpenMaps-39 Place of Publication (English)
# TBS 2016-04-13: Not in HNAP, we can skip
# CC::OpenMaps-40 Place of Publication (French)
# TBS 2016-04-13: Not in HNAP, we can skip
# CC::OpenMaps-41 Spatial
north = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["41n"])
if north:
south = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["41s"])
if south:
east = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["41e"])
if east:
west = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["41w"])
if west:
# ensure we have proper numbers
north = [float(north[0]) if '.' in north[0] else int(north[0])]
east = [float(east[0]) if '.' in east[0] else int(east[0])]
south = [float(south[0]) if '.' in south[0] else int(south[0])]
west = [float(west[0]) if '.' in west[0] else int(west[0])]
GeoJSON = {}
GeoJSON['type'] = "Polygon"
GeoJSON['coordinates'] = [[
[west, south],
[east, south],
[east, north],
[west, north],
[west, south]
]]
#json_record[schema_ref["41"]['CKAN API property']] = json.dumps(GeoJSON)
json_record[schema_ref["41"]['CKAN API property']] = '{"type": "Polygon","coordinates": [[[%s,%s],[%s,%s],[%s,%s],[%s,%s],[%s,%s]]]}' % (west[0],south[0],east[0],south[0],east[0],north[0],west[0],north[0],west[0],south[0])
# CC::OpenMaps-42 Geographic Region Name
# TBS 2016-04-13: Not in HNAP, we can skip (the only providing the bounding box, not the region name)
# CC::OpenMaps-43 Time Period Coverage Start Date
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["43"])
if value:
if sanityDate(
HNAP_fileIdentifier,[
schema_ref["43"]['CKAN API property']+'-start'
],
maskDate(value)
):
json_record[schema_ref["43"]['CKAN API property']] = maskDate(value)
# CC::OpenMaps-44 Time Period Coverage End Date
# ADAPTATION #2
# CKAN (or Solr) requires an end date where one doesn't exist. An open
# record should run without an end date. Since this is not the case a
# '9999-99-99' is used in lieu.
# ADAPTATION #3
# Temporal elements are ISO 8601 date objects but this field may be
# left blank (invalid).
# The intent is to use a blank field as a maker for an "open" record
# were omission of this field would be standard practice. No
# gml:endPosition = no end.
# Since changing the source seems to be impossible we adapt by
# replacing a blank entry with the equally ugly '9999-99-99' forced
# end in CKAN.
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["44"])
if value:
check_for_blank = value
if check_for_blank == '':
check_for_blank = '9999-09-09'
if sanityDate(
HNAP_fileIdentifier,[
schema_ref["44"]['CKAN API property']+'-end'
],
maskDate(check_for_blank)
):
json_record[schema_ref["44"]['CKAN API property']] = maskDate(check_for_blank)
# CC::OpenMaps-45 Maintenance and Update Frequency
value = fetch_FGP_value(record, HNAP_fileIdentifier, schema_ref["45"])
if value:
# Can you find the CL entry?
termsValue = fetchCLValue(value, napMD_MaintenanceFrequencyCode)
if not termsValue:
reportError(
HNAP_fileIdentifier,[
schema_ref["45"]['CKAN API property'],
'Value not found in '+schema_ref["45"]['Reference']
])
else:
json_record[schema_ref["45"]['CKAN API property']] = termsValue[2]
# CC::OpenMaps-46 Date Published
# CC::OpenMaps-47 Date Modified
##################################################
# These are a little different, we have to do these odd birds manually
r = record.xpath(
schema_ref["46"]["FGP XPATH"],
namespaces={
'gmd': 'http://www.isotc211.org/2005/gmd',
'gco': 'http://www.isotc211.org/2005/gco'})
if(len(r)):
for cn in r:
input_types = {}
inKey = []
inVal = ''
# Decypher which side has the code and which has the data,
# yea... it changes -sigh-
# Keys will always use the ;
try:
if cn[0][0].text is not None and len(cn[0][0].text.split(';')) > 1:
inKey = cn[0][0].text.split(';')
inVal = cn[1][0].text.strip()
elif cn[1][0].text is not None:
inKey = cn[1][0].text.split(';')
inVal = cn[0][0].text.strip()
except:
pass
for input_type in inKey:
input_type = input_type.strip()
if input_type == u'publication':
if sanityDate(
HNAP_fileIdentifier,[
schema_ref["46"]['CKAN API property']
],
maskDate(inVal)):
json_record[schema_ref["46"]['CKAN API property']] = maskDate(inVal)
break
if input_type == u'revision' or input_type == u'révision':
if sanityDate(
HNAP_fileIdentifier,[
schema_ref["47"]['CKAN API property']
],
maskDate(inVal)):
json_record[schema_ref["47"]['CKAN API property']] = maskDate(inVal)
break
# Check the field is populated if you have to
if schema_ref["46"]['Requirement'] == 'M' and schema_ref["46"]['CKAN API property'] not in json_record:
reportError(