-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcompress.py
46 lines (35 loc) · 1.15 KB
/
compress.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
import copy
import arithmetic_compressor.arithmetic_coding as AE
# Compress using arithmetic encoding
class AECompressor:
def __init__(self, model, adapt=True) -> None:
self.adapt = adapt
# clone model, so we dont mutate original
self.model = copy.deepcopy(model)
self.__model = copy.deepcopy(model) # for decoding
def compress(self, data):
encoder = AE.Encoder()
for symbol in data:
# Use the model to predict the probability of the next symbol
probability = self.model.cdf()
# encode the symbol
encoder.encode_symbol(probability, symbol)
if self.adapt:
# update the model with the new symbol
self.model.update(symbol)
encoder.finish()
return encoder.get_encoded()
def decompress(self, encoded, length_encoded):
decoded = []
model = self.__model
decoder = AE.Decoder(encoded)
for _ in range(length_encoded):
# probability of the next symbol
probability = model.cdf()
# decode symbol
symbol = decoder.decode_symbol(probability)
if self.adapt:
# update model
model.update(symbol)
decoded += [symbol]
return decoded