-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
270 lines (189 loc) · 8.16 KB
/
util.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""Miscellaneous utility functions
"""
import os
import re
import subprocess
import time
from pathlib import PosixPath
import cv2
import pydicom
from pydicom.errors import InvalidDicomError
from custom_apng import get_apng_frames_resolution, get_apng_depth
from parameters import PathParameters, DEPTH
def construct_djxl(decoded_path, target_image):
"""Creates the command for decoding an image to jxl
Given the provided configurations
@param decoded_path: Output path
@param target_image: Input path
@return: Command
"""
return f"djxl {target_image} {decoded_path}"
def construct_davif(decoded_path: str, input_path: str):
"""Creates the command for decoding an image from avif
Given the provided configurations
@param decoded_path: Output path
@param input_path: Input path
@return: Command
"""
return f"avif_decode {input_path} {decoded_path}"
def construct_dwebp(decoded_path: str, input_path: str, additional_options: str = ""):
"""Creates the command for decoding an image from webp
Given the provided configurations
@param additional_options: More options
@param decoded_path: Output path
@param input_path: Input path
@return: Command
"""
return f"dwebp -v {input_path} {additional_options} -o {decoded_path}"
def construct_cwebp(effort, output_path, quality, target_image):
"""Creates the command for encoding an image to webp
Given the provided configurations
@param effort: Effort setting
@param output_path: Output
@param quality: Quality setting
@param target_image: Input
@return: Void
"""
return f"cwebp -quiet -v -q {quality} -m {effort} {target_image} -o {output_path}"
def construct_cavif(output_path, quality, speed, target_image):
"""Creates the command for encoding an image to avif
Given the provided configurations
@param output_path: Output
@param quality: Quality setting
@param speed: Effort setting
@param target_image: Input
@return: Void
"""
return f"cavif -o {output_path} " f"--quality {quality} --speed {speed} --quiet " f"{os.path.abspath(target_image)}"
def construct_cjxl(distance, effort, output_path, target_image):
"""Creates the command for encoding an image to jxl
Given the provided configurations
@param distance: Quality setting
@param effort: Effort setting
@param output_path: Output
@param target_image: Input
@return: Void
"""
return f"cjxl {target_image} {output_path} " f"--distance={distance} --effort={effort} --quiet"
def number_lgt_regex(expr: str) -> str:
"""Parses lt/gt condition expression into a regex that validates such a number
@note function name could be read as - number lesser or greater than regular expression
@param expr: Bigger/Lesser than condition - e.g.: "<122", ">9".
@return: Regex that validates a number which passes the expression
"""
bigger_than = re.compile(r">\d+")
lesser_than = re.compile(r"<\d+")
number = int(expr[1:])
digits_count = len(expr) - 1
last_digit = number % 10
if bigger_than.fullmatch(expr) is not None:
return fr"((\d{{{digits_count + 1}}}\d*)|(\d{{{digits_count - 1}}}[{last_digit + 1}-9]))"
# return re.compile(fr"""\
# (\d{{{digits_count + 1}}}\d*)\ # More digits than the number
# |\ # or
# (\d{{{digits_count - 1}}}[{last_digit + 1}-9]) # Same #digits, but last one is greater than number % 10
# """, re.VERBOSE).pattern
elif lesser_than.fullmatch(expr) is not None:
return fr"((\d{{1,{digits_count - 1}}})|(\d{{{digits_count - 1}}}[0-{last_digit-1}]))"
# return fr"""\
# (\d{{1,{digits_count - 1}}})\ # Less digits than the original number
# |\ # or
# (\d{{{digits_count - 1}}}[0-{last_digit-1}]) # Same #digits, but last one is lesser than number % 10
# """
raise AssertionError(f"This is not a lt/gt expression! '{expr}'")
def timed_command(stdin: str) -> float:
"""Runs a given command on a subshell and records its execution time
Note: Execution timeout implemented to 60 seconds
@param stdin: Used to run the subshell command
@return: Time it took for the command to run (in seconds)
"""
# Execute command and time the CT
start = time.time()
subprocess.run(stdin, shell=True, check=True, timeout=180,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return time.time() - start
def total_pixels(target_image: str) -> int:
"""Counts the number of pixels of an image
@param target_image: Input image path
@return: Number of pixels
"""
# Parameter checking
assert os.path.exists(target_image), f"Image at \"{target_image}\" does not exist!"
# Extract resolution
if target_image.endswith("apng"):
height, width = get_apng_frames_resolution(target_image)
depth = get_apng_depth(target_image)
return height * width * depth
return cv2.imread(target_image, cv2.IMREAD_UNCHANGED).size
def rename_duplicate(intended_abs_filepath: str) -> str:
"""Finds an original filename if it is already taken
Example - give path/to/filename.txt -> it already exists -> return path/to/filename_1.txt
@param intended_abs_filepath: Absolute path to a file not yet written (w/o the file's extension)
@return: Same path, with basename of the file changed to an original one
"""
# Separate path from extension
extension: str = intended_abs_filepath.split(".")[-1]
intended_abs_filepath: str = ".".join(intended_abs_filepath.split(".")[:-1])
suffix: str = ""
counter: int = 0
while os.path.exists(f"{intended_abs_filepath + suffix}.{extension}"):
counter += 1
suffix = f"_{counter}"
return f"{intended_abs_filepath + suffix}.{extension}"
def rm_encoded():
"""Removes compressed files from a previous execution
"""
for file in os.listdir(PathParameters.DATASET_COMPRESSED_PATH):
os.remove(os.path.abspath(PathParameters.DATASET_COMPRESSED_PATH + file))
def dataset_img_info(target_image: str, keyword: int) -> str:
"""Extract the information present in the names of the pre-processed dataset
@param target_image: Path to the image which name is to be evaluated
@param keyword: parameter defined attribute (id) to extract
@return: Attribute value for the image
"""
retval = os.path.basename(target_image).split("_")[keyword]
return retval.replace(".apng", "") if keyword == DEPTH else retval
def remove_last_dict_level(dictionary: dict) -> dict | list:
"""Recursive function to remove the last level of a (tree-like) nested dictionary
@note If there is but one non-dict type value in a level, that one is removed
@param dictionary:
@return:
"""
for key in dictionary:
# Stop condition
if type(dictionary[key]) != dict:
dictionary = list(dictionary.keys())
break
# Recursive call
dictionary[key] = remove_last_dict_level(dictionary[key])
return dictionary
def sort_by_keys(*args) -> list:
"""Sort all the lists by the first one
@return: A list with the lists provided, each one ordered according to the first one
"""
zipped = zip(*args)
zipped = list(sorted(zipped, key=lambda elem: float(elem[0]), reverse=False))
return list(zip(*zipped))
def is_file_a_dicom(file):
"""
Check whether a given file is of type DICOM
:param file: path to the file to identify
:type file: str
:return: True if the file is DICOM, False otherwise
:rtype: bool
"""
try:
pydicom.read_file(file, stop_before_pixels=True)
except InvalidDicomError:
return False
return True
def mkdir_if_not_exists(path: str, regard_parent: bool = False):
"""Create directory if the one in the path provided does not exist
@param path:
@param regard_parent: Evaluate parent directory instead
@return:
"""
if regard_parent:
path = str(PosixPath(path).parent)
if os.path.isdir(path) and not os.path.exists(path):
os.makedirs(path)