-
Notifications
You must be signed in to change notification settings - Fork 1
/
function.py
77 lines (61 loc) · 2.13 KB
/
function.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
from os import mkdir
from os.path import abspath, basename, exists, expanduser, getsize, join
from shutil import move, rmtree
from subprocess import DEVNULL, run
from typing import Tuple
from rich.console import Console
console = Console()
# Modify these to use on other platform
cache_folder = expanduser("~/Library/Caches/compress-office/")
image_optim_executable = "/Applications/ImageOptim.app/Contents/MacOS/ImageOptim"
def convert_size(size_in_byte: int) -> str:
units = ("B", "KB", "MB", "GB")
for unit in units:
if size_in_byte < 1024:
return f"{round(size_in_byte, 2)}{unit}"
size_in_byte /= 1024
return f"{round(size_in_byte, 2)}TB"
def compress(file_path: str) -> Tuple:
file_path = abspath(file_path)
file_name = basename(file_path)
before_size = getsize(file_path)
# Delete old files
if exists(cache_folder):
rmtree(cache_folder)
# Create cache folder
mkdir(cache_folder)
# Unzip file
with console.status("[bold green]Unzipping Document..."):
run(
["unzip", file_path, "-d", cache_folder],
stdout=DEVNULL,
).check_returncode()
# Compress
new_file_path = join(cache_folder, file_name)
with console.status("[bold green]Compressing Images..."):
run(
[image_optim_executable, cache_folder],
stdout=DEVNULL,
stderr=DEVNULL,
).check_returncode()
# Rezip file
with console.status("[bold green]Packing Document..."):
run(
["zip", file_name, "-r", "."],
stdout=DEVNULL,
cwd=cache_folder,
).check_returncode()
after_size = getsize(new_file_path)
if after_size >= before_size:
print("File size unchanged")
return (before_size, before_size)
# Move new file to origin place
run(
["trash", file_path],
).check_returncode()
move(new_file_path, file_path)
# Delete caches
if exists(cache_folder):
rmtree(cache_folder)
print(f"Successfully compressed {convert_size(before_size)} -> {convert_size(after_size)}")
return (before_size, after_size)