This repository has been archived by the owner on Apr 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathutil.py
139 lines (105 loc) · 4.52 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
import json
import locale
import logging
from datetime import datetime
import requests
from PIL import Image, ImageFont
log = logging.getLogger(__name__)
class Utility:
"""Class containing utilitarian functions intended to reduce duplicate code."""
def GET(self, url: str, headers: dict, parameters: dict = {"language": "en"}):
"""
Return the response of a successful HTTP GET request to the specified
URL with the optionally provided header values.
"""
res = requests.get(url, headers=headers, params=parameters)
# HTTP 200 (OK)
if res.status_code == 200:
return res.text
else:
log.critical(f"Failed to GET {url} (HTTP {res.status_code})")
def nowISO(self):
"""Return the current utc time in ISO8601 timestamp format."""
return datetime.utcnow().isoformat()
def ISOtoHuman(self, date: str, language: str):
"""Return the provided ISO8601 timestamp in human-readable format."""
try:
locale.setlocale(locale.LC_ALL, language)
except locale.Error:
log.warn(f"Unsupported locale configured, using system default")
try:
# Unix-supported zero padding removal
return datetime.strptime(date, "%Y-%m-%d").strftime("%A, %B %-d, %Y")
except ValueError:
try:
# Windows-supported zero padding removal
return datetime.strptime(date, "%Y-%m-%d").strftime("%A, %B %#d, %Y")
except Exception as e:
log.error(self, f"Failed to convert to human-readable time, {e}")
def ReadFile(self, filename: str, extension: str, directory: str = ""):
"""
Read and return the contents of the specified file.
Optionally specify a relative directory.
"""
try:
with open(
f"{directory}{filename}.{extension}", "r", encoding="utf-8"
) as file:
return file.read()
except Exception as e:
log.critical(f"Failed to read {filename}.{extension}, {e}")
class ImageUtil:
"""Class containing utilitarian image-based functions intended to reduce duplicate code."""
def Open(self, filename: str, directory: str = "assets/images/"):
"""Return the specified image file."""
return Image.open(f"{directory}{filename}")
def Download(self, url: str):
"""Download and return the raw file from the specified url as an image object."""
res = requests.get(url, stream=True)
# HTTP 200 (OK)
if res.status_code == 200:
return Image.open(res.raw)
else:
log.critical(f"Failed to GET {url} (HTTP {res.status_code})")
def RatioResize(self, image: Image.Image, maxWidth: int, maxHeight: int):
"""Resize and return the provided image while maintaining aspect ratio."""
ratio = max(maxWidth / image.width, maxHeight / image.height)
return image.resize(
(int(image.width * ratio), int(image.height * ratio)), Image.ANTIALIAS
)
def CenterX(self, foregroundWidth: int, backgroundWidth: int, distanceTop: int = 0):
"""Return the tuple necessary for horizontal centering and an optional vertical distance."""
return (int(backgroundWidth / 2) - int(foregroundWidth / 2), distanceTop)
def Font(
self,
size: int,
font: str = "BurbankBigCondensed-Black.otf",
directory: str = "assets/fonts/",
):
"""Return a font object with the specified font file and size."""
try:
return ImageFont.truetype(f"{directory}{font}", size)
except OSError:
log.warn(
"BurbankBigCondensed-Black.otf not found, defaulted font to LuckiestGuy-Regular.ttf"
)
return ImageFont.truetype(f"{directory}LuckiestGuy-Regular.ttf", size)
except Exception as e:
log.error(f"Failed to load font, {e}")
def FitTextX(
self,
text: str,
size: int,
maxSize: int,
font: str = "BurbankBigCondensed-Black.otf",
):
"""Return the font and width which fits the provided text within the specified maxiumum width."""
font = ImageUtil.Font(self, size)
textWidth, _ = font.getsize(text)
change = 0
while textWidth >= maxSize:
change += 1
size -= 1
font = ImageUtil.Font(self, size)
textWidth, _ = font.getsize(text)
return ImageUtil.Font(self, size), textWidth, change