From 76c7cdbb1b3037723e341d798b181efa96f5e3b9 Mon Sep 17 00:00:00 2001 From: laggykiller Date: Tue, 3 Oct 2023 01:21:48 +0800 Subject: [PATCH] Reduce code smells --- Dockerfile | 4 +- compile.py | 10 +- scripts/opt-comp-experiment.py | 4 +- src/sticker_convert/auth/get_signal_auth.py | 10 +- src/sticker_convert/cli.py | 8 +- .../downloaders/download_kakao.py | 2 +- .../downloaders/download_line.py | 5 +- .../gui_frames/progress_frame.py | 4 - .../gui_windows/line_get_auth_window.py | 2 +- .../uploaders/upload_signal.py | 2 +- .../uploaders/xcode_imessage.py | 12 +-- .../utils/apple_png_normalize.py | 102 +++++++++--------- 12 files changed, 81 insertions(+), 84 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6618f3d..bbb760c 100755 --- a/Dockerfile +++ b/Dockerfile @@ -60,13 +60,13 @@ RUN chmod -R 777 /app VOLUME ["/app/stickers_input", "/app/stickers_output"] -FROM base-gui as min-gui +FROM base-gui AS min-gui RUN apt purge -y curl wget gpg git && \ apt clean autoclean && \ apt autoremove --yes && \ rm -rf /var/lib/{apt,dpkg,cache,log}/ -FROM base-gui as full +FROM base-gui AS full # Install signal-desktop-beta RUN wget -O- https://updates.signal.org/desktop/apt/keys.asc | gpg --dearmor > signal-desktop-keyring.gpg && \ cat signal-desktop-keyring.gpg | tee -a /usr/share/keyrings/signal-desktop-keyring.gpg > /dev/null && \ diff --git a/compile.py b/compile.py index 8a15441..9f173c5 100755 --- a/compile.py +++ b/compile.py @@ -73,7 +73,7 @@ def osx_install_universal2_dep(): osx_run_in_venv('python -m pip download --require-virtualenv -r requirements.txt --platform macosx_11_0_x86_64 --only-binary=:all: -d wheel_x64') create_universal_wheels('./wheel_arm', './wheel_x64', 'wheel_universal2') - osx_run_in_venv(f'python -m pip install --require-virtualenv ./wheel_universal2/*') + osx_run_in_venv('python -m pip install --require-virtualenv ./wheel_universal2/*') def nuitka(python_bin, arch): cmd_list = [ @@ -99,7 +99,7 @@ def nuitka(python_bin, arch): cmd_list.append('--windows-icon-from-ico=src/sticker_convert/resources/appicon.ico') elif platform.system() == 'Darwin' and arch: cmd_list.append(f'--macos-target-arch={arch}') - cmd_list.append(f'--disable-console') + cmd_list.append('--disable-console') cmd_list.append('src/sticker-convert.py') if platform.system() == 'Darwin': @@ -122,7 +122,7 @@ def osx_patch(): f.write('open ./sticker-convert-cli') os.chmod('sticker-convert.app/Contents/MacOS/sticker-convert', 0o744) - osx_run_in_venv(f'codesign --force --deep -s - sticker-convert.app') + osx_run_in_venv('codesign --force --deep -s - sticker-convert.app') def compile(): arch = os.environ.get('SC_COMPILE_ARCH') @@ -153,8 +153,8 @@ def compile(): if platform.system() == 'Windows': win_patch() - elif platform.system() == 'Darwin' and arch: - osx_patch() + # elif platform.system() == 'Darwin': + # osx_patch() if __name__ == '__main__': compile() \ No newline at end of file diff --git a/scripts/opt-comp-experiment.py b/scripts/opt-comp-experiment.py index 1f165d9..61da4c7 100755 --- a/scripts/opt-comp-experiment.py +++ b/scripts/opt-comp-experiment.py @@ -75,7 +75,7 @@ def put(self, msg: str): def generate_random_apng(res: int, fps: float, duration: float, out_f: str): apngasm = APNGAsm() - for i in range(int(duration/1000*fps)): + for _ in range(int(duration/1000*fps)): im = numpy.random.rand(res, res, 4) * 255 frame = create_frame_from_rgba(im, res, res) frame.delay_num = int(1000 / fps) @@ -171,7 +171,7 @@ def main(): Thread(target=write_result, args=(csv_path, results_queue, len(combinations))).start() processes = [] - for i in range(processes_max): + for _ in range(processes_max): process = Process( target=compress_worker, args=(jobs_queue, results_queue) diff --git a/src/sticker_convert/auth/get_signal_auth.py b/src/sticker_convert/auth/get_signal_auth.py index 061b791..cde7516 100755 --- a/src/sticker_convert/auth/get_signal_auth.py +++ b/src/sticker_convert/auth/get_signal_auth.py @@ -60,7 +60,9 @@ def download_signal_desktop(self, download_url: str, signal_bin_path: str): self.cb_msg(download_url) - prompt = f'Signal Desktop not detected.\nDownload and install Signal Desktop BETA version\nAfter installation, quit Signal Desktop before continuing' + prompt = 'Signal Desktop not detected.\n' + prompt += 'Download and install Signal Desktop BETA version\n' + prompt += 'After installation, quit Signal Desktop before continuing' while not (os.path.isfile(signal_bin_path) or shutil.which(signal_bin_path)): if self.cb_ask_str != input: self.cb_ask_str(prompt, initialvalue=download_url, cli_show_initialvalue=False) @@ -154,7 +156,7 @@ def download_chromedriver(self, major_version: str, chromedriver_download_dir: s with zipfile.ZipFile(f, 'r') as z, open(chromedriver_path, 'wb+') as g: g.write(z.read(chromedriver_zip_path)) - if not platform.system() == 'Windows': + if platform.system() != 'Windows': st = os.stat(chromedriver_path) os.chmod(chromedriver_path, st.st_mode | stat.S_IEXEC) @@ -187,7 +189,7 @@ def get_cred(self) -> tuple[Optional[str], Optional[str]]: else: uuid = str(self.driver.execute_script('return window.SignalDebug.getReduxState().items.uuid_id')) password = str(self.driver.execute_script('return window.SignalDebug.getReduxState().items.password')) - except JavascriptException as e: + except JavascriptException: pass return uuid, password @@ -241,7 +243,7 @@ def launch_signal_desktop(self): if major_version: self.cb_msg(f'Signal Desktop is using chrome version {major_version}') else: - self.cb_msg(f'Unable to determine Signal Desktop chrome version') + self.cb_msg('Unable to determine Signal Desktop chrome version') return chromedriver_path, local_chromedriver_version = self.get_local_chromedriver(chromedriver_download_dir=self.chromedriver_download_dir) diff --git a/src/sticker_convert/cli.py b/src/sticker_convert/cli.py index 6ca675d..f538f2f 100755 --- a/src/sticker_convert/cli.py +++ b/src/sticker_convert/cli.py @@ -34,7 +34,7 @@ def cli(self): parser = argparse.ArgumentParser(description='CLI for stickers-convert', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--version', action='version', version=__version__) - parser.add_argument(f'--no-confirm', dest='no_confirm', action='store_true', help=self.help['global']['no_confirm']) + parser.add_argument('--no-confirm', dest='no_confirm', action='store_true', help=self.help['global']['no_confirm']) parser_input = parser.add_argument_group('Input options') for k, v in self.help['input'].items(): @@ -176,7 +176,7 @@ def get_opt_comp(self, args): if output_option == 'local': preset = 'custom' args.no_compress = True - self.cb_msg(f'Auto compression option set to no_compress (Reason: Export to local directory only)') + self.cb_msg('Auto compression option set to no_compress (Reason: Export to local directory only)') elif output_option == 'imessage': preset = 'imessage_small' self.cb_msg(f'Auto compression option set to {preset}') @@ -288,9 +288,9 @@ def get_opt_cred(self, args): if line_cookies: self.opt_cred['line']['cookies'] = line_cookies - self.cb_msg(f'Got Line cookies successfully') + self.cb_msg('Got Line cookies successfully') else: - self.cb_msg(f'Failed to get Line cookies. Have you logged in the web browser?') + self.cb_msg('Failed to get Line cookies. Have you logged in the web browser?') if args.save_cred: creds_path = os.path.join(CurrDir.get_config_dir(), 'creds.json') diff --git a/src/sticker_convert/downloaders/download_kakao.py b/src/sticker_convert/downloaders/download_kakao.py index b8aa485..3d4e845 100755 --- a/src/sticker_convert/downloaders/download_kakao.py +++ b/src/sticker_convert/downloaders/download_kakao.py @@ -241,7 +241,7 @@ def download_animated(self, item_code: str) -> bool: num = 0 with zipfile.ZipFile(io.BytesIO(zip_file)) as zf: - self.cb_msg(f'Unzipping...') + self.cb_msg('Unzipping...') if self.cb_bar: self.cb_bar(set_progress_mode='determinate', steps=len(zf.namelist())) diff --git a/src/sticker_convert/downloaders/download_line.py b/src/sticker_convert/downloaders/download_line.py index ebc000b..f2550c2 100755 --- a/src/sticker_convert/downloaders/download_line.py +++ b/src/sticker_convert/downloaders/download_line.py @@ -34,7 +34,6 @@ def analyze_url(url: str) -> Optional[tuple[str, str, bool]]: pack_id = url.replace('https://line.me/S/sticker/', '').split('/')[0] region = parse.parse_qs(url_parsed.query)['lang'][0] elif url.startswith('https://store.line.me/officialaccount/event/sticker/'): - url_parsed = parse.urlparse(url) pack_id = url.replace('https://store.line.me/officialaccount/event/sticker/', '').split('/')[0] region = url.replace('https://store.line.me/officialaccount/event/sticker/', '').split('/')[1] elif url.startswith('https://store.line.me/emojishop/product/'): @@ -178,7 +177,7 @@ def get_pack_url(self) -> str: def decompress_emoticon(self, zip_file: bytes): num = 0 with zipfile.ZipFile(io.BytesIO(zip_file)) as zf: - self.cb_msg(f'Unzipping...') + self.cb_msg('Unzipping...') self.cb_bar(set_progress_mode='determinate', steps=len(self.pack_files)) for sticker in self.pack_files: @@ -201,7 +200,7 @@ def decompress_emoticon(self, zip_file: bytes): def decompress_stickers(self, zip_file: bytes): num = 0 with zipfile.ZipFile(io.BytesIO(zip_file)) as zf: - self.cb_msg(f'Unzipping...') + self.cb_msg('Unzipping...') self.cb_bar(set_progress_mode='determinate', steps=len(self.pack_files)) for sticker in self.pack_files: diff --git a/src/sticker_convert/gui_frames/progress_frame.py b/src/sticker_convert/gui_frames/progress_frame.py index 43c7849..c0abc11 100644 --- a/src/sticker_convert/gui_frames/progress_frame.py +++ b/src/sticker_convert/gui_frames/progress_frame.py @@ -57,8 +57,6 @@ def update_message_box(self, *args, **kwargs): msg = kwargs.get('msg') cls = kwargs.get('cls') - # scrollbar_prev_loc = self.message_box.yview()[1] - if not msg and len(args) == 1: msg = str(args[0]) @@ -77,8 +75,6 @@ def update_message_box(self, *args, **kwargs): if msg: self.message_box.insert('end', msg) - # Follow the end of the box if it was at the end - # if scrollbar_prev_loc == 1.0: if self.auto_scroll: self.message_box._text.yview_moveto(1.0) diff --git a/src/sticker_convert/gui_windows/line_get_auth_window.py b/src/sticker_convert/gui_windows/line_get_auth_window.py index 0f7de64..c0e2361 100644 --- a/src/sticker_convert/gui_windows/line_get_auth_window.py +++ b/src/sticker_convert/gui_windows/line_get_auth_window.py @@ -60,7 +60,7 @@ def cb_get_cookies_thread(self, *args): self.gui.creds['line']['cookies'] = line_cookies self.gui.line_cookies_var.set(line_cookies) - self.cb_msg_block_line(f'Got Line cookies successfully') + self.cb_msg_block_line('Got Line cookies successfully') self.gui.save_creds() self.gui.highlight_fields() return diff --git a/src/sticker_convert/uploaders/upload_signal.py b/src/sticker_convert/uploaders/upload_signal.py index 6ca7282..9d6bc2b 100755 --- a/src/sticker_convert/uploaders/upload_signal.py +++ b/src/sticker_convert/uploaders/upload_signal.py @@ -105,7 +105,7 @@ def upload_stickers_signal(self) -> list[str]: msg_block = 'emoji.txt is required for uploading signal stickers\n' msg_block += f'emoji.txt generated for you in {self.in_dir}\n' msg_block += f'Default emoji is set to {self.opt_comp.get("default_emoji")}.\n' - msg_block += f'Please edit emoji.txt now, then continue' + msg_block += 'Please edit emoji.txt now, then continue' MetadataHandler.generate_emoji_file(dir=self.in_dir, default_emoji=self.opt_comp.get("default_emoji")) self.cb_msg_block(msg_block) diff --git a/src/sticker_convert/uploaders/xcode_imessage.py b/src/sticker_convert/uploaders/xcode_imessage.py index 48dbb76..cec7f87 100755 --- a/src/sticker_convert/uploaders/xcode_imessage.py +++ b/src/sticker_convert/uploaders/xcode_imessage.py @@ -217,7 +217,7 @@ def create_xcode_proj(self, author: str, title: str): # packname StickerPackExtension/Stickers.xcstickers/Sticker Pack.stickerpack/0.sticker/0.png shutil.copy(os.path.join(self.in_dir, i), os.path.join(sticker_path, i)) - dict = { + json_content = { 'info': { 'author': 'xcode', 'version': 1, @@ -229,18 +229,18 @@ def create_xcode_proj(self, author: str, title: str): # packname StickerPackExtension/Stickers.xcstickers/Sticker Pack.stickerpack/0.sticker/Contents.json with open(os.path.join(sticker_path, 'Contents.json'), 'w+') as f: - json.dump(dict, f, indent=2) + json.dump(json_content, f, indent=2) # packname StickerPackExtension/Stickers.xcstickers/Sticker Pack.stickerpack/Contents.json with open(os.path.join(stickers_path, 'Contents.json')) as f: - dict = json.load(f) + json_content = json.load(f) - dict['stickers'] = [] + json_content['stickers'] = [] for i in stickers_lst: - dict['stickers'].append({'filename': i}) # type: ignore[attr-defined] + json_content['stickers'].append({'filename': i}) # type: ignore[attr-defined] with open(os.path.join(stickers_path, 'Contents.json'), 'w+') as f: - json.dump(dict, f, indent=2) + json.dump(json_content, f, indent=2) # packname StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset iconset_path = os.path.join(pack_path, 'stickers StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset') diff --git a/src/sticker_convert/utils/apple_png_normalize.py b/src/sticker_convert/utils/apple_png_normalize.py index 8b2a3b4..d9abd03 100755 --- a/src/sticker_convert/utils/apple_png_normalize.py +++ b/src/sticker_convert/utils/apple_png_normalize.py @@ -8,85 +8,85 @@ class ApplePngNormalize: @staticmethod - def normalize(oldPNG: bytes) -> bytes: - pngheader = b"\x89PNG\r\n\x1a\n" + def normalize(old_png: bytes) -> bytes: + png_header = b"\x89PNG\r\n\x1a\n" - if oldPNG[:8] != pngheader: - return oldPNG + if old_png[:8] != png_header: + return old_png - newPNG = oldPNG[:8] + new_png = old_png[:8] - chunkPos = len(newPNG) - chunkD = bytearray() + chunk_pos = len(new_png) + chunk_d = bytearray() - foundCGBi = False + found_cgbi = False # For each chunk in the PNG file - while chunkPos < len(oldPNG): + while chunk_pos < len(old_png): # Reading chunk - chunkLength = oldPNG[chunkPos:chunkPos+4] - chunkLength = struct.unpack(">L", chunkLength)[0] - chunkType = oldPNG[chunkPos+4 : chunkPos+8] - chunkData = oldPNG[chunkPos+8:chunkPos+8+chunkLength] # type: ignore[operator] - chunkCRC = oldPNG[chunkPos+chunkLength+8:chunkPos+chunkLength+12] # type: ignore[operator] - chunkCRC = struct.unpack(">L", chunkCRC)[0] - chunkPos += chunkLength + 12 # type: ignore[operator] + chunk_length = old_png[chunk_pos:chunk_pos+4] + chunk_length = struct.unpack(">L", chunk_length)[0] + chunk_type = old_png[chunk_pos+4 : chunk_pos+8] + chunk_data = old_png[chunk_pos+8:chunk_pos+8+chunk_length] # type: ignore[operator] + chunk_crc = old_png[chunk_pos+chunk_length+8:chunk_pos+chunk_length+12] # type: ignore[operator] + chunk_crc = struct.unpack(">L", chunk_crc)[0] + chunk_pos += chunk_length + 12 # type: ignore[operator] # Parsing the header chunk - if chunkType == b"IHDR": - width = struct.unpack(">L", chunkData[0:4])[0] - height = struct.unpack(">L", chunkData[4:8])[0] + if chunk_type == b"IHDR": + width = struct.unpack(">L", chunk_data[0:4])[0] + height = struct.unpack(">L", chunk_data[4:8])[0] # Parsing the image chunk - if chunkType == b"IDAT": + if chunk_type == b"IDAT": # Concatename all image data chunks - chunkD += chunkData + chunk_d += chunk_data continue # Stopping the PNG file parsing - if chunkType == b"IEND": - if not foundCGBi: - return oldPNG + if chunk_type == b"IEND": + if not found_cgbi: + return old_png bufSize = width * height * 4 + height - chunkData = zlib.decompress(chunkD, -8, bufSize) + chunk_data = zlib.decompress(chunk_d, -8, bufSize) # Swapping red & blue bytes for each pixel - chunkData = bytearray(chunkData) + chunk_data = bytearray(chunk_data) offset = 1 for y in range(height): for x in range(width): - chunkData[offset+4*x],chunkData[offset+4*x+2] = chunkData[offset+4*x+2],chunkData[offset+4*x] + chunk_data[offset+4*x],chunk_data[offset+4*x+2] = chunk_data[offset+4*x+2],chunk_data[offset+4*x] offset += 1+4*width # Compressing the image chunk - #chunkData = newdata - chunkData = zlib.compress( chunkData ) - chunkLength = len( chunkData ) # type: ignore[assignment] - chunkCRC = zlib.crc32(b'IDAT') # type: ignore[assignment] - chunkCRC = zlib.crc32(chunkData, chunkCRC) # type: ignore[assignment, arg-type] - chunkCRC = (chunkCRC + 0x100000000) % 0x100000000 # type: ignore[operator] - - newPNG += struct.pack(">L", chunkLength) - newPNG += b'IDAT' - newPNG += chunkData - newPNG += struct.pack(">L", chunkCRC) - - chunkCRC = zlib.crc32(chunkType) # type: ignore[assignment] - newPNG += struct.pack(">L", 0) - newPNG += b'IEND' - newPNG += struct.pack(">L", chunkCRC) + #chunk_data = newdata + chunk_data = zlib.compress(chunk_data) + chunk_length = len(chunk_data) # type: ignore[assignment] + chunk_crc = zlib.crc32(b'IDAT') # type: ignore[assignment] + chunk_crc = zlib.crc32(chunk_data, chunk_crc) # type: ignore[assignment, arg-type] + chunk_crc = (chunk_crc + 0x100000000) % 0x100000000 # type: ignore[operator] + + new_png += struct.pack(">L", chunk_length) + new_png += b'IDAT' + new_png += chunk_data + new_png += struct.pack(">L", chunk_crc) + + chunk_crc = zlib.crc32(chunk_type) # type: ignore[assignment] + new_png += struct.pack(">L", 0) + new_png += b'IEND' + new_png += struct.pack(">L", chunk_crc) break # Removing CgBI chunk - if chunkType == b"CgBI": - foundCGBi = True + if chunk_type == b"CgBI": + found_cgbi = True else: - newPNG += struct.pack(">L", chunkLength) - newPNG += chunkType - if chunkLength > 0: # type: ignore[operator] - newPNG += chunkData - newPNG += struct.pack(">L", chunkCRC) + new_png += struct.pack(">L", chunk_length) + new_png += chunk_type + if chunk_length > 0: # type: ignore[operator] + new_png += chunk_data + new_png += struct.pack(">L", chunk_crc) - return newPNG \ No newline at end of file + return new_png \ No newline at end of file