This repository has been archived by the owner on Jan 24, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutility.py
333 lines (269 loc) · 10.5 KB
/
utility.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import csv
import json
import logging
import re
import shutil
import subprocess
from datetime import datetime
from glob import glob
from itertools import islice
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union
from PIL import Image
log: logging.Logger = logging.getLogger(__name__)
class Utility:
"""Utilitarian functions intended to reduce duplicate code."""
def ReadFile(
self: Any, path: str
) -> Optional[Union[Dict[str, Any], List[Any], str]]:
"""Read and return the contents of the specified file."""
try:
with open(path, "r", encoding="utf-8") as file:
if path.split(".")[-1] == "json":
return json.loads(file.read())
else:
return file.read()
except Exception as e:
log.error(f"Failed to read file {path}, {e}")
def ReadCSV(
self: Any, path: str, types: TypedDict, skip: int = 0
) -> List[Dict[str, Any]]:
"""
Read and transform a comma separated values (csv) file to a list
of dictionaries with the desired value types.
"""
entries: List[Dict[str, Any]] = []
fields: Dict[str, Any] = types.__annotations__
try:
with open(path, "r", encoding="utf-8") as file:
if skip > 0:
file: List[str] = file.readlines()[skip:]
for row in csv.DictReader(file, fieldnames=list(fields)):
try:
entries.append(
{
key: None
if ((v := value) == "") or (v is None)
else fields[key](value)
for key, value in islice(
row.items(), 0, len(list(fields))
)
}
)
except Exception:
continue
except Exception as e:
log.error(f"Failed to read file {path}, {e}")
return entries
def WriteFile(
self: Any, path: str, contents: Union[str, dict, list], **kwargs
) -> None:
"""Write the contents of the specified file."""
if Path(dirPath := (path.rsplit("/", 1)[0])).exists() is False:
Path(dirPath).mkdir(parents=True, exist_ok=True)
try:
with open(path, "w+", encoding="utf-8") as file:
if path.rsplit(".")[1] == "json":
if kwargs.get("compress") is True:
file.write(json.dumps(contents, ensure_ascii=False))
else:
file.write(json.dumps(contents, indent=4, ensure_ascii=False))
else:
file.write(contents)
except Exception as e:
log.error(f"Failed to write file {path}, {e}")
def FileExists(self: Any, path: str) -> bool:
"""
Return a boolean value indicating whether or not the specified
file exists.
"""
if Path(path).is_file():
return True
return False
def GetMatchingFiles(
self: Any,
path: str,
fileType: str,
start: Optional[str],
end: Optional[str],
recursive: bool = False,
) -> List[str]:
"""
Return a list of paths to the files in the specified directory
which match the desired filetype and filename scheme.
"""
files: List[str] = []
for file in glob(f"{path}*.{fileType}", recursive=recursive):
filename: str = file.rsplit("\\")[1].split(".")[0]
if (start is not None) and (end is None):
if filename.startswith(start) is False:
continue
elif (start is None) and (end is not None):
if filename.endswith(end) is False:
continue
elif (start is not None) and (end is not None):
if (filename.startswith(start) is False) or (
filename.endswith(end) is False
):
continue
files.append(file)
return files
def GetCSVArray(
self: Any, array: str, type: Any, delimiter: str = "|"
) -> List[Any]:
"""
Transform a comma separated values (csv) array to a list of
values with the desired value types.
"""
values: List[Any] = []
for value in array.split(delimiter):
values.append(type(value))
return values
def GetStringBool(self: Any, value: str) -> Optional[bool]:
"""Determine the proper boolean value for the given string."""
if value == "TRUE":
return True
elif value == "FALSE":
return False
elif value == "Y":
return True
elif value == "N":
return False
def SortList(
self: Any, array: List[Dict[str, Any]], key: str, **kwargs
) -> List[Dict[str, Any]]:
"""
Alphabetically sort the provided list of dicts by the specified key.
Null values are placed at the end of the list.
"""
if (key2 := kwargs.get("key2", key)) is not None:
sort: List[Dict[str, Any]] = sorted(
array, key=lambda k: (k[key] is None, k[key], k[key2] is None, k[key2])
)
else:
sort: List[Dict[str, Any]] = sorted(
array, key=lambda k: (k[key] is None, k[key])
)
return sort
def PrettyTime(self: Any, timestamp: int) -> str:
"""Convert the provided UTC timestamp to a human-readable string."""
return datetime.utcfromtimestamp(timestamp).strftime("%A, %B %e, %Y %I:%M %p")
def StripColorCodes(self: Any, input: str, quiet: bool = False) -> str:
"""Remove all Call of Duty color codes from the provided string."""
colors: List[str] = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"*",
"+",
";",
".",
"/",
"<",
">",
"=",
"?",
"&",
"(",
")",
"L",
"'",
"-",
":",
"$",
",",
"@",
"B",
"R",
]
output: str = input
for i in colors:
output = output.replace(f"^{i}", "")
if "^" in output:
try:
modifier: str = output.split("^")[1][0]
if quiet is False:
log.warning(f"Potential color code found: ^{modifier}")
except Exception:
pass
return output
def StripButtonCodes(self: Any, input: str) -> str:
"""Replace all Call of Duty button codes from the provided string."""
buttons: List[Dict[str, str]] = [
{"code": "[{ONFOOT:+breath_sprint;+holdbreath}]", "literal": "button"},
{"code": "[{ui_alt2}]", "literal": "button"},
{"code": "[{+frag}]", "literal": "button"},
{"code": "[{+activate}]", "literal": "button"},
{"code": "[{BUTTON_SELECTCHOICE+gostand}]", "literal": "button"},
]
output: str = input
for button in buttons:
output = output.replace(button.get("code"), button.get("literal"))
return output
def Sluggify(self: Any, input: str) -> str:
"""Transform the provided string into a URL-friendly slug."""
invalids: re.Pattern[str] = re.compile(r"[^a-z0-9\s-]")
hypens: re.Pattern[str] = re.compile(r"\s")
doubleHypens: re.Pattern[str] = re.compile(r"-{2,}")
output: str = re.sub(invalids, "", input.lower())
output: str = re.sub(hypens, "-", output)
output: str = re.sub(doubleHypens, "-", output)
return output[:45]
def AnimateSprite(
self: Any, filename: str, dimensions: List[Tuple[int, int]]
) -> bool:
"""Animate the provided Spritesheet into a WEBM video."""
with Image.open(f"{self.iImages}/{filename}.png") as file:
width, height = file.size
for dimension in dimensions:
frameWidth: int = dimension[0]
frameHeight: int = dimension[1]
if (width == frameWidth) and (height == frameHeight):
return False
if (width % dimension[0] != 0) or (height % frameHeight != 0):
continue
columns: int = width // frameWidth
rows: int = height // frameHeight
if self.config.get("animateImages") is True:
Path(f"{self.eImages}/temp/").mkdir(parents=True, exist_ok=True)
Path(f"{self.eImages}").mkdir(parents=True, exist_ok=True)
Path(f"{self.eVideos}").mkdir(parents=True, exist_ok=True)
i: int = 1
for row in range(0, rows):
for column in range(0, columns):
frame = file.crop(
(
column * frameWidth,
row * frameHeight,
(column + 1) * frameWidth,
(row + 1) * frameHeight,
)
)
frame.save(f"{self.eImages}/temp/{filename}_{i:03}.png")
if i == 1:
frame.save(f"{self.eImages}/{filename}.png")
i += 1
subprocess.call(
[
"ffmpeg",
"-framerate",
"10",
"-i",
f"{self.eImages}/temp/{filename}_%03d.png",
"-y",
f"{self.eVideos}/{filename}.webm",
],
stderr=subprocess.DEVNULL,
)
shutil.rmtree(f"{self.eImages}/temp/", ignore_errors=True)
log.info(f"Animated {filename} ({columns}x{rows})")
return True
else:
return True