Skip to content

Commit

Permalink
Linting
Browse files Browse the repository at this point in the history
  • Loading branch information
laggykiller committed Mar 13, 2024
1 parent 2ea61bc commit df8843d
Show file tree
Hide file tree
Showing 44 changed files with 292 additions and 332 deletions.
2 changes: 1 addition & 1 deletion scripts/opt-comp-experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def compress_worker(
out_f=out_f,
opt_comp=opt_comp,
cb=Callback(),
cb_return=CallbackReturn(),
_cb_return=CallbackReturn(),
)
results_queue.put(
(
Expand Down
6 changes: 3 additions & 3 deletions scripts/update-xcode-imessage-iconset.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
ROOT_DIR = Path(__file__).parents[1]


def main():
def main() -> None:
xcode_imessage_iconset: Dict[str, Tuple[int, int]] = {}

with open(
ROOT_DIR
/ "src/sticker_convert/ios-message-stickers-template/stickers StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset/Contents.json"
) as f:
dict = json.load(f)
contents_json = json.load(f)

for i in dict["images"]:
for i in contents_json["images"]:
filename = i["filename"]
size = i["size"]
size_w = int(size.split("x")[0])
Expand Down
7 changes: 4 additions & 3 deletions src/sticker_convert/cli.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import argparse
import signal
import sys
from argparse import Namespace
from json.decoder import JSONDecodeError
from math import ceil
Expand Down Expand Up @@ -28,7 +29,7 @@ def cli(self) -> None:
try:
from sticker_convert.utils.files.json_resources_loader import COMPRESSION_JSON, EMOJI_JSON, HELP_JSON, INPUT_JSON, OUTPUT_JSON
except RuntimeError as e:
self.cb.msg(e.__str__())
self.cb.msg(str(e))
return

self.help = HELP_JSON
Expand Down Expand Up @@ -181,7 +182,7 @@ def cli(self) -> None:

signal.signal(signal.SIGINT, job.cancel)
status = job.start()
exit(status)
sys.exit(status)

def get_opt_input(self, args: Namespace) -> InputOption:
download_options = {
Expand All @@ -207,7 +208,7 @@ def get_opt_input(self, args: Namespace) -> InputOption:
self.cb.msg(f"Detected URL input source: {download_option}")
else:
self.cb.msg(f"Error: Unrecognied URL input source for url: {url}")
exit()
sys.exit()

opt_input = InputOption(
option=download_option,
Expand Down
42 changes: 20 additions & 22 deletions src/sticker_convert/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
import numpy as np
from PIL import Image

if TYPE_CHECKING:
from av.video.plane import VideoPlane # type: ignore

from sticker_convert.job_option import CompOption
from sticker_convert.utils.callback import Callback, CallbackReturn
from sticker_convert.utils.files.cache_store import CacheStore
from sticker_convert.utils.media.codec_info import CodecInfo
from sticker_convert.utils.media.format_verify import FormatVerify

if TYPE_CHECKING:
from av.video.plane import VideoPlane # type: ignore

CbQueueItemType = Union[
Tuple[str, Optional[Tuple[str]], Optional[Dict[str, str]]],
str,
Expand All @@ -45,8 +45,8 @@ def rounding(value: float) -> Decimal:


def get_step_value(
max: Optional[int],
min: Optional[int],
max_step: Optional[int],
min_step: Optional[int],
step: int,
steps: int,
power: float = 1.0,
Expand All @@ -62,14 +62,12 @@ def get_step_value(
else:
factor = 0

if max is not None and min is not None:
v = round((max - min) * step / steps * factor + min)
if max_step is not None and min_step is not None:
v = round((max_step - min_step) * step / steps * factor + min_step)
if even is True and v % 2 == 1:
return v + 1
else:
return v
else:
return None
return v
return None


def useful_array(
Expand Down Expand Up @@ -151,7 +149,7 @@ def convert(
out_f: Path,
opt_comp: CompOption,
cb: "Union[Queue[CbQueueItemType], Callback]",
cb_return: CallbackReturn,
_cb_return: CallbackReturn,
) -> Tuple[bool, Path, Union[None, bytes, Path], int]:
sticker = StickerConvert(in_f, out_f, opt_comp, cb)
result = sticker._convert()
Expand Down Expand Up @@ -272,8 +270,8 @@ def check_if_compatible(self) -> Optional[bytes]:
self.result_size = len(self.in_f)

return result
else:
return None

return None

def generate_steps_list(self) -> List[Tuple[Optional[int], ...]]:
steps_list: List[Tuple[Optional[int], ...]] = []
Expand Down Expand Up @@ -378,7 +376,7 @@ def frames_import(self) -> None:
def _frames_import_pillow(self) -> None:
with Image.open(self.in_f) as im:
# Note: im.convert("RGBA") would return rgba image of current frame only
if "n_frames" in im.__dir__():
if "n_frames" in dir(im):
for i in range(im.n_frames):
im.seek(i)
self.frames_raw.append(np.asarray(im.convert("RGBA")))
Expand Down Expand Up @@ -764,10 +762,10 @@ def quantize(self, image: Image.Image) -> Image.Image:
return image.copy()
if self.opt_comp.quantize_method == "imagequant":
return self._quantize_by_imagequant(image)
elif self.opt_comp.quantize_method == "fastoctree":
if self.opt_comp.quantize_method == "fastoctree":
return self._quantize_by_fastoctree(image)
else:
return image

return image

def _quantize_by_imagequant(self, image: Image.Image) -> Image.Image:
import imagequant # type: ignore
Expand Down Expand Up @@ -812,17 +810,17 @@ def fix_fps(self, fps: float) -> Fraction:
#
# For GIF, we need to adjust fps such that delay is matching to hundreths of second
return self._fix_fps_duration(fps, 100)
elif self.out_f.suffix in (".webp", ".apng", ".png"):
if self.out_f.suffix in (".webp", ".apng", ".png"):
return self._fix_fps_duration(fps, 1000)
else:
return self._fix_fps_pyav(fps)

return self._fix_fps_pyav(fps)

def _fix_fps_duration(self, fps: float, denominator: int) -> Fraction:
delay = int(rounding(denominator / fps))
fps_fraction = Fraction(denominator, delay)
if self.opt_comp.fps_max and fps_fraction > self.opt_comp.fps_max:
return Fraction(denominator, (delay + 1))
elif self.opt_comp.fps_min and fps_fraction < self.opt_comp.fps_min:
if self.opt_comp.fps_min and fps_fraction < self.opt_comp.fps_min:
return Fraction(denominator, (delay - 1))
return fps_fraction

Expand Down
20 changes: 8 additions & 12 deletions src/sticker_convert/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ def check_root_dir_exe_writable() -> bool:
or "site-packages" in ROOT_DIR_EXE.as_posix()
):
return False
else:
return True
return True


ROOT_DIR_EXE_WRITABLE = check_root_dir_exe_writable()
Expand All @@ -58,13 +57,11 @@ def check_root_dir_exe_writable() -> bool:
def get_default_dir() -> Path:
if ROOT_DIR_EXE_WRITABLE:
return ROOT_DIR_EXE
else:
home_dir = Path.home()
desktop_dir = home_dir / "Desktop"
if desktop_dir.is_dir():
return desktop_dir
else:
return home_dir
home_dir = Path.home()
desktop_dir = home_dir / "Desktop"
if desktop_dir.is_dir():
return desktop_dir
return home_dir


# Default directory for stickers_input and stickers_output
Expand All @@ -79,9 +76,8 @@ def get_config_dir() -> Path:

if ROOT_DIR_EXE_WRITABLE:
return ROOT_DIR_EXE
else:
os.makedirs(fallback_dir, exist_ok=True)
return fallback_dir
os.makedirs(fallback_dir, exist_ok=True)
return fallback_dir


# Directory for saving configs
Expand Down
8 changes: 3 additions & 5 deletions src/sticker_convert/downloaders/download_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ def download_file(

if response.status_code != 200:
return b""
else:
self.cb.put(f"Downloading {url}")
self.cb.put(f"Downloading {url}")

if show_progress:
steps = (total_length / chunk_size) + 1
Expand All @@ -101,11 +100,10 @@ def download_file(

if not result:
return b""
elif dest:
if dest:
with open(dest, "wb+") as f:
f.write(result)
msg = f"Downloaded {url}"
self.cb.put(msg)
return b""
else:
return result
return result
41 changes: 18 additions & 23 deletions src/sticker_convert/downloaders/download_kakao.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get_info_from_share_link(url: str) -> Tuple[Optional[str], Optional[str]]:
data_urls = app_scheme_link_tag.get("data-url")
if not data_urls:
return None, None
elif isinstance(data_urls, list):
if isinstance(data_urls, list):
data_url = data_urls[0]
else:
data_url = data_urls
Expand Down Expand Up @@ -113,7 +113,7 @@ def get_title_from_id(item_code: str, auth_token: str) -> Optional[str]:

class DownloadKakao(DownloadBase):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(DownloadKakao, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.pack_title: Optional[str] = None
self.author: Optional[str] = None

Expand All @@ -129,13 +129,10 @@ def download_stickers_kakao(self) -> bool:

if item_code:
return self.download_animated(item_code)
else:
self.cb.put(
"Download failed: Cannot download metadata for sticker pack"
)
return False
self.cb.put("Download failed: Cannot download metadata for sticker pack")
return False

elif self.url.isnumeric() or self.url.startswith("kakaotalk://store/emoticon/"):
if self.url.isnumeric() or self.url.startswith("kakaotalk://store/emoticon/"):
item_code = self.url.replace("kakaotalk://store/emoticon/", "")

self.pack_title = None
Expand All @@ -150,7 +147,7 @@ def download_stickers_kakao(self) -> bool:

return self.download_animated(item_code)

elif urlparse(self.url).netloc == "e.kakao.com":
if urlparse(self.url).netloc == "e.kakao.com":
self.pack_title = self.url.replace("https://e.kakao.com/t/", "")
(
self.author,
Expand All @@ -172,24 +169,22 @@ def download_stickers_kakao(self) -> bool:
item_code = MetadataKakao.get_item_code(title_ko, auth_token)
if item_code:
return self.download_animated(item_code)
msg = "Warning: Cannot get item code.\n"
msg += "Is auth_token invalid / expired? Try to regenerate it.\n"
msg += "Continue to download static stickers instead?"
self.cb.put(("ask_bool", (msg,), None))
if self.cb_return:
response = self.cb_return.get_response()
else:
msg = "Warning: Cannot get item code.\n"
msg += "Is auth_token invalid / expired? Try to regenerate it.\n"
msg += "Continue to download static stickers instead?"
self.cb.put(("ask_bool", (msg,), None))
if self.cb_return:
response = self.cb_return.get_response()
else:
response = False

if response is False:
return False
response = False

if response is False:
return False

return self.download_static(thumbnail_urls)

else:
self.cb.put("Download failed: Unrecognized URL")
return False
self.cb.put("Download failed: Unrecognized URL")
return False

def download_static(self, thumbnail_urls: str) -> bool:
MetadataHandler.set_metadata(
Expand Down
10 changes: 5 additions & 5 deletions src/sticker_convert/downloaders/download_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from sticker_convert.utils.files.metadata_handler import MetadataHandler
from sticker_convert.utils.media.apple_png_normalize import ApplePngNormalize

"""Reference: https://github.com/doubleplusc/Line-sticker-downloader/blob/master/sticker_dl.py"""
# Reference: https://github.com/doubleplusc/Line-sticker-downloader/blob/master/sticker_dl.py


class MetadataLine:
Expand Down Expand Up @@ -162,7 +162,7 @@ def get_metadata_stickers(

class DownloadLine(DownloadBase):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(DownloadLine, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.headers = {
"referer": "https://store.line.me",
"user-agent": "Android",
Expand Down Expand Up @@ -444,13 +444,13 @@ def download_stickers_line(self) -> bool:
self.decompress_stickers(zip_file)

custom_sticker_text_urls: List[Tuple[str, Path]] = []
if self.sticker_text_dict != {} and (
if self.sticker_text_dict and (
self.resource_type == "PER_STICKER_TEXT"
or (self.resource_type == "NAME_TEXT" and self.cookies != {})
or (self.resource_type == "NAME_TEXT" and self.cookies)
):
self.edit_custom_sticker_text()
custom_sticker_text_urls = self.get_custom_sticker_text_urls()
elif self.resource_type == "NAME_TEXT" and self.cookies == {}:
elif self.resource_type == "NAME_TEXT" and not self.cookies:
self.cb.put('Warning: Line "Custom stickers" is supplied as input')
self.cb.put(
"However, adding custom message requires Line cookies, and it is not supplied"
Expand Down
6 changes: 3 additions & 3 deletions src/sticker_convert/downloaders/download_signal.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
from pathlib import Path
from queue import Queue
from typing import Any, Dict, Optional, Union
from typing import Dict, Optional, Union

import anyio
from signalstickers_client import StickersClient # type: ignore
Expand All @@ -17,8 +17,8 @@


class DownloadSignal(DownloadBase):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(DownloadSignal, self).__init__(*args, **kwargs)
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# super().__init__(*args, **kwargs)

@staticmethod
async def get_pack(pack_id: str, pack_key: str) -> StickerPack:
Expand Down
6 changes: 3 additions & 3 deletions src/sticker_convert/downloaders/download_telegram.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
from pathlib import Path
from queue import Queue
from typing import Any, Dict, Optional, Union
from typing import Dict, Optional, Union
from urllib.parse import urlparse

import anyio
Expand All @@ -16,8 +16,8 @@


class DownloadTelegram(DownloadBase):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(DownloadTelegram, self).__init__(*args, **kwargs)
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# super().__init__(*args, **kwargs)

def download_stickers_telegram(self) -> bool:
self.token = ""
Expand Down
Loading

0 comments on commit df8843d

Please sign in to comment.