Skip to content

Commit

Permalink
Reduce recreating variables and reading json files
Browse files Browse the repository at this point in the history
  • Loading branch information
laggykiller committed Mar 13, 2024
1 parent 3ded36d commit 9ad07c7
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 175 deletions.
4 changes: 2 additions & 2 deletions scripts/opt-comp-experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
opt_comp_template.set_color(50)
opt_comp_template.set_duration(3000)

formats = [
formats = (
("img", ".webp"),
("vid", ".webp"),
("vidlong", ".webp"),
Expand All @@ -59,7 +59,7 @@
("vid618", ".apng"),
("vid", ".webm"),
("vid", ".gif"),
]
)


def generate_random_apng(res: int, fps: float, duration: float, out_f: str) -> None:
Expand Down
27 changes: 27 additions & 0 deletions scripts/update-xcode-imessage-iconset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import Dict, Tuple
import json
from pathlib import Path

ROOT_DIR = Path(__file__).parents[1]

def main():
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)

for i in dict["images"]:
filename = i["filename"]
size = i["size"]
size_w = int(size.split("x")[0])
size_h = int(size.split("x")[1])
scale = int(i["scale"].replace("x", ""))
size_w_scaled = size_w * scale
size_h_scaled = size_h * scale

xcode_imessage_iconset[filename] = (size_w_scaled, size_h_scaled)

print(xcode_imessage_iconset)

if __name__ == "__main__":
main()
23 changes: 9 additions & 14 deletions src/sticker_convert/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pathlib import Path
from typing import Any, Dict

from sticker_convert.definitions import CONFIG_DIR, DEFAULT_DIR, ROOT_DIR
from sticker_convert.definitions import CONFIG_DIR, DEFAULT_DIR
from sticker_convert.job import Job
from sticker_convert.job_option import CompOption, CredOption, InputOption, OutputOption
from sticker_convert.utils.auth.get_kakao_auth import GetKakaoAuth
Expand All @@ -26,21 +26,16 @@ def __init__(self) -> None:

def cli(self) -> None:
try:
self.help: Dict[str, Dict[str, str]] = JsonManager.load_json(
ROOT_DIR / "resources/help.json"
)
self.input_presets = JsonManager.load_json(
ROOT_DIR / "resources/input.json"
)
self.compression_presets = JsonManager.load_json(
ROOT_DIR / "resources/compression.json"
)
self.output_presets = JsonManager.load_json(
ROOT_DIR / "resources/output.json"
)
from sticker_convert.utils.files.json_resources_loader import HELP_JSON, INPUT_JSON, COMPRESSION_JSON, OUTPUT_JSON, EMOJI_JSON
except RuntimeError as e:
self.cb.msg(e.__str__)
self.cb.msg(e.__str__())
return

self.help = HELP_JSON
self.input_presets = INPUT_JSON
self.compression_presets = COMPRESSION_JSON
self.output_presets = OUTPUT_JSON
self.emoji_list = EMOJI_JSON

parser = argparse.ArgumentParser(
description="CLI for stickers-convert",
Expand Down
37 changes: 18 additions & 19 deletions src/sticker_convert/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@
None,
]

MSG_START_COMP = "[I] Start compressing {} -> {}"
MSG_SKIP_COMP = "[S] Compatible file found, skip compress and just copy {} -> {}"
MSG_COMP = (
"[C] Compressing {} -> {} res={}x{}, "
"quality={}, fps={}, color={} (step {}-{}-{})"
)
MSG_REDO_COMP = "[{}] Compressed {} -> {} but size {} {} limit {}, recompressing"
MSG_DONE_COMP = "[S] Successful compression {} -> {} size {} (step {})"
MSG_FAIL_COMP = (
"[F] Failed Compression {} -> {}, "
"cannot get below limit {} with lowest quality under current settings (Best size: {})"
)

def rounding(value: float) -> Decimal:
return Decimal(value).quantize(0, ROUND_HALF_UP)
Expand Down Expand Up @@ -71,19 +83,6 @@ def useful_array(


class StickerConvert:
MSG_START_COMP = "[I] Start compressing {} -> {}"
MSG_SKIP_COMP = "[S] Compatible file found, skip compress and just copy {} -> {}"
MSG_COMP = (
"[C] Compressing {} -> {} res={}x{}, "
"quality={}, fps={}, color={} (step {}-{}-{})"
)
MSG_REDO_COMP = "[{}] Compressed {} -> {} but size {} {} limit {}, recompressing"
MSG_DONE_COMP = "[S] Successful compression {} -> {} size {} (step {})"
MSG_FAIL_COMP = (
"[F] Failed Compression {} -> {}, "
"cannot get below limit {} with lowest quality under current settings (Best size: {})"
)

def __init__(
self,
in_f: Union[Path, Tuple[Path, bytes]],
Expand Down Expand Up @@ -163,7 +162,7 @@ def _convert(self) -> Tuple[bool, Path, Union[None, bytes, Path], int]:
if result:
return self.compress_done(result)

self.cb.put((self.MSG_START_COMP.format(self.in_f_name, self.out_f_name)))
self.cb.put((MSG_START_COMP.format(self.in_f_name, self.out_f_name)))

steps_list = self.generate_steps_list()

Expand Down Expand Up @@ -195,7 +194,7 @@ def _convert(self) -> Tuple[bool, Path, Union[None, bytes, Path], int]:
self.color = param[4]

self.tmp_f = BytesIO()
msg = self.MSG_COMP.format(
msg = MSG_COMP.format(
self.in_f_name,
self.out_f_name,
self.res_w,
Expand Down Expand Up @@ -261,7 +260,7 @@ def check_if_compatible(self) -> Optional[bytes]:
file_info=self.codec_info_orig,
)
):
self.cb.put((self.MSG_SKIP_COMP.format(self.in_f_name, self.out_f_name)))
self.cb.put((MSG_SKIP_COMP.format(self.in_f_name, self.out_f_name)))

if isinstance(self.in_f, Path):
with open(self.in_f, "rb") as f:
Expand Down Expand Up @@ -323,15 +322,15 @@ def generate_steps_list(self) -> List[Tuple[Optional[int], ...]]:
return steps_list

def recompress(self, sign: str) -> None:
msg = self.MSG_REDO_COMP.format(
msg = MSG_REDO_COMP.format(
sign, self.in_f_name, self.out_f_name, self.size, sign, self.size_max
)
self.cb.put(msg)

def compress_fail(
self,
) -> Tuple[bool, Path, Union[None, bytes, Path], int]:
msg = self.MSG_FAIL_COMP.format(
msg = MSG_FAIL_COMP.format(
self.in_f_name, self.out_f_name, self.size_max, self.size
)
self.cb.put(msg)
Expand All @@ -353,7 +352,7 @@ def compress_done(
f.write(data)

if result_step:
msg = self.MSG_DONE_COMP.format(
msg = MSG_DONE_COMP.format(
self.in_f_name, self.out_f_name, self.result_size, result_step
)
self.cb.put(msg)
Expand Down
18 changes: 11 additions & 7 deletions src/sticker_convert/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,17 @@ def warn_tkinter_bug(self) -> None:
self.cb_msg(msg)

def load_jsons(self) -> None:
self.help = JsonManager.load_json(ROOT_DIR / "resources/help.json")
self.input_presets = JsonManager.load_json(ROOT_DIR / "resources/input.json")
self.compression_presets: Dict[str, Dict[str, Any]] = JsonManager.load_json(
ROOT_DIR / "resources/compression.json"
)
self.output_presets = JsonManager.load_json(ROOT_DIR / "resources/output.json")
self.emoji_list = JsonManager.load_json(ROOT_DIR / "resources/emoji.json")
try:
from sticker_convert.utils.files.json_resources_loader import HELP_JSON, INPUT_JSON, COMPRESSION_JSON, OUTPUT_JSON, EMOJI_JSON
except RuntimeError as e:
self.cb_msg(e.__str__())
return

self.help = HELP_JSON
self.input_presets = INPUT_JSON
self.compression_presets = COMPRESSION_JSON
self.output_presets = OUTPUT_JSON
self.emoji_list = EMOJI_JSON

if not (
self.compression_presets and self.input_presets and self.output_presets
Expand Down
5 changes: 2 additions & 3 deletions src/sticker_convert/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from urllib.parse import urlparse

from sticker_convert.converter import StickerConvert
from sticker_convert.definitions import ROOT_DIR
from sticker_convert.downloaders.download_kakao import DownloadKakao
from sticker_convert.downloaders.download_line import DownloadLine
from sticker_convert.downloaders.download_signal import DownloadSignal
Expand All @@ -26,7 +25,7 @@
from sticker_convert.uploaders.upload_telegram import UploadTelegram
from sticker_convert.uploaders.xcode_imessage import XcodeImessage
from sticker_convert.utils.callback import CallbackReturn
from sticker_convert.utils.files.json_manager import JsonManager
from sticker_convert.utils.files.json_resources_loader import OUTPUT_JSON
from sticker_convert.utils.files.metadata_handler import MetadataHandler
from sticker_convert.utils.media.codec_info import CodecInfo

Expand Down Expand Up @@ -335,7 +334,7 @@ def verify_input(self) -> bool:
error_msg += "[X] Uploading to signal requires uuid and password.\n"
error_msg += save_to_local_tip

output_presets = JsonManager.load_json(ROOT_DIR / "resources/output.json")
output_presets = OUTPUT_JSON

input_option = self.opt_input.option
output_option = self.opt_output.option
Expand Down
78 changes: 19 additions & 59 deletions src/sticker_convert/uploaders/xcode_imessage.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import zipfile
from pathlib import Path
from queue import Queue
from typing import Any, Dict, List, Tuple, Union
from typing import Any, Dict, List, Union

from sticker_convert.converter import CbQueueItemType, StickerConvert
from sticker_convert.definitions import ROOT_DIR
Expand All @@ -19,65 +19,25 @@
from sticker_convert.utils.media.codec_info import CodecInfo
from sticker_convert.utils.media.format_verify import FormatVerify


class XcodeImessageIconset:
iconset: Dict[str, Tuple[int, int]] = {}

def __init__(self) -> None:
if self.iconset != {}:
return

if (ROOT_DIR / "ios-message-stickers-template").is_dir():
with open(
ROOT_DIR
/ "ios-message-stickers-template/stickers StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset/Contents.json"
) as f:
dict = json.load(f)
elif (ROOT_DIR / "ios-message-stickers-template.zip").is_file():
with zipfile.ZipFile(
(ROOT_DIR / "ios-message-stickers-template.zip"), "r"
) as f:
dict = json.loads(
f.read(
"stickers StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset/Contents.json"
).decode()
)
else:
raise FileNotFoundError("ios-message-stickers-template not found")

for i in dict["images"]:
filename = i["filename"]
size = i["size"]
size_w = int(size.split("x")[0])
size_h = int(size.split("x")[1])
scale = int(i["scale"].replace("x", ""))
size_w_scaled = size_w * scale
size_h_scaled = size_h * scale

self.iconset[filename] = (size_w_scaled, size_h_scaled)

# self.iconset = {
# 'App-Store-1024x1024pt.png': (1024, 1024),
# '[email protected]': (58, 58),
# '[email protected]': (58, 58),
# '[email protected]': (87, 87),
# '[email protected]': (54, 40),
# '[email protected]': (81, 60),
# '[email protected]': (64, 48),
# '[email protected]': (96, 72),
# 'Messages-App-Store-1024x768pt.png': (1024, 768),
# '[email protected]': (134, 100),
# '[email protected]': (148, 110),
# '[email protected]': (120, 90),
# '[email protected]': (180, 135)
# }

XCODE_IMESSAGE_ICONSET = {
'App-Store-1024x1024pt.png': (1024, 1024),
'[email protected]': (58, 58),
'[email protected]': (58, 58),
'[email protected]': (87, 87),
'[email protected]': (54, 40),
'[email protected]': (81, 60),
'[email protected]': (64, 48),
'[email protected]': (96, 72),
'Messages-App-Store-1024x768pt.png': (1024, 768),
'[email protected]': (134, 100),
'[email protected]': (148, 110),
'[email protected]': (120, 90),
'[email protected]': (180, 135)
}

class XcodeImessage(UploadBase):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(XcodeImessage, self).__init__(*args, **kwargs)
self.iconset = XcodeImessageIconset().iconset

self.base_spec.set_size_max(500000)
self.base_spec.set_res(300)
self.base_spec.set_format(("png", ".apng", ".gif", ".jpeg", "jpg"))
Expand Down Expand Up @@ -169,7 +129,7 @@ def add_metadata(self, author: str, title: str) -> None:
else:
icon_source = first_image_path

for icon, res in self.iconset.items():
for icon, res in XCODE_IMESSAGE_ICONSET.items():
spec_cover = CompOption()
spec_cover.set_res_w(res[0])
spec_cover.set_res_h(res[1])
Expand Down Expand Up @@ -264,7 +224,7 @@ def create_xcode_proj(self, author: str, title: str) -> None:
if (
CodecInfo.get_file_ext(i) == ".png"
and i.stem != "cover"
and i.name not in self.iconset
and i.name not in XCODE_IMESSAGE_ICONSET
):
sticker_dir = f"{i.stem}.sticker" # 0.sticker
stickers_lst.append(sticker_dir)
Expand Down Expand Up @@ -308,7 +268,7 @@ def create_xcode_proj(self, author: str, title: str) -> None:
os.remove(iconset_path / iconfile_name)

icons_lst: List[str] = []
for icon in self.iconset:
for icon in XCODE_IMESSAGE_ICONSET:
shutil.copy(self.opt_output.dir / icon, iconset_path / icon)
icons_lst.append(icon)

Expand Down
10 changes: 10 additions & 0 deletions src/sticker_convert/utils/files/json_resources_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from typing import Dict

from sticker_convert.definitions import ROOT_DIR
from sticker_convert.utils.files.json_manager import JsonManager

HELP_JSON: Dict[str, Dict[str, str]] = JsonManager.load_json(ROOT_DIR / "resources/help.json")
INPUT_JSON = JsonManager.load_json(ROOT_DIR / "resources/input.json")
COMPRESSION_JSON = JsonManager.load_json(ROOT_DIR / "resources/compression.json")
OUTPUT_JSON = JsonManager.load_json(ROOT_DIR / "resources/output.json")
EMOJI_JSON = JsonManager.load_json(ROOT_DIR / "resources/emoji.json")
Loading

0 comments on commit 9ad07c7

Please sign in to comment.