-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperf_huffman.py
More file actions
212 lines (148 loc) · 5.58 KB
/
perf_huffman.py
File metadata and controls
212 lines (148 loc) · 5.58 KB
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
import json
from collections import Counter, namedtuple
from multiprocessing import Pool, cpu_count
from os.path import getsize
from time import process_time
MULTIPROCESSING_THRESHOLD = 200000
class HuffmanHeap(list):
Element = namedtuple('Element', ('weight', 'encodings'))
def push(self, weight, encodings):
element = HuffmanHeap.Element(weight, encodings)
if not self or weight >= self[-1].weight:
self.append(element)
return
for i in range(len(self)):
if weight < self[i].weight:
self.insert(i - 1, element)
return
def create_encoding_table(bytes_):
heap = HuffmanHeap()
for byte, count in Counter(bytes_).items():
heap.push(count, {byte: ''})
while len(heap) - 1:
lo, hi = heap.pop(0), heap.pop(0)
for byte in lo.encodings:
lo.encodings[byte] = '0' + lo.encodings[byte]
for byte in hi.encodings:
hi.encodings[byte] = '1' + hi.encodings[byte]
heap.push(lo.weight + hi.weight, {**lo.encodings, **hi.encodings})
return heap[0].encodings
def segment(array, parts):
avg = len(array) / parts
last = 0.0
while last < len(array):
yield array[int(last):int(last + avg)]
last += avg
def encoding_worker(data, table):
return ''.join(table[byte] for byte in data)
def encode(data, table, pool):
tasks = [pool.apply_async(encoding_worker, args=(part, table)) for part in segment(data, cpu_count())]
del data, table
return ''.join(task.get() for task in tasks)
def segment_bytewise(string, parts):
avg = len(string) / parts
avg = avg + (8 - avg % 8)
last = 0
while last < len(string):
yield string[int(last):int(last + avg)]
last += avg
def pack_bytes_worker(string):
return bytearray(int(string[i:i + 8], 2) for i in range(0, len(string), 8))
def pack_bytes(string, pool):
tasks = [pool.apply_async(pack_bytes_worker, args=(part,))
for part in segment_bytewise(string + '0' * (8 - len(string) % 8), cpu_count())]
del string
return bytearray(b''.join(task.get() for task in tasks))
def compress(filename, table_filename, compressed_filename, encoding='UTF-8', silent=False):
start_time = process_time()
silent or print('Reading... ', end='')
with open(filename, 'rb') as file:
uncompressed_bytes = file.read()
silent or print('Done')
if not uncompressed_bytes or len(uncompressed_bytes) == 1:
raise ValueError("Not enough data to compress")
silent or print('Creating tables... ', end='')
encoding_table = create_encoding_table(uncompressed_bytes)
decoding_table = {value: key for key, value in encoding_table.items()}
decoding_table['size'] = len(uncompressed_bytes)
silent or print('Done')
silent or print('Writing table... ', end='')
with open(table_filename, 'w+', encoding=encoding) as file:
json.dump(decoding_table, file)
silent or print('Done')
del decoding_table
pool = Pool(cpu_count())
silent or print('Compressing... ', end='')
if len(uncompressed_bytes) < MULTIPROCESSING_THRESHOLD:
compressed_string = encoding_worker(uncompressed_bytes, encoding_table)
else:
silent or print('using multiprocessing... ', end='')
compressed_string = encode(uncompressed_bytes, encoding_table, pool)
silent or print('Done')
del uncompressed_bytes, encoding_table
silent or print('Preparing data using multiprocessing... ', end='')
compressed_bytes = pack_bytes(compressed_string, pool)
silent or print('Done')
del compressed_string
pool.close()
pool.terminate()
silent or print('Writing... ', end='')
with open(compressed_filename, 'wb+') as file:
file.write(compressed_bytes)
silent or print('Done')
silent or print('Encoded in {:.4f} seconds, {:.2%} Space savings'.format(
process_time() - start_time,
1 - (getsize(compressed_filename) + getsize(table_filename)) / getsize(filename))
)
def unpack_bytes_worker(bytes_):
return ''.join('{0:08b}'.format(byte) for byte in bytes_)
def unpack_bytes(bytes_, pool):
tasks = [pool.apply_async(unpack_bytes_worker, args=(part,)) for part in segment(bytes_, cpu_count())]
del bytes_
return ''.join(task.get() for task in tasks)
def decode(string, table, size):
uncompressed_bytes = b''
string = iter(string)
buffer = ''
while len(uncompressed_bytes) < size:
buffer += next(string)
if buffer in table:
uncompressed_bytes += bytes([table[buffer]])
buffer = ''
return uncompressed_bytes
def decompress(filename, table_filename, uncompressed_filename, encoding='UTF-8', silent=False):
start_time = process_time()
silent or print('Reading file...', end='')
with open(filename, 'rb') as file:
compressed_bytes = file.read()
silent or print('Done')
pool = Pool(cpu_count())
silent or print('Preparing data using multiprocessing... ', end='')
compressed_string = unpack_bytes(compressed_bytes, pool)
silent or print('Done')
pool.close()
pool.terminate()
silent or print('Reading table... ', end='')
with open(table_filename, encoding=encoding) as file:
decoding_table = json.load(file)
size = decoding_table.pop('size')
silent or print('Done')
silent or print('Uncompressing...', end='')
uncompressed_bytes = decode(compressed_string, decoding_table, size)
silent or print('Done')
silent or print('Writing... ', end='')
with open(uncompressed_filename, 'wb+') as file:
file.write(uncompressed_bytes)
silent or print('Done')
silent or print('Decoded in {:.4f} seconds'.format(process_time() - start_time))
def main():
in_name = 'sample3.txt'
table_name = 'table.json'
compressed_name = 'compressed.bin'
out_name = 'out.bmp'
compress(in_name, table_name, compressed_name)
decompress(compressed_name, table_name, out_name)
with open(in_name, 'rb') as in_, open(out_name, 'rb') as out:
assert in_.read() == out.read()
if __name__ == '__main__':
main()