Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image
- from PyQt5 import QtCore, QtWidgets, uic
- from PyQt5.QtGui import QPixmap
- from file_handling import list_compressed_archive, unpack_file
- from file_handling import windows_unrar_extractall
- from os import listdir
- from os.path import isfile, join
- from tricks import DB, Worker, sqliteconnection, sqlitecursor, tech
- from zipfile import BadZipFile, ZipFile
- import os
- import pathlib
- import platform
- import rarfile
- import shutil
- import tempfile
- import time
- class BulkCompresser(QtWidgets.QWidget):
- def __init__(self, main):
- super(BulkCompresser, self).__init__()
- uic.loadUi('./gui/bulk_compressor.ui', self)
- self.main = main
- self.parent = main
- self.threadpool = self.main.threadpool
- self.summary_covers()
- self.setWindowTitle(f'LongSnabel ComicReader bulk compressor!')
- if os.path.exists('/mnt/ramdisk') == True:
- self.tmp_folder = '/mnt/ramdisk/longsnabel_comic_reader_tmp_folder'
- else:
- self.tmp_folder = tech.fpath(f'{tempfile.gettempdir()}/longsnabel_comic_reader_tmp_folder')
- if os.path.exists(self.tmp_folder) == False:
- pathlib.Path(self.tmp_folder).mkdir(parents=True)
- self.tmp_file = tech.fpath(f'{self.tmp_folder}/longsnabel_comic_reader_tmp_file.jpg')
- self.fixed_width_list = ['3840', '1920', '1280', '1024']
- for i in self.fixed_width_list:
- self.combo_fixed_width.addItem(f'{i}')
- # TRIGGERS >
- self.pte_searchbar.textChanged.connect(self.search_comics)
- self.lw_left_side.itemPressed.connect(self.list_clicked)
- self.slider_quality.valueChanged.connect(self.slider_changed)
- self.btn_start.clicked.connect(self.start_compressing)
- self.btn_show_all.clicked.connect(self.show_all_comics)
- self.btn_soft_stop.clicked.connect(self.soft_stop_clicked)
- # TRUGGERS <
- self.slider_changed()
- self.summary = {'original': {}, 'new': {}}
- self.show_all_comics()
- self.show()
- def soft_stop_clicked(self):
- self.soft_stop = True
- def make_left_right_canvas(self):
- if 'pixmap_left' in dir(self):
- self.pixmap_left.close()
- if 'pixmap_right' in dir(self):
- self.pixmap_right.close()
- self.pixmap_left = QtWidgets.QLabel(self.canvas, lineWidth=0)
- self.pixmap_right = QtWidgets.QLabel(self.canvas, lineWidth=0)
- self.pixmap_left.setGeometry(0, 0, 0, 0)
- self.pixmap_right.setGeometry(0, 0, 0, 0)
- self.pixmap_left.show()
- self.pixmap_right.show()
- def start_compressing(self):
- """
- when pressing startbutton, if only highlighted its the only one beeing processed
- else it runs from top to bottom but halts if count exceeds spinbox, makes a list
- that is being used by threadpool thus leaving this function
- """
- self.soft_stop = False
- self.job_total = {'total_time' : time.time(), 'files_done' : 0, 'total_files' : self.spinbox_stop_after.value()}
- self.summary_covers()
- self.thread_work_que = {}
- if self.check_highlighted.isChecked() == True:
- self.start_time = time.time()
- currentrow = self.lw_left_side.currentRow()
- sqlitecursor.execute('select * from comics where id = (?)', (self.drawlist[currentrow][0],))
- self.database = sqlitecursor.fetchone()
- self.thread_work_que.update({0 : self.database})
- else:
- for count in range(self.spinbox_stop_after.value()):
- if count+1 <= len(self.drawlist):
- self.start_time = time.time()
- sqlitecursor.execute('select * from comics where id = (?)', (self.drawlist[count][0],))
- self.database = sqlitecursor.fetchone()
- self.thread_work_que.update({count : self.database})
- if self.thread_work_que != {}:
- self.thread_processing_que()
- def process_database_as_per_que(self):
- """
- unpacks the entire file into temp-folder and compress one image at
- the time, choices are JPEG or WEBP from radiobuttons, extensions happens.
- """
- self.summary = {'original':{'file_size':self.database[DB.file_size]}, 'new':{}}
- self.worklist = {}
- dummy = []
- rv = self.decompress_archive()
- if rv == False:
- return False
- all_dirs = []
- dirs = [x[0] for x in os.walk(self.tmp_folder)]
- for eachdir in dirs:
- all_dirs.append(eachdir)
- full_path = []
- for i in all_dirs:
- files = [f for f in listdir(i) if isfile(join(i, f))]
- for count in range(len(files)):
- if files[count] == 'thumbs.db':
- os.remove(f"{i}/{files[count]}")
- else:
- full_path.append(f"{i}/{files[count]}")
- extensionlist = ['png', 'jpg', 'bmp', 'gif', 'jpeg']
- for count, eachfile in enumerate(full_path):
- if eachfile[-1] != '/' and eachfile[eachfile.rfind('.')+1:].lower() in extensionlist:
- dummy.append(eachfile)
- dummy.sort()
- for count, eachfile in enumerate(dummy):
- if os.path.getsize(eachfile) == 0:
- os.remove(eachfile)
- else:
- self.worklist.update({count:tech.fpath(eachfile)})
- if self.worklist == {}:
- del self.worklist
- def thread_processing_que(self):
- """
- starting here worklist should be deleted from self, each file from thread_work_que is unpacked
- removed from threadlist and put to work in thread. once worklist is empty a summary function
- is called removing worklist and restaring all over
- :return: is called once thread_work_que is empty
- """
- if 'worklist' in dir(self) and self.worklist == {}:
- recompress_time = time.time()
- self.recompress_archive()
- self.replace_old_file_with_compressed()
- self.show_summary()
- recompress_time = time.time() - recompress_time
- text = self.summary_label.text()
- text = text + f'Re-pack time: {round(recompress_time, 2)}s'
- self.summary_label.setText(text)
- self.start_time = time.time()
- if len(self.lw_left_side) > 0:
- self.job_total['files_done'] += 1
- self.lw_left_side.takeItem(0)
- self.lw_left_side.setCurrentRow(0)
- self.spinbox_stop_after.setValue(self.spinbox_stop_after.value() -1)
- del self.worklist
- if 'worklist' not in dir(self):
- if self.thread_work_que == {} or self.soft_stop == True:
- return
- for count, database in self.thread_work_que.items():
- self.count = count
- self.database = database
- self.set_previews()
- rv = self.process_database_as_per_que()
- self.thread_work_que.pop(count)
- if rv == False:
- self.thread_processing_que()
- break
- self.thread_processing_que_background()
- thread = Worker(self.dummy)
- thread.signals.finished.connect(self.thread_processing_que)
- self.threadpool.start(thread)
- def dummy(self):
- if 'dummy_status' not in dir(self) or self.dummy_status['current'] != self.database[0]:
- self.dummy_status = {'current':self.database[0], 'unpack_time': time.time() - self.start_time}
- try: self.dummy_status['files_done'] +=1
- except KeyError: self.dummy_status['files_done'] = 1
- try: self.dummy_status['file_times'] += time.time() - self.file_time
- except KeyError: self.dummy_status['file_times'] = time.time() - self.file_time
- que_left = len(self.worklist)
- time_per_file = self.dummy_status['file_times'] / self.dummy_status['files_done']
- time_left = time_per_file * que_left
- unpack_time = self.dummy_status["unpack_time"]
- saved_size = 0
- for i in self.summary['new']:
- if type(i) == int:
- old = self.summary['original'][i]['file_size']
- new = self.summary['new'][i]['file_size']
- saved_size += old - new
- partz = f'Files done: {self.job_total["files_done"]} / {self.job_total["total_files"]}\n'
- part0 = f'Current: {round(time.time() - self.start_time, 2)}s / {round((time.time() - self.job_total["total_time"]) / 60)}min\n'
- part1 = f'Files left: {que_left} / {que_left + self.dummy_status["files_done"]}\n'
- part2 = f'Time left: {round(time_left, 2)}s\n'
- part3 = f'Average time: {round(time_per_file, 2)}s\n'
- part4 = f'Space saved: {round(saved_size /1000000, 2)}mb\n'
- part5 = f'Unpack time: {round(unpack_time, 2)}s\n'
- self.summary_label.setText(partz + part0 + part1 + part2 + part3 + part4 + part5)
- def thread_processing_que_background(self):
- """
- if conversion has failed, old file is kept
- # TODO: you need to write more stuff here
- """
- for count, eachfile in self.worklist.items():
- self.file_time = time.time()
- self.compress_image(image_path=eachfile, count=count)
- if os.path.exists(self.tmp_file) == True:
- try: os.remove(eachfile)
- except PermissionError:
- os.chmod(eachfile[0:eachfile.rfind('/')], 0o777)
- os.chmod(eachfile, 0o777)
- os.remove(eachfile)
- if self.radio_jpeg.isChecked() == True:
- os.rename(self.tmp_file, eachfile)
- else:
- eachfile = f"{eachfile[0:eachfile.rfind('.')]}.webp"
- os.rename(self.tmp_file, eachfile)
- summary_cover = CompressSummaryCover(
- self.canvas,
- parent = self,
- count = count,
- summary = self.summary,
- image_path = eachfile,
- show_preview= self.check_show_previews.isChecked()
- )
- self.my_summary_covers.append(summary_cover)
- self.worklist.pop(count)
- break
- def slider_changed(self):
- self.spinbox_quality.setValue(self.slider_quality.value())
- def list_clicked(self):
- """
- clicking the list it draws the first image on left side and
- draws same image but compressed at right side
- """
- self.count = 0
- self.start_time = time.time()
- self.summary_covers()
- currentrow = self.lw_left_side.currentRow()
- sqlitecursor.execute('select * from comics where id = (?)', (self.drawlist[currentrow][0],))
- self.database = sqlitecursor.fetchone()
- self.summary = {'original': {'file_size': self.database[DB.file_size]}, 'new': {}}
- self.set_previews()
- self.show_summary()
- def set_previews(self):
- """
- destroys current images and draws new ones
- """
- self.make_left_right_canvas()
- lister = list_compressed_archive(self.database)
- unpack_file(self.database, 0)
- sqlitecursor.execute('select * from comics where id = (?)', (self.database[0],))
- self.database = sqlitecursor.fetchone()
- cdef str orginal_image = lister.final_location[0]
- cdef int width = (self.canvas.width() / 2) - 303
- self.file_time = time.time()
- self.compress_image(image_path=orginal_image, count=0)
- self.org_pixmap = QPixmap(orginal_image).scaledToWidth(width, QtCore.Qt.SmoothTransformation)
- if self.org_pixmap.height() > self.canvas.height():
- self.org_pixmap = QPixmap(orginal_image).scaledToHeight(self.canvas.height(), QtCore.Qt.SmoothTransformation)
- self.tmp_pixmap = QPixmap(self.tmp_file).scaledToHeight(self.canvas.height(), QtCore.Qt.SmoothTransformation)
- else:
- self.tmp_pixmap = QPixmap(self.tmp_file).scaledToWidth(width, QtCore.Qt.SmoothTransformation)
- self.pixmap_left.setGeometry(
- 0,
- 0,
- self.org_pixmap.width(),
- self.org_pixmap.height()
- )
- self.pixmap_right.setGeometry(
- self.org_pixmap.width() + 6,
- 0,
- self.tmp_pixmap.width(),
- self.tmp_pixmap.height()
- )
- self.pixmap_left.setPixmap(self.org_pixmap)
- self.pixmap_right.setPixmap(self.tmp_pixmap)
- def compress_image(self, **kwargs):
- """
- processes each image here, if size are larger than the one in the combobox
- if checkbox is checked, the image is resized before beeing processed
- :param kwargs: count (for summary purposes only)
- :param kwargs: image_path
- """
- image_path = kwargs['image_path']
- count = kwargs['count']
- image = Image.open(image_path)
- self.summary['original'].update({count:{'file_size':os.path.getsize(image_path), 'pixmap':image.size}})
- if self.check_fixed_width.isChecked() == True and self.combo_fixed_width.currentText().isdigit() == True:
- fixed_width = int(self.combo_fixed_width.currentText())
- if image.size[0] > fixed_width:
- image_size = fixed_width, round(image.size[1] * (fixed_width / image.size[0]))
- image.thumbnail(image_size, Image.ANTIALIAS)
- try:
- if self.radio_jpeg.isChecked() == True:
- image.save(self.tmp_file, method=self.spinbox_webp_method.value(), optimize=self.check_optimize.isChecked(), quality=int(self.spinbox_quality.value()))
- else:
- image.save(self.tmp_file, 'webp', method=self.spinbox_webp_method.value(), optimize=self.check_optimize.isChecked(), quality=int(self.spinbox_quality.value()))
- self.summary['new'].update({count: {'file_size': os.path.getsize(self.tmp_file), 'pixmap': image.size, 'time':time.time() - self.file_time}})
- except OSError:
- if os.path.exists(self.tmp_file) == True:
- os.remove(self.tmp_file)
- def decompress_archive(self):
- archive = tech.fpath(self.database[DB.local_path])
- shutil.rmtree(self.tmp_folder)
- try:
- comp = ZipFile(archive)
- except BadZipFile:
- try:
- comp = rarfile.RarFile(archive)
- if platform.system() == "Windows":
- windows_unrar_extractall(self.database, self.tmp_folder)
- return True
- except rarfile.NotRarFile:
- return False
- comp.extractall(self.tmp_folder)
- return True
- def recompress_archive(self):
- self.make_md5_file()
- self.recompressed_file = f'{tempfile.gettempdir()}/{self.database[DB.file_name][0:self.database[DB.file_name].rfind(".")]}'
- if os.path.exists(self.recompressed_file) == True:
- os.remove(self.recompressed_file)
- shutil.make_archive(self.recompressed_file, 'zip', self.tmp_folder)
- self.final_file_path = f'{self.recompressed_file}.cbz'
- self.final_file_name = f'{self.final_file_path[self.final_file_path.rfind("/")+1:]}'
- shutil.move(f'{self.recompressed_file}.zip', self.final_file_path)
- self.summary['new']['file_size'] = os.path.getsize(self.final_file_path)
- def replace_old_file_with_compressed(self):
- if os.path.exists(self.database[DB.local_path]) == True and os.path.exists(self.final_file_path) == True:
- self.new_location = f"{self.database[DB.local_path][0:self.database[DB.local_path].rfind('/')]}/{self.final_file_name}"
- os.remove(self.database[DB.local_path])
- shutil.copyfile(self.final_file_path, self.new_location)
- if os.path.exists(self.new_location) == True:
- os.remove(self.final_file_path)
- self.update_database()
- else:
- action = input(f"YOU GOT PROBLEM: I've removed {tech.color.YELLOW2}{self.database[DB.local_path]}{tech.color.END} from your computer while holding my dick with both hands!\nClear ID:{self.database[0]} from database? ")
- if action.lower() == 'y':
- with sqliteconnection:
- sqlitecursor.execute('delete from comics where id = (?)', (self.database[0],))
- action = input(f"Update database anyway and perhaps manually look into {tech.color.YELLOW2}{self.final_file_path}{tech.color.YELLOW2} supposally moved(ing) to: {tech.color.YELLOW2}{self.new_location}{tech.color.END}")
- if action.lower() == 'y':
- self.update_database()
- def update_database(self):
- with sqliteconnection:
- sqlitecursor.execute('update comics set recompressed = (?) where id = (?)', (1, self.database[0],))
- sqlitecursor.execute('update comics set filecontents = (?) where id = (?)', (None, self.database[0],))
- sqlitecursor.execute('update comics set bad_files = (?) where id = (?)', (None, self.database[0],))
- sqlitecursor.execute('update comics set contains_bad_files = (?) where id = (?)', (None, self.database[0],))
- sqlitecursor.execute('update comics set local_path = (?) where id = (?)', (self.new_location, self.database[0],))
- sqlitecursor.execute('update comics set file_name = (?) where id = (?)', (self.final_file_name, self.database[0],))
- sqlitecursor.execute('update comics set file_size = (?) where id = (?)', (os.path.getsize(self.new_location), self.database[0],))
- def make_md5_file(self):
- """
- md5hash.md5 file is beeing made, containing original filename original filesize and md5 hash.
- also comicvine id if one is present and md5+filesize for each original file
- """
- cdef list all_dirs = [], dirs, full_path = [], files
- cdef str eachdir, eachfile, file_name, current_md5 = self.database[DB.md5]
- cdef int count
- cdef dict md5dict = {}, fsize_dict = {}
- if os.path.exists(self.tmp_folder + '/' + current_md5 + '.md5') == True:
- return
- dirs = [x[0] for x in os.walk(self.tmp_folder)]
- for eachdir in dirs:
- all_dirs.append(eachdir)
- for i in all_dirs:
- files = [f for f in listdir(i) if isfile(join(i, f))]
- for count in range(len(files)):
- full_path.append(i + '/' + files[count])
- for eachfile in full_path:
- file_name = eachfile[eachfile.rfind('/')+1:]
- md5 = tech.md5_hash(eachfile)
- md5dict[md5] = file_name
- fsize_dict[md5] = os.path.getsize(eachfile)
- md5dict = {k: v for k, v in sorted(md5dict.items(), key=lambda item: item[1])}
- if current_md5.find('[!FAKE]') != -1: # file needs to be rehashed
- current_md5 = tech.md5_hash(self.database[DB.local_path])
- with open(self.tmp_folder + '/' + current_md5 + '.md5', 'w') as crc_file:
- crc_file.write('; original md5: ' + current_md5 + '\n')
- crc_file.write('; original filesize in bytes: ' + str(self.database[DB.file_size]) + '\n')
- crc_file.write('; original filename: ' + self.database[DB.file_name] + '\n')
- if self.database[DB.comic_id] != None:
- crc_file.write('; comicvine id: ' + str(self.database[DB.comic_id]) + '\n')
- for md5, file_name in md5dict.items():
- crc_file.write(md5 + ':' + str(fsize_dict[md5]) + ':' + file_name + '\n')
- def show_all_comics(self):
- sqlitecursor.execute('select * from comics where recompressed is not 1')
- self.all_comics = sqlitecursor.fetchall()
- if self.all_comics == []:
- self.main.status_bar.showMessage('NO COMICS FOUND!')
- return
- self.all_comics = tech.uni_sort(self.main, self.all_comics)
- self.all_comics.sort(key=lambda x:x[DB.file_size], reverse=True)
- self.summary_label.setText(str(len(self.all_comics)) + ' still uncompressed')
- self.drawlist = self.all_comics
- self.draw_left_list()
- def set_specific_comic(self, dbinput):
- self.drawlist = [dbinput]
- self.draw_left_list(dbinput)
- self.lw_left_side.setCurrentRow(0)
- self.list_clicked()
- def draw_left_list(self, dbinput=None):
- self.lw_left_side.clear()
- if dbinput == None:
- for count in range(len(self.drawlist)-1,-1,-1):
- if self.check_linked_only.isChecked() == True and self.drawlist[count][DB.comic_id] == None:
- self.drawlist.pop(count)
- for i in self.drawlist:
- file_size = i[DB.file_size] / 1000000
- self.lw_left_side.addItem(f'{round(file_size)}mb {i[DB.file_name][0:-3]}')
- self.spinbox_stop_after.setValue(len(self.drawlist))
- def search_comics(self):
- text = self.pte_searchbar.toPlainText()
- if len(text) < 3:
- return
- self.drawlist = tech.uni_search(self.all_comics, text, DB.file_name)
- self.drawlist.sort(key=lambda x:x[DB.file_size], reverse=True) # makes sence to show largest files first
- self.draw_left_list()
- def show_summary(self):
- if self.count not in self.summary['new']:
- return
- total_pages = self.database[DB.filecontents].split('\n')
- self.total_pages = SummaryLabel(
- self.pixmap_left,
- text=f"Number of pages {len(total_pages)}",
- stylesheet='background-color: rgba(1, 100, 162, 225) ; color: rgb(255, 255, 255) ; font: 12pt',
- height_factor=5
- )
- self.org_file_size = SummaryLabel(
- self.pixmap_left,
- text=f"File size {round(self.summary['original']['file_size']/1000000, 2)}mb",
- height_factor=3
- )
- self.org_image_size = SummaryLabel(
- self.pixmap_left,
- text=f"Preview image {round(self.summary['original'][self.count]['file_size']/1000000, 2)}mb",
- height_factor=2
- )
- self.org_pixmap_dm = SummaryLabel(
- self.pixmap_left,
- text=f"Dimensions {self.summary['original'][self.count]['pixmap'][0]} x {self.summary['original'][self.count]['pixmap'][1]}",
- height_factor=1
- )
- if 'file_size' in self.summary['new']:
- file_size = f"File size {round(self.summary['new']['file_size'] / 1000000, 2)}mb"
- space_saved = self.summary['original']['file_size'] - self.summary['new']['file_size']
- percent_saved = self.summary['new']['file_size'] / self.summary['original']['file_size']
- else:
- factor = self.summary['new'][self.count]['file_size'] / self.summary['original'][self.count]['file_size']
- file_size = f"Estemated file size {round(self.summary['original']['file_size'] * factor / 1000000, 2)}mb"
- space_saved = self.summary['original']['file_size'] - (self.summary['original']['file_size'] * factor)
- percent_saved = factor
- self.new_file_size = SummaryLabel(
- self.pixmap_right,
- text=file_size,
- height_factor=3
- )
- self.new_image_size = SummaryLabel(
- self.pixmap_right,
- text=f"Preview image {round(self.summary['new'][self.count]['file_size']/1000000, 2)}mb",
- height_factor=2
- )
- self.new_pixmap_dm = SummaryLabel(
- self.pixmap_right,
- text=f"Dimensions {self.summary['new'][self.count]['pixmap'][0]} x {self.summary['new'][self.count]['pixmap'][1]}",
- height_factor=1
- )
- self.saved_label = SummaryLabel(
- self.pixmap_right,
- text=f"SAVING {round(space_saved/1000000)}mb ({round((1 - percent_saved) * 100)}%)",
- stylesheet='background-color: rgba(165, 0, 0, 225); color: rgb(255, 255, 255) ; font: 20pt',
- height_factor=4
- )
- self.time_label = SummaryLabel(
- self.pixmap_right,
- text=f"CPU time {round(time.time() - self.start_time, 2)}s",
- stylesheet='background-color: rgba(1, 100, 162, 225) ; color: rgb(255, 255, 255) ; font: 12pt',
- height_factor=5
- )
- cycle = [[self.org_image_size, self.org_file_size, self.org_pixmap_dm],[self.new_image_size, self.new_file_size, self.new_pixmap_dm]]
- for eachlist in cycle:
- width = 0
- for i in eachlist:
- if i.width() > width:
- width = i.width()
- for i in eachlist:
- i.setFixedWidth(width)
- def summary_covers(self):
- if 'my_summary_covers' not in dir(self):
- self.my_summary_covers = []
- else:
- for i in self.my_summary_covers:
- i.close()
- self.my_summary_covers = []
- class SummaryLabel(QtWidgets.QLabel):
- def __init__(self, place, **kwargs):
- super(SummaryLabel, self).__init__(place)
- self.setText(f" {kwargs['text']} ")
- if 'stylesheet' in kwargs:
- stylesheet = kwargs['stylesheet']
- else:
- stylesheet = 'background-color: rgba(20, 20, 20, 225); color: rgb(255, 255, 255) ; font: 20pt'
- self.setStyleSheet(stylesheet)
- self.move(0, int(place.height() - ((self.height() + 15) * kwargs['height_factor'])))
- self.show()
- class CompressSummaryCover(QtWidgets.QFrame):
- def __init__(self, place, **kwargs):
- super(CompressSummaryCover, self).__init__(place)
- self.parent = kwargs['parent']
- self.summary = kwargs['summary']
- self.who_am_i = kwargs['count']
- self.offset = self.parent.pixmap_left.width() + self.parent.pixmap_right.width() + (6)
- self.my_width = place.width() - self.offset
- self.my_height = int(tech.icon_size()['height'] * 0.6)
- self.resize(self.my_width, self.my_height)
- self.move(self.offset, 0)
- if kwargs['show_preview'] == True:
- self.image_path = tech.fpath(kwargs['image_path'])
- self.pixmap = QPixmap(self.image_path).scaledToHeight(self.height(), QtCore.Qt.SmoothTransformation)
- if self.pixmap.width() > place.width():
- self.pixmap = QPixmap(self.image_path).scaled(place.width(), self.height(), transformMode=QtCore.Qt.SmoothTransformation)
- self.cover = QtWidgets.QLabel(self, styleSheet='background-color: white')
- self.cover.setPixmap(self.pixmap)
- self.cover.setGeometry(0, 0, self.pixmap.width(), self.pixmap.height())
- else:
- self.cover = QtWidgets.QLabel(self, styleSheet='background-color: black ; color: white', text='PREVIEW DISABLED')
- self.cover.setGeometry(0,0,int(self.height() * 0.7), self.height())
- self.status_plate()
- for count in range(len(self.parent.my_summary_covers)-1,-1,-1):
- widget = self.parent.my_summary_covers[count]
- widget.move(self.offset, widget.geometry().bottom() + 3)
- if widget.geometry().bottom() > place.height():
- widget.close()
- self.parent.my_summary_covers.pop(count)
- self.show()
- def status_plate(self):
- pre_size = f'{round(self.summary["original"][self.who_am_i]["file_size"] / 1000)}kb'
- post_size = f'{round(self.summary["new"][self.who_am_i]["file_size"] / 1000)}kb'
- ratio = self.summary["new"][self.who_am_i]["file_size"] / self.summary["original"][self.who_am_i]["file_size"]
- time = self.summary["new"][self.who_am_i]["time"]
- sum_time = {'max_time' : 0, 'all_time' : 0, 'count' : 0, 'low_time' : time, 'average' : 0}
- for i in self.summary['new']:
- thistime = self.summary['new'][i]['time']
- sum_time['all_time'] += thistime
- sum_time['count'] += 1
- if thistime > sum_time['max_time']:
- sum_time['max_time'] = thistime
- if thistime < sum_time['low_time']:
- sum_time['low_time'] = thistime
- sum_time['average'] = sum_time['all_time'] / sum_time['count']
- cdef float time_ratio = time * (0.6 / sum_time['average'])
- self.label_pre_size = QtWidgets.QLabel(self, text=f'OLD Size: {pre_size}', styleSheet='background-color: rgba(67, 132, 0, 175) ; color: rgb(0,0,0) ; font: 12pt')
- self.label_pre_size.resize(self.width() - self.cover.width(), self.label_pre_size.height())
- self.label_post_size = QtWidgets.QLabel(self, text=f'{post_size}', styleSheet='background-color: rgba(68, 255, 0, 255) ; color: rgb(0,0,0) ; font: 12pt')
- self.label_post_size.resize(int(self.label_pre_size.width() * ratio), self.label_post_size.height())
- self.label_pre_size.move(self.cover.width(), self.cover.height() - self.label_pre_size.height() - 3)
- self.label_post_size.move(self.cover.width(), self.cover.height() - self.label_pre_size.height() - self.label_post_size.height() - 6)
- pre_image = f'{self.summary["original"][self.who_am_i]["pixmap"][0]} x {self.summary["original"][self.who_am_i]["pixmap"][1]}'
- post_image = f'{self.summary["new"][self.who_am_i]["pixmap"][0]} x {self.summary["new"][self.who_am_i]["pixmap"][1]}'
- pixmap_ratio = self.summary["original"][self.who_am_i]["pixmap"][0] / self.summary["new"][self.who_am_i]["pixmap"][0]
- self.label_time = QtWidgets.QLabel(self, text=f'CPU time: {round(time, 2)}s', styleSheet='background-color: rgba(255, 128, 0, 200) ; color: rgb(255, 255, 255) ; font: 12pt')
- self.label_time.resize(int(self.label_pre_size.width() * time_ratio), self.label_time.height())
- self.pre_pixmap = QtWidgets.QLabel(self, text=f'Before:\t{pre_image}', styleSheet='background-color: rgba(1, 100, 162, 200)')
- self.pre_pixmap.resize(self.width() - self.cover.width(), self.pre_pixmap.height())
- self.post_pixmap = QtWidgets.QLabel(self, text=f'After:\t{post_image}', styleSheet='background-color: rgba(1, 100, 162, 200)')
- self.post_pixmap.resize(int(self.pre_pixmap.width() * pixmap_ratio), self.post_pixmap.height())
- self.label_time.move(self.cover.width(), 3)
- self.pre_pixmap.move(self.cover.width(), self.label_time.height() + 5)
- self.post_pixmap.move(self.cover.width(), self.label_time.height() + self.pre_pixmap.height() + 9)
- from_top = self.post_pixmap.geometry().bottom()
- from_bottom = self.label_post_size.geometry().top()
- self.percentlabel = QtWidgets.QLabel(self, styleSheet='color: rgb(255, 255, 255) ; font: 64pt', lineWidth=0, text=f'{round((1 - ratio) * 100)}%', alignment=QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
- self.percentlabel.setGeometry(self.cover.width(), from_top + 3, self.label_pre_size.width(), from_bottom - from_top - 6)
Add Comment
Please, Sign In to add comment