Debian Codegraph @

stetl/filters/formatconverter.py

raw
1 #!/usr/bin/env python
2 #
3 # Converts Stetl Packet FORMATs. This can be used to connect
4 # Stetl components with different output/input formats.
5 #
6 # Author:Just van den Broecke
7
8 import json
9 from stetl.component import Config
10 from stetl.util import Util, etree
11 from stetl.filter import Filter
12 from stetl.packet import FORMAT
13
14 log = Util.get_log("formatconverter")
15
16
17 class FormatConverter(Filter):
18 """
19 Converts (almost) any packet format (if converter available).
20
21 consumes=FORMAT.any, produces=FORMAT.any but actual formats
22 are changed at initialization based on the input to output format to
23 be converted via the input_format and output_format config parameters.
24 """
25
26 # Start attribute config meta
27 # Applying Decorator pattern with the Config class to provide
28 # read-only config values from the configured properties.
29
30 @Config(ptype=dict, default=None, required=False)
31 def converter_args(self):
32 """
33 Custom converter-specific arguments.
34 """
35 pass
36
37 # End attribute config meta
38
39 # Constructor
40 def __init__(self, configdict, section):
41 Filter.__init__(self, configdict, section, consumes=FORMAT.any, produces=FORMAT.any)
42 self.converter = None
43
44 def init(self):
45 if self.output_format == FORMAT.any:
46 # Any as output is always valid, do nothing
47 self.converter = FormatConverter.no_op
48 return
49
50 # generate runtime error as we may have registered converters at init time...
51 if self.input_format not in FORMAT_CONVERTERS.keys():
52 raise NotImplementedError('No format converters found for input format %s' % self.input_format)
53
54 # ASSERTION: converters present for input_format
55
56 if self.output_format not in FORMAT_CONVERTERS[self.input_format].keys():
57 raise NotImplementedError('No format converters found for input format %s to output format %s' % (
58 self.input_format, self.output_format))
59
60 # ASSERTION: converters present for input_format and output_format
61
62 # Lookup and assign the active converter
63 self.converter = FORMAT_CONVERTERS[self.input_format][self.output_format]
64
65 # OGR feature def
66 self.feat_def = None
67
68 def invoke(self, packet):
69
70 if packet.data is None:
71 packet.format = self.output_format
72 return packet
73
74 if self.converter_args is not None:
75 self.converter(packet, self.converter_args)
76 else:
77 self.converter(packet)
78
79 packet.format = self.output_format
80 return packet
81
82 @staticmethod
83 def add_converter(input_format, output_format, converter_fun):
84 # Add to existing input format converters or create new
85 if input_format not in FORMAT_CONVERTERS.keys():
86 FORMAT_CONVERTERS[input_format] = {output_format: converter_fun}
87 else:
88 FORMAT_CONVERTERS[input_format][output_format] = converter_fun
89
90 @staticmethod
91 def no_op(packet):
92 return packet
93
94 # START etree_doc
95 @staticmethod
96 def etree_doc2geojson_collection(packet, converter_args=None):
97 """
98 Use converter_args to determine XML tag names for features and GeoJSON feature id.
99 For example
100
101 converter_args = {
102 'root_tag': 'FeatureCollection',
103 'feature_tag': 'featureMember',
104 'feature_id_attr': 'fid'
105 }
106
107 :param packet:
108 :param converter_args:
109 :return:
110 """
111 packet.data = packet.data.getroot()
112 packet = FormatConverter.etree_elem2struct(packet)
113 feature_coll = {'type': 'FeatureCollection', 'features': []}
114
115 root_tag = 'FeatureCollection'
116 feature_tag = 'featureMember'
117 if converter_args:
118 root_tag = converter_args['root_tag']
119 feature_tag = converter_args['feature_tag']
120
121 features = packet.data[root_tag][feature_tag]
122 for feature in features:
123 packet.data = feature
124 packet = FormatConverter.struct2geojson_feature(packet, converter_args)
125 feature_coll['features'].append(packet.data)
126
127 packet.data = feature_coll
128 return packet
129
130 @staticmethod
131 def etree_doc2string(packet):
132 packet.data = etree.tostring(packet.data, pretty_print=True, xml_declaration=True)
133 return packet
134
135 @staticmethod
136 def etree_doc2struct(packet, strip_space=True, strip_ns=True, sub=False, attr_prefix='', gml2ogr=True,
137 ogr2json=True):
138 """
139 :param packet:
140 :param strip_space:
141 :param strip_ns:
142 :param sub:
143 :param attr_prefix:
144 :param gml2ogr:
145 :param ogr2json:
146 :return:
147 """
148 packet.data = packet.data.getroot()
149 return FormatConverter.etree_elem2struct(packet, strip_space, strip_ns, sub, attr_prefix, gml2ogr, ogr2json)
150
151 # END etree_doc
152
153 # START etree_elem
154 @staticmethod
155 def etree_elem2geojson_feature(packet, converter_args=None):
156 """
157
158 """
159 packet = FormatConverter.etree_elem2struct(packet, converter_args)
160 packet = FormatConverter.struct2geojson_feature(packet, converter_args)
161
162 return packet
163
164 @staticmethod
165 def etree_elem2struct(packet, strip_space=True, strip_ns=True, sub=False, attr_prefix='', gml2ogr=True,
166 ogr2json=True):
167 """
168 :param packet:
169 :param strip_space:
170 :param strip_ns:
171 :param sub:
172 :param attr_prefix:
173 :param gml2ogr:
174 :param ogr2json:
175 :return:
176 """
177 packet.data = Util.elem_to_dict(packet.data, strip_space, strip_ns, sub, attr_prefix, gml2ogr, ogr2json)
178 return packet
179
180 # END etree_elem
181
182 # START geojson_feature
183 @staticmethod
184 def geojson_feature2ogr_feature(packet, converter_args=None):
185 from stetl.util import ogr
186
187 # str = json.dumps(packet.data)
188 json_feat = packet.data
189 json_geom = json_feat["geometry"]
190 json_props = json_feat["properties"]
191
192 # Create OGR Geometry from GeoJSON geom-fields
193 geom_dict = dict()
194 geom_dict["type"] = json_geom["type"]
195 geom_dict["coordinates"] = json_geom["coordinates"]
196 geom_str = json.dumps(geom_dict)
197 ogr_geom = ogr.CreateGeometryFromJson(geom_str)
198
199 # Once: create OGR Feature definition
200 # TODO: assume all string-fields for now, may use type-mapping definition in converter_args
201 comp = packet.component
202 if comp.feat_def is None:
203 comp.feat_def = ogr.FeatureDefn()
204
205 field_def = ogr.FieldDefn("id", ogr.OFTString)
206 comp.feat_def.AddFieldDefn(field_def)
207
208 for field_name in json_props:
209 field_def = ogr.FieldDefn(field_name, ogr.OFTString)
210 comp.feat_def.AddFieldDefn(field_def)
211
212 ogr_geom_type = ogr_geom.GetGeometryType()
213 comp.feat_def.SetGeomType(ogr_geom_type)
214
215 # Create and populate Feature with id, geom and attributes
216 feature = ogr.Feature(comp.feat_def)
217 json_id = json_feat["id"]
218 feature.SetField("id", json_id)
219 feature.SetGeometry(ogr_geom)
220 for field_name in json_props:
221
222 field_value = str(json_props[field_name])
223
224 # print("id=%s k=%s v=%s" % (json_id, field_name, field_value))
225 feature.SetField(field_name, field_value)
226
227 packet.data = feature
228 return packet
229
230 # END geojson_feature
231
232 # START geojson_collection
233
234 @staticmethod
235 def geojson_coll2ogr_feature_arr(packet, converter_args=None):
236 json_feat_arr = packet.data["features"]
237 ogr_feat_arr = list()
238
239 for feat in json_feat_arr:
240 packet.data = feat
241 packet = FormatConverter.geojson_feature2ogr_feature(packet)
242 ogr_feat_arr.append(packet.data)
243
244 packet.data = ogr_feat_arr
245 return packet
246
247 # END geojson_collection
248
249 # START gdal_vsi_path
250
251 @staticmethod
252 def gdal_vsi_path2etree_doc(packet, converter_args=None):
253 from stetl.util import gdal
254 import re
255
256 # Example input path:
257 # /vsizip/{/vsizip/{BAGGEM0221L-15022021.zip}/GEM-WPL-RELATIE-15022021.zip}/GEM-WPL-RELATIE-15022021-000001.xml
258 vsi_file_path = packet.data
259 vsi_file = gdal.VSIFOpenL(vsi_file_path, 'rb')
260 gdal.VSIFSeekL(vsi_file, 0, 2)
261 vsileng = gdal.VSIFTellL(vsi_file)
262 gdal.VSIFSeekL(vsi_file, 0, 0)
263
264 # read the XML as string (or bytearray)
265 xml_str = gdal.VSIFReadL(1, vsileng, vsi_file)
266
267 # Type is GDAL-version dependent, may be bytes-like
268 if type(xml_str) in [bytearray, bytes]:
269 xml_str = xml_str.decode('utf-8')
270
271 # Need to strip the XML header to avoid XML parse error
272 xml_str = re.sub(r'<\?xml.*?\?>', '', xml_str)
273 packet.data = etree.fromstring(xml_str)
274
275 return packet
276
277 # END gdal_vsi_path
278
279 # START ogr_feature
280
281 @staticmethod
282 def ogr_feature2struct(packet, converter_args=None):
283 s = packet.data.ExportToJson()
284 import ast
285 # http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary
286 # ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
287 packet.data = ast.literal_eval(s)
288
289 return packet
290
291 # END ogr_feature
292
293 @staticmethod
294 def ogr_feature_arr2geojson_coll(packet, converter_args=None):
295 # See http://geojson.org/geojson-spec.html
296 geojson_coll = {'type': 'FeatureCollection', 'features': []}
297 import ast
298 for feature in packet.data:
299 geojson_coll['features'].append(ast.literal_eval(feature.ExportToJson()))
300
301 packet.data = geojson_coll
302
303 return packet
304
305 @staticmethod
306 def record2struct(packet, converter_args=None):
307 if converter_args is not None:
308 struct = dict()
309 struct[converter_args['top_name']] = packet.data
310 packet.data = struct
311
312 return packet
313
314 @staticmethod
315 def record2record_array(packet, converter_args=None):
316 if not hasattr(packet, 'arr'):
317 packet.arr = list()
318
319 if packet.data is not None:
320 packet.arr.append(packet.data)
321 packet.consume()
322
323 # At end of stream or when max array size reached: close the array
324 if packet.is_end_of_stream() is True or \
325 (converter_args is not None and len(packet.arr) >= converter_args['max_len']):
326 # End of stream reached: assembled record array
327 packet.data = packet.arr
328 packet.arr = list()
329
330 return packet
331
332 @staticmethod
333 def record_array2struct(packet, converter_args=None):
334 return FormatConverter.record2struct(packet, converter_args)
335
336 @staticmethod
337 def string2etree_doc(packet):
338 packet.data = etree.fromstring(packet.data)
339 return packet
340
341 @staticmethod
342 def struct2string(packet):
343 packet.data = packet.to_string()
344 return packet
345
346 @staticmethod
347 def struct2geojson_feature(packet, converter_args=None):
348 key, feature_struct = packet.data.popitem()
349 feature = {'type': 'feature', 'properties': {}}
350
351 id_field = None
352 if converter_args:
353 id_field = converter_args['feature_id_attr']
354
355 for attr_name in feature_struct:
356 val = feature_struct[attr_name]
357 if attr_name == 'geometry':
358 feature['geometry'] = val
359 elif attr_name == id_field:
360 feature['id'] = val
361 else:
362 feature['properties'][attr_name] = val
363
364 packet.data = feature
365 return packet
366
367
368 # 'xml_line_stream', 'etree_doc', 'etree_element', 'etree_feature_array', 'xml_doc_as_string',
369 # 'string', 'record', 'record_array', 'geojson_collection', geojson_feature', 'struct',
370 # 'ogr_feature', 'ogr_feature_array', 'any'
371 FORMAT_CONVERTERS = {
372 FORMAT.etree_doc: {
373 FORMAT.geojson_collection: FormatConverter.etree_doc2geojson_collection,
374 FORMAT.string: FormatConverter.etree_doc2string,
375 FORMAT.struct: FormatConverter.etree_doc2struct,
376 FORMAT.xml_doc_as_string: FormatConverter.etree_doc2string
377 },
378 FORMAT.etree_element: {
379 FORMAT.geojson_feature: FormatConverter.etree_elem2geojson_feature,
380 FORMAT.string: FormatConverter.etree_doc2string,
381 FORMAT.struct: FormatConverter.etree_elem2struct,
382 FORMAT.xml_doc_as_string: FormatConverter.etree_doc2string
383 },
384 FORMAT.geojson_feature: {
385 FORMAT.ogr_feature: FormatConverter.geojson_feature2ogr_feature
386 },
387 FORMAT.geojson_collection: {
388 FORMAT.ogr_feature_array: FormatConverter.geojson_coll2ogr_feature_arr
389 },
390 FORMAT.gdal_vsi_path: {
391 FORMAT.etree_doc: FormatConverter.gdal_vsi_path2etree_doc
392 },
393 FORMAT.ogr_feature: {
394 FORMAT.geojson_feature: FormatConverter.ogr_feature2struct,
395 FORMAT.struct: FormatConverter.ogr_feature2struct
396 },
397 FORMAT.ogr_feature_array: {
398 FORMAT.geojson_collection: FormatConverter.ogr_feature_arr2geojson_coll
399 },
400 FORMAT.record: {
401 FORMAT.struct: FormatConverter.record2struct,
402 FORMAT.record_array: FormatConverter.record2record_array
403 },
404 FORMAT.record_array: {
405 FORMAT.struct: FormatConverter.record_array2struct
406 },
407 FORMAT.string: {
408 FORMAT.etree_doc: FormatConverter.string2etree_doc,
409 FORMAT.xml_doc_as_string: FormatConverter.no_op
410 },
411 FORMAT.struct: {
412 FORMAT.string: FormatConverter.struct2string,
413 FORMAT.geojson_feature: FormatConverter.struct2geojson_feature
414 },
415 FORMAT.xml_doc_as_string: {
416 FORMAT.etree_doc: FormatConverter.string2etree_doc,
417 FORMAT.string: FormatConverter.no_op
418 },
419 FORMAT.line_stream: {
420 FORMAT.string: FormatConverter.no_op
421 },
422 FORMAT.xml_line_stream: {
423 FORMAT.string: FormatConverter.no_op
424 }
425 }