-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.py
225 lines (179 loc) · 6.82 KB
/
parser.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
import collections
import csv
import re
import sys
from collections import OrderedDict
from pathlib import Path
HEADER_FIELD = '.m.Pay Date'
FIELDS_ORDER = [
HEADER_FIELD, '.m.Pay', '.m.',
'.d.p',
'.d.d',
'.d.t',
'.d.et',
'.d.ytd',
]
UNWANTED_FIELDS = [
'.m.Company Name', '.m.Account', '.m.Sort Code', '.m.NI Number', '.m.NI Category', '.m.Pay Method',
]
def parse_amount(amount: str):
amount = amount.replace(',', '')
if amount.endswith('-'):
return -float(amount[:-1])
else:
return float(amount)
def parse_metadata(metadata_text: str):
metadata = {}
for row in metadata_text.splitlines():
if not row:
continue
_, cell1, cell2, cell3, _ = row.split('|')
for cell in [cell1, cell2, cell3]:
cell = cell.strip()
if cell:
separator_regex = r':\s+' if ':' in cell else r'\s\s+'
item, value = re.compile(separator_regex).split(cell, maxsplit=1)
metadata[item.strip()] = value.strip()
return metadata
def parse_payments_table(payments_table: str):
payments = {}
deductions = {}
ytd_balances = {}
for row in payments_table.splitlines():
row = row.strip()
if not row:
continue
_, payment, deduction, ytd_balance, _ = row.split('|')
payment = payment.strip()
if payment:
payment_item, amount = re.compile(r'\s\s+').split(payment)
payments[payment_item] = parse_amount(amount)
deduction = deduction.strip()
if deduction:
deduction_item, amount = re.compile(r'\s\s+').split(deduction)
deductions[deduction_item] = parse_amount(amount)
ytd_balance = ytd_balance.strip()
if ytd_balance:
ytd_balance_item, amount = re.compile(r'\s\s+').split(ytd_balance)
ytd_balances[ytd_balance_item] = parse_amount(amount)
return payments, deductions, ytd_balances
def parse_totals(totals_row: str):
totals = {}
_, payment_total, deduction_total, net_pay, _ = totals_row.split('|')
for total_value in [payment_total, deduction_total, net_pay]:
item, amount = re.compile(r':\s+').split(total_value.strip())
totals[item] = parse_amount(amount)
return totals
def parse_employer_totals(employer_total_footer):
totals = {}
for row in employer_total_footer.strip().splitlines()[1:]:
row = row.strip()
if not row or row.count('|') != 4:
continue
_, this_employer_cell, _ = row.split('|', maxsplit=2)
item, amount = re.compile(r'\s\s+').split(this_employer_cell.strip())
totals[item] = parse_amount(amount)
return totals
def parse_payslip(payslip_text: str):
address, metadata, payment_data = re.compile(r"^\s+?-+$", re.MULTILINE).split(payslip_text)
_, payment_headers, payments_table, totals_row, _, employer_total_footer = \
re.compile(r"^\s+?-+\|$", re.MULTILINE).split(payment_data)
metadata = parse_metadata(metadata)
payments, deductions, ytd_balances = parse_payments_table(payments_table)
totals = parse_totals(totals_row)
employer_totals = parse_employer_totals(employer_total_footer)
data = {
'p': payments,
'd': deductions,
'ytd': ytd_balances,
't': totals,
'et': employer_totals
}
return {
# 'address': address,
'm': metadata,
'd': data
}
def print_payslip(dd, indent=""):
for k, v in dd.items():
if not hasattr(v, 'items'):
print(f"{k}:\n{v}")
# print(['*'] * 30)
else:
print(f"{k}:\n")
print_payslip(v, indent=indent + " ")
def count_fields(counts, nested_dict, prefix=''):
if hasattr(nested_dict, 'items'):
for k, v in nested_dict.items():
count_fields(counts, v, prefix=prefix + '.' + k)
else:
counts[prefix] += 1
def flatten(nested_dict, flat_dict, prefix=''):
if hasattr(nested_dict, 'items'):
for k, v in nested_dict.items():
flatten(v, flat_dict, prefix=prefix + '.' + k)
else:
flat_dict[prefix] = nested_dict
def write_payslip_csv_month_rows(categories, csv_table):
with open('payslips-month-rows.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=categories)
writer.writeheader()
for row in csv_table:
writer.writerow(row)
def write_payslip_csv_month_columns(columns, csv_table):
with open('payslips-month-columns.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=columns)
# writer.writeheader()
for row in csv_table:
writer.writerow(row)
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
from itertools import tee
from itertools import filterfalse
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
def enforce_order(iterable, prefixes: list):
remainder = iterable
result = []
for prefix in prefixes:
remainder, matching = partition(lambda x: x.startswith(prefix), remainder)
remainder = list(remainder)
result += sorted(matching)
result += sorted(remainder)
return result
if __name__ == '__main__':
payslips_dir = Path(sys.argv[1])
counts = collections.Counter()
csv_rows_table = []
for payslip_file in sorted(payslips_dir.glob('*.txt')):
# if payslip_file.name < '2018-04-' or payslip_file.name > '2019-04-':
# continue
payslip_text = payslip_file.read_text(encoding='utf-8')
if 'Employee Number' not in payslip_text:
print(f"Skipping {payslip_file} ...")
continue
print(f"Parsing {payslip_file} ...")
payslip = parse_payslip(payslip_text)
count_fields(counts, payslip)
flat_payslip = {}
flatten(payslip, flat_payslip)
csv_rows_table.append(flat_payslip)
categories = counts.keys()
categories = enforce_order(categories, FIELDS_ORDER)
# pprint('\n'.join(categories))
# print(len(categories))
write_payslip_csv_month_rows(categories, csv_rows_table)
for unwanted_field in UNWANTED_FIELDS:
categories.remove(unwanted_field)
csv_cols_table = []
columns = [HEADER_FIELD, *[payslip[HEADER_FIELD] for payslip in csv_rows_table]]
for category in categories:
category_row = OrderedDict()
category_row[HEADER_FIELD] = category
for payslip in csv_rows_table:
month = payslip[HEADER_FIELD]
category_row[month] = payslip.get(category)
csv_cols_table.append(category_row)
write_payslip_csv_month_columns(columns, csv_cols_table)
print("Done.")