-
Notifications
You must be signed in to change notification settings - Fork 2
/
comepress.py
228 lines (189 loc) · 7.57 KB
/
comepress.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
import fnmatch
import os
import shutil
import sys
from os.path import isdir, join
from PIL import Image
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import *
bundle_dir = getattr(sys, "_MEIPASS", os.path.abspath(os.path.dirname(__file__)))
def restart_program():
python = sys.executable
os.execl(python, python, *sys.argv)
def include_patterns(*patterns):
def _ignore_patterns(path, all_names):
# Determine names which match one or more patterns (that shouldn't be
# ignored).
keep = (
name for pattern in patterns for name in fnmatch.filter(all_names, pattern)
)
# Ignore file names which *didn't* match any of the patterns given that
# aren't directory names.
dir_names = (name for name in all_names if isdir(join(path, name)))
return set(all_names) - set(keep) - set(dir_names)
return _ignore_patterns
def ignore_list(path, files):
filesToIgnore = []
for fileName in files:
fullFileName = os.path.join(os.path.normpath(path), fileName)
if (
not os.path.isdir(fullFileName)
and not fileName.endswith("jpg")
and not fileName.endswith("jpeg")
and not fileName.endswith("png")
and not fileName.endswith("mp4")
):
filesToIgnore.append(fileName)
return filesToIgnore
class MyGUI(QMainWindow):
def __init__(self):
super(MyGUI, self).__init__()
uic.loadUi(os.path.abspath(os.path.join(bundle_dir, "res/comepress.ui")), self)
# Remove Titlebar and background
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setStyleSheet(
"""QToolTip {
border: none;
color: white;
}"""
)
self.setWindowIcon(QtGui.QIcon("res/inbox_tray_3d.ico"))
# BUTTONS
self.pushButton.clicked.connect(self.browse)
self.checkBox.clicked.connect(self.checked)
self.checkBox.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.closeButton.clicked.connect(self.close)
self.closeButton.setToolTip("Close")
self.closeButton.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.minimizeButton.clicked.connect(self.showMinimized)
self.minimizeButton.setToolTip("Minimize")
self.minimizeButton.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.comboBox.activated.connect(self.comboBoxSelected)
self.horizontalSlider.valueChanged.connect(self.horizontalSliderChanged)
self.setAcceptDrops(True)
# DEFAULT VARIABLES
self.backup = True
self.dragPos = QtCore.QPoint()
self.quality = 100
self.percentageLabel.setText(f"{self.quality}")
self.format = "JPG"
self.show()
def mousePressEvent(self, event):
self.dragPos = event.globalPos()
def mouseMoveEvent(self, event):
if event.buttons() == QtCore.Qt.LeftButton:
self.move(self.pos() + event.globalPos() - self.dragPos)
self.dragPos = event.globalPos()
event.accept()
def checked(self):
self.backup = bool(self.checkBox.isChecked())
def browse(self):
folder_path = QtWidgets.QFileDialog.getExistingDirectory(
self, "Select a Folder"
)
if folder_path == "":
return
self.comepress_folder(folder_path)
alert_dialog = QMessageBox.information(
self, "All good!", "Successfully comepressed all files/folders"
)
def comboBoxSelected(self):
self.format = self.comboBox.currentText()
def horizontalSliderChanged(self):
self.percentageLabel.setText(f"{self.horizontalSlider.value()}")
self.quality = self.horizontalSlider.value()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
allowed_types = ["image/jpeg", "image/jpg", "image/png", "inode/directory"]
dropped_files_folders = []
db = QtCore.QMimeDatabase()
for url in event.mimeData().urls():
mimetype = db.mimeTypeForUrl(url)
if mimetype.name() in allowed_types:
dropped_files_folders.append((url.toLocalFile(), mimetype.name()))
for file_folder_path in dropped_files_folders:
if file_folder_path[1] == "inode/directory":
self.comepress_folder(file_folder_path[0])
else:
self.comepress_file(file_folder_path[0])
alert_dialog = QMessageBox.information(
self, "All good!", "Successfully comepressed all files/folders"
)
def comepress_folder(self, folder_path):
# Get parent folder path
# Get folder name
folder_name = os.path.basename(folder_path)
# Destination backup
if os.path.isdir(f"{folder_path}_COMEPRESS"):
shutil.rmtree(f"{folder_path}_COMEPRESS")
backup_destination = os.path.abspath(f"{folder_path}_COMEPRESS")
# Backup folder
print(f"backup: {self.backup}")
if self.backup:
shutil.copytree(
folder_path,
backup_destination,
ignore=include_patterns("*.png", "*.jpg", "*.jpeg"),
)
# Loop through all the files in the folder
for root, dirs, files in os.walk(
folder_path,
):
for file in files:
# If file is an image
if file.endswith((".jpg", ".jpeg", ".png", ".webp")):
# Convert to WebP
try:
img = Image.open(f"{root}/{file}")
img.save(
(
f"{root}/{file.rsplit('.', 1)[0]}.{self.format}",
self.format,
),
quality=self.quality,
optimize=(self.quality < 100),
)
# Remove original file
os.remove(f"{root}/{file}")
except Exception:
alert_dialog = QMessageBox.information(
self,
"Error!",
f"Please check if {root}/{file} is not corrupt",
)
return
def comepress_file(self, file_path):
# GET DETAILS
parent_folder = os.path.abspath(os.path.join(file_path, os.pardir))
file_name = os.path.basename(file_path)
destination_path = f"{parent_folder}/ORIGINAL_{file_name}"
# BACKUP
if self.backup:
shutil.copyfile(file_path, destination_path)
# CONVERT
try:
img = Image.open(f"{parent_folder}/{file_name}")
img.save(
((f"{parent_folder}/" + file_name.rsplit(".", 1)[0]) + ".webp"), "webp"
)
os.remove(f"{parent_folder}/{file_name}")
except Exception:
alert_dialog = QMessageBox.information(
self,
"Error!",
f"Please check if {parent_folder}/{file_name} is not corrupt",
)
return
def main():
app = QApplication([])
app.setWindowIcon(QtGui.QIcon("res/inbox_tray_3d.ico"))
window = MyGUI()
app.exec()
if __name__ == "__main__":
main()