-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencode.py
210 lines (171 loc) · 7.95 KB
/
encode.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
# Author: Jacob Hallberg
# Last Edited: 12/30/2017
import huffman
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from pathlib import Path
from math import log2
from encode_UI import Ui_HuffmanEncode
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton, QFileDialog, QTabWidget
from PyQt5.QtCore import (QLineF, QPointF, QRectF, Qt, QTimer)
matplotlib.rcParams.update({'axes.titlesize': 32})
class Huffman_Encode(QMainWindow, Ui_HuffmanEncode):
def __init__(self, parent=None):
super(Huffman_Encode, self).__init__(parent)
self.setupUi(self)
self.original_file_size, self.encoding_size, self.lower_bound = 0, 0, 0
self.decoded_file, self.file_name, self.encoding, self.code_book = "", "", "", ""
self.uploaded, self.save_or, self.saveable = False, 0, 0
self.frequency = {}
self.UploadFile.clicked.connect(self.encode_button_clicked)
self.DecodeFile.clicked.connect(self.decode_button_clicked)
def decode_button_clicked(self):
if not self.save_or:
self.openFileNamesDialog()
else:
self.saveFileDialog('write_decode')
def encode_button_clicked(self):
if not self.saveable:
self.openFileNameDialog()
if self.uploaded:
self.envoke_encode()
self.calculate_size()
self.translate_button()
self.create_plot()
self.uploaded = False
self.saveable = True
elif self.saveable == 1:
self.saveFileDialog('write_binary')
else:
self.saveFileDialog('write_code_book')
self.reset()
# huffman.decode_file(self.code_book, self.file_name)
def openFileNameDialog(self):
# Settng up elements for saving.
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.file_name, _ = QFileDialog.getOpenFileName(
self, "Select file for encoding", "",
"All Files (*);;Python Files (*.py);;Text Files (*.txt)", options=options)
if self.file_name:
self.saveable += 1
self.uploaded = True
def openFileNamesDialog(self):
if not self.save_or:
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
files, _ = QFileDialog.getOpenFileNames(
self, "First select the encoding and then the compression.", "", "All Files (*);;Binary Files (*.bin)", options=options)
if len(files) == 2:
decoded_file = huffman.decode_file(files[1], files[0])
self.textBrowser.setText(decoded_file)
self.label.setText("Upload Complete")
self.DecodeFile.setText("Click Again to Save File")
else:
self.DecodeFile.setText("You Must Upload Two Files")
else:
self.save_or = 0
def saveFileDialog(self, operation):
# Settng up elements for saving.
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
sfile_name, _ = QFileDialog.getSaveFileName(
self, "Type in file name to save compression.", "", "All Files (*);;Binary Files (*.bin)", options=options)
# Operation string determines function call.
if sfile_name and operation == 'write_binary':
huffman.write_binary_encoding(self.encoding, sfile_name)
self.UploadFile.setText("Click again to save Code Book")
self.saveable += 1
elif sfile_name and operation == 'write_code_book':
huffman.write_code_book(self.code_book, sfile_name)
self.UploadFile.setText("Click to compress another file")
elif sfile_name and operation == 'write_decode':
with open(sfile_name, 'w') as decode:
decode.write(self.decoded_file)
self.file_name = sfile_name
def calculate_size(self):
file = Path(self.file_name)
self.original_file_size = file.stat().st_size
self.encoding_size = len(self.encoding) + 8 - (len(self.encoding) % 8)
# Theoretical limit based on:
# https://en.wikipedia.org/wiki/Entropy_(information_theory)
p_xi = lambda freq, n=self.original_file_size: freq / n
entropy_sum = 0
for _, value in self.frequency.items():
entropy_sum += p_xi(value) * log2(p_xi(value))
self.lower_bound = int(
round(entropy_sum * -1 * self.original_file_size, 0))
self.original_file_size = self.original_file_size * 8
# Bit comparisons between the original file and my compression.
# Added 7 bits to my implementation size because
print("- Original File Size :", self.original_file_size, "bits.")
print("- My Implementation Size:", self.encoding_size, "bits.")
print("- Theoretical Limit Size:", self.lower_bound, "bits.")
def envoke_encode(self):
# Open file using the passed in file_name.
with open(self.file_name) as stream:
read_file = stream.read()
# Run the encoding functions from huffman.py.
self.frequency = huffman.calculate_frequency(read_file)
self.encoding, self.code_book = huffman.create_encoding(
self.frequency, read_file)
def translate_button(self):
_translate = QtCore.QCoreApplication.translate
percentage_change = 100 - \
((self.encoding_size / self.original_file_size) * 100)
changed_string = "File size reducable by: " + \
str(round(percentage_change, 0)) + "%"
self.label_2.setText(_translate("HuffmanEncode", changed_string))
self.UploadFile.setText(_translate(
"HuffmanEncode", "Click Again to Save Encoding"))
def reset(self):
self.setupUi(self)
self.original_file_size, self.encoding_size, self.lower_bound = 0, 0, 0
self.file_name, self.encoding, self.code_book = "", "", ""
self.uploaded, self.saveable = False, 0
self.frequency = {}
self.UploadFile.clicked.connect(self.encode_button_clicked)
self.DecodeFile.clicked.connect(self.decode_button_clicked)
def create_plot(self):
size_l = [self.original_file_size,
self.encoding_size, self.lower_bound]
m = PlotCanvas(self.Encode, 7, 5, 100, size_l)
m.move(35, 15)
m.show()
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100, hi=None):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(
self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot(hi)
def plot(self, size_l):
# Increase font size beacuse of resolution.
x_data = ["Original File", "Our Implementation", "Theoretical Limit"]
y_data = size_l
# Create 1x1 area and plot.
axes = self.figure.add_subplot(1, 1, 1)
axes.bar(x_data, y_data, width=.5)
# axes.legend(('r','g','b'), ('Original File', 'My Implementation', 'Thoeretical Limit'))
# red_patch = mpatches.Patch(color='red', label='The red data')
# axes.legend(handles=[red_patch])
for i, v in enumerate(size_l):
axes.text(i - .1, v + 35, str(v), color='red', fontweight='bold')
axes.set_ylabel("Size (bits)", fontsize=18)
axes.set_xlabel("Compression Type", fontsize=18)
self.draw()
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
nextGui = Huffman_Encode()
nextGui.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()