-
Notifications
You must be signed in to change notification settings - Fork 0
/
csvmod.py
executable file
·453 lines (324 loc) · 11.2 KB
/
csvmod.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
#!/usr/bin/python
import csv
def comma_decimal(val):
return float(val.replace(",", "."))
def comma_decimal_formatter(val):
return str(val).replace(".", ",")
class CSVError(Exception):
pass
class CSVHeaderError(CSVError):
def __init__(self, expected, actual):
CSVError.__init__(self, "Invalid header")
self.expected = expected
self.actual = actual
class CSVFieldError(CSVError):
def __init__(self, field, file=None):
if file is None:
CSVError.__init__(self, "Unknown field '%s'" % field)
else:
CSVError.__init__(self, "Unknown field '%s' in file '%s'" % (field, file))
class CSVMod(object):
def __init__(self, controller):
self.controller = controller
def start(self):
reader = self.controller.reader
reader.begin()
writer = self.controller.writer
writer.begin()
writer.writeheader()
for data in reader:
row = reader.create_row(data)
update = self.controller.handle(row)
self.controller.post_progress(row)
if update is None:
update = row.is_changed
if update:
writer.write(row.fields)
self.controller.finish()
class CSVRow(object):
"""
:type joins: dict
"""
def __init__(self, fields, joins, aliases: dict, file_name=None):
self.fields = fields
self.origin = dict(fields)
self.joins = joins
self.aliases = aliases
self.file_name = file_name
def __getitem__(self, item):
return self.fields[self._get_field_name(item, True)]
def __setitem__(self, key, value):
getattr(self, "fields")[self._get_field_name(key, False)] = value
def __repr__(self):
return str(self.fields)
def _get_field_name(self, key, strict=True) -> str:
if key in self.fields:
return key
if key in self.aliases:
return self.aliases[key]
if strict:
raise CSVFieldError(key, file=self.file_name)
else:
return key
@property
def is_changed(self) -> bool:
return self.origin != self.fields
def join(self, name, field=None):
"""
:rtype: CSVRow
"""
try:
join = self.joins[name]
except KeyError:
raise CSVError("Unknown join '%s'" % name)
joint = join.auto_join(self)
if joint is None:
return None
if field is not None:
return joint[field]
return joint
def has_join(self, name) -> bool:
return name in self.joins.keys()
class CSVFile(object):
def __init__(self, **kwargs):
self._fields = list()
self.file_name = kwargs.pop("file")
self.file_handle = None
self.format = dict(delimiter=";", quotechar='"')
self.encoding = kwargs.pop("encoding", "utf-8")
self.aliases = kwargs.pop("aliases", dict())
self.fields = kwargs.pop("fields", list())
self.converter = kwargs.pop("converter", dict())
self.base_csv = None
self.name = kwargs.pop("name", None)
if "format" in kwargs:
self.format.update(kwargs.pop("format"))
if len(kwargs) > 0:
raise KeyError("Invalid option: %s" % ", ".join(kwargs.keys()))
@property
def fields(self):
return self._fields
@fields.setter
def fields(self, lst):
fields = list()
for field in lst:
if field in self.aliases:
fields.append(self.aliases[field])
else:
fields.append(field)
self._fields = fields
def begin(self):
pass
def end(self):
self.file_handle.close()
def _reduce_fields(self, row: dict) -> dict:
return {k: v for k, v in row.items() if k in self.fields}
class CSVReadFile(CSVFile):
def __init__(self, **kwargs):
self._joins = dict()
self.joins = kwargs.pop("joins", list())
super().__init__(**kwargs)
@property
def joins(self):
return self._joins
@joins.setter
def joins(self, joins):
if not hasattr(joins, "__iter__"):
joins = (joins, )
self._joins = dict()
for join in joins:
self._joins[join.name] = join
def __iter__(self):
return self.base_csv
def check_header(self, header):
if self.fields is None:
return True
header = list(header)
fields = list(self.fields)
for field in fields:
if field not in header:
raise CSVHeaderError(field, header)
return True
def create_row(self, data) -> CSVRow:
for field, converter in self.converter.items():
data[field] = converter(data[field])
return CSVRow(self._reduce_fields(data), self.joins, self.aliases, self.name)
@property
def reader(self) -> csv.DictReader:
if not self.base_csv:
self.file_handle = open(self.file_name, "r", encoding=self.encoding)
self.base_csv = csv.DictReader(self.file_handle, **self.format)
return self.base_csv
def begin(self):
if self.fields is None:
self.fields = self.reader.fieldnames
else:
self.check_header(self.reader.fieldnames)
for join in self.joins.values():
join.begin()
def end(self):
super().end()
for join in self.joins.values():
join.end()
class CSVWriteFile(CSVFile):
def __init__(self, **kwargs):
self.formatter = kwargs.pop("formatter", dict())
if "name" not in kwargs:
kwargs["name"] = "target"
super().__init__(**kwargs)
@property
def writer(self) -> csv.DictWriter:
if not self.base_csv:
self.file_handle = open(self.file_name, "w", encoding=self.encoding)
self.base_csv = csv.DictWriter(self.file_handle, self.fields, **self.format)
return self.base_csv
@CSVFile.fields.setter
def fields(self, val):
self._fields = val
def write(self, data):
data = dict(data)
for field, formatter in self.formatter.items():
data[field] = formatter(data[field])
self.writer.writerow(self._reduce_fields(data))
def writeheader(self):
self.writer.writeheader()
def _reduce_fields(self, row: dict):
result = dict()
for k, v in row.items():
if k in self.fields:
result[k] = v
if k in self.aliases:
result[self.aliases[k]] = v
return result
class JoinCSV(CSVReadFile):
def __init__(self, **kwargs):
self.local_field = kwargs.pop("local")
self.join_field = kwargs.pop("remote")
self.cache_enabled = kwargs.pop("cache", True)
self.cache = dict()
if "name" not in kwargs:
kwargs["name"] = kwargs["file"]
super().__init__(**kwargs)
def get_row(self, criteria) -> CSVRow:
if self.cache_enabled:
f = self.get_row_cached
else:
f = self.get_row_uncached
data = f(criteria)
return data
def get_row_uncached(self, criteria) -> dict:
for row in self.reader:
if self._is_match(row, criteria):
return self.create_row(row)
def get_row_cached(self, criteria) -> dict:
if criteria in self.cache:
return self.cache[criteria]
for row in self.reader:
r = self.create_row(row)
self.cache[row[self.join_field]] = r
if self._is_match(r, criteria):
return r
def auto_join(self, row: CSVRow) -> CSVRow:
criteria = row[self.local_field]
return self.get_row(criteria)
def _is_match(self, row, criteria) -> bool:
return row[self.join_field] == criteria
class Statistics(object):
class Counter(object):
def __init__(self, allow_negative=True):
self.slots = dict()
self.allow_negative = allow_negative
def plus(self, slot, n=1):
try:
self.slots[slot] += n
except KeyError:
self.slots[slot] = n
if not self.allow_negative and self[slot] < 0:
self.slots[slot] = 0
def minus(self, slot, n=1):
self.plus(slot, -n)
def __getitem__(self, item):
return self.slots.get(item, 0)
def __init__(self):
self.changes = {}
self.rows = 0
def process(self, data):
changed = False
for field in data.origin.keys():
if data.origin[field] != data[field]:
changed = True
self._incr("changes", field)
if changed:
self.rows += 1
def finish(self):
import operator
print("Finished, modified %d rows." % self.rows)
s = sorted(self.changes.items(), key=operator.itemgetter(1))
for field, changes in s:
print("%6d %s" % (changes, field))
def _incr(self, prop, index, n=1):
try:
self.__dict__[prop][index] += n
except KeyError:
self.__dict__[prop][index] = n
class Controller(object):
statistics = [Statistics()]
settings = dict()
output = dict()
def __init__(self, input_file=None, output_file=None):
if input_file is not None:
self.settings["file"] = input_file
if output_file is not None:
self.output["file"] = output_file
self._reader = None
self._writer = None
def handle(self, data):
pass
@property
def reader(self) -> CSVReadFile:
if not self._reader:
if "name" not in self.settings:
self.settings["name"] = "main"
self._reader = CSVReadFile(**self.settings)
return self._reader
@property
def writer(self) -> CSVWriteFile:
if not self._writer:
opts = dict(self.output)
if opts.get("fields") is None:
opts["fields"] = self.reader.fields
if "name" not in opts:
opts["name"] = "main"
self._writer = CSVWriteFile(**opts)
return self._writer
def post_progress(self, data):
for stat in self.statistics:
stat.process(data)
def finish(self):
self._reader.end()
for stat in self.statistics:
stat.finish()
if __name__ == "__main__":
from sys import argv, path
from os import getcwd
def import_controller(name):
components = name.split('.')
module = __import__(components[0])
for comp in components[1:]:
module = getattr(module, comp)
return module
if len(argv) != 4:
print("Usage: %s <controller> <input> <output>" % argv[0])
exit(1)
controller_name = argv[1]
read_file = argv[2]
write_file = argv[3]
path.append(getcwd())
chosen_controller = import_controller(controller_name)
mod = CSVMod(chosen_controller(read_file, write_file))
try:
mod.start()
except CSVHeaderError as e:
print("Unexpected header detected.")
print(e.expected)
print(e.actual)