Debian Codegraph @

stetl/filters/fileextractor.py

raw
1 # Extracts a file from and archive file like a .zip,
2 # and saves it as the given file name.
3 #
4 # Author: Just van den Broecke (generic and VsiFileExtractor)
5 # Author: Frank Steggink (ZipFileExtractor)
6 #
7 import os.path
8 from stetl.component import Config
9 from stetl.filter import Filter
10 from stetl.util import Util
11 from stetl.packet import FORMAT
12
13 log = Util.get_log('fileextractor')
14
15 DEFAULT_BUFFER_SIZE = 1024 * 1024 * 1024
16
17
18 class FileExtractor(Filter):
19 """
20 Abstract Base Class.
21 Extracts a file an archive and saves as the configured file name.
22
23 consumes=FORMAT.any, produces=FORMAT.string
24 """
25
26 # Start attribute config meta
27
28 @Config(ptype=str, default=None, required=True)
29 def file_path(self):
30 """
31 File name to write the extracted file to.
32 """
33 pass
34
35 @Config(ptype=bool, default=True, required=False)
36 def delete_file(self):
37 """
38 Delete the file when the chain has been completed?
39 """
40 pass
41
42 @Config(ptype=int, default=DEFAULT_BUFFER_SIZE, required=False)
43 def buffer_size(self):
44 """
45 Buffer size for read buffer during extraction.
46 """
47 pass
48
49 # End attribute config meta
50
51 # Constructor
52 def __init__(self, configdict, section, consumes=FORMAT.any, produces=FORMAT.string):
53 Filter.__init__(self, configdict, section, consumes=consumes, produces=produces)
54
55 def delete_target_file(self):
56 if os.path.isfile(self.file_path):
57 os.remove(self.file_path)
58
59 def extract_file(self, packet):
60 log.error('Only classes derived from FileExtractor can be used!')
61
62 def invoke(self, packet):
63
64 if packet.data is None:
65 log.info("Input data is empty")
66 return packet
67
68 # Optionally remove old file
69 self.delete_target_file()
70 self.extract_file(packet)
71 packet.data = self.file_path
72
73 if not os.path.isfile(self.file_path):
74 log.warn('Extracted file {} does not exist'.format(self.file_path))
75 packet.data = None
76
77 return packet
78
79 def after_chain_invoke(self, packet):
80 if not self.delete_file:
81 return
82
83 self.delete_target_file()
84
85 return True
86
87
88 class ZipFileExtractor(FileExtractor):
89 """
90 Extracts a file from a ZIP file, and saves it as the given file name.
91 Author: Frank Steggink
92
93 consumes=FORMAT.record, produces=FORMAT.string
94 """
95
96 def __init__(self, configdict, section):
97 FileExtractor.__init__(self, configdict, section, consumes=FORMAT.record)
98
99 def extract_file(self, packet):
100
101 import zipfile
102
103 with zipfile.ZipFile(packet.data['file_path']) as z:
104 with open(self.file_path, 'wb') as f:
105 with z.open(packet.data['name']) as zf:
106 while True:
107 buffer = zf.read(self.buffer_size)
108 if not buffer:
109 break
110 f.write(buffer)
111
112
113 class VsiFileExtractor(FileExtractor):
114 """
115 Extracts a file from a GDAL /vsi path spec, and saves it as the given file name.
116
117 Example paths:
118 /vsizip/{/project/nlextract/data/BAG-2.0/BAGNLDL-08112020.zip}/9999STA08112020.zip'
119 /vsizip/{/vsizip/{BAGGEM0221L-15022021.zip}/GEM-WPL-RELATIE-15022021.zip}/GEM-WPL-RELATIE-15022021-000001.xml
120
121 See also stetl.inputs.fileinput.VsiZipFileInput that generates these paths.
122
123 Author: Just van den Broecke
124
125 consumes=FORMAT.gdal_vsi_path, produces=FORMAT.string
126 """
127
128 def __init__(self, configdict, section):
129 FileExtractor.__init__(self, configdict, section, consumes=FORMAT.gdal_vsi_path)
130
131 def extract_file(self, packet):
132 from stetl.util import gdal
133
134 # Example input path can be as complex as this:
135 #
136 vsi_file_path = packet.data
137 vsi = None
138 vsi_len = 0
139 try:
140 # gdal.VSIF does not support 'with' so old-school open/close.
141 log.info('Extracting {}'.format(vsi_file_path))
142 vsi = gdal.VSIFOpenL(vsi_file_path, 'rb')
143 with open(self.file_path, 'wb') as f:
144 gdal.VSIFSeekL(vsi, 0, 2)
145 vsi_len = gdal.VSIFTellL(vsi)
146 gdal.VSIFSeekL(vsi, 0, 0)
147 read_size = self.buffer_size
148 if vsi_len < read_size:
149 read_size = vsi_len
150
151 while True:
152 buffer = gdal.VSIFReadL(1, read_size, vsi)
153 if not buffer or len(buffer) == 0:
154 break
155 f.write(buffer)
156
157 except Exception as e:
158 log.error('Cannot extract {} err={}'.format(vsi_file_path, str(e)))
159 raise e
160 finally:
161 if vsi:
162 log.info('Extracted {} ok len={} bytes'.format(vsi_file_path, vsi_len))
163 gdal.VSIFCloseL(vsi)