This repository has been archived by the owner on Oct 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.py
546 lines (430 loc) · 16.7 KB
/
image.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
from dataclasses import dataclass
from math import ceil, floor, log10
from pathlib import Path
from textwrap import wrap
from typing import (
Any, Collection, Dict, List, Mapping, Optional, Sequence, Tuple, Union)
import pendulum
from PIL import Image, ImageDraw, ImageFont
from photo_dash import config
SECTIONS = Sequence[Mapping[str, Any]]
SECTION_SPACING = {
'text': 1,
'gauge': 2,
}
# Spacing: between lines and away from the canvas edges
SPACER = 10
V_SPACER = 5
H_SPACER = 5
# Font-related variables
FONT = 'DejaVuSansMono.ttf'
TEXT_COLOR = '#FFFFFF' # Does not apply to sections
TITLE_SIZE = 20
TITLE_FONT = ImageFont.truetype(font=FONT, size=TITLE_SIZE)
SECTION_SIZE = 16
SECTION_FONT = ImageFont.truetype(font=FONT, size=SECTION_SIZE)
# This ratio depends on the current font, FONT.
SECTION_CHAR = int(16 * 10 / 16)
FOOTER_SIZE = 10
FOOTER_FONT = ImageFont.truetype(font=FONT, size=FOOTER_SIZE)
# For a width of 480, SECTION_SIZE of 16, and using a monospace font,
# 48 chars could fit on one line. As such, MAX_C_PER_LINE can be scaled
# by dividing configured width by 10.
# MAX_C_PER_LINE is then subtracted by 2 H_SPACERs rounded up.
MAX_C_PER_LINE = (
config.WIDTH
// SECTION_CHAR
- ceil(2 * H_SPACER / SECTION_CHAR)
)
GAUGE_WIDTH = int(0.9 * config.WIDTH)
GAUGE_OFFSET = int(0.05 * config.WIDTH)
GAUGE_VALUE_STROKE = 2
GAUGE_LINE_WIDTH = 5
GAUGE_LINE_COLOR = '#808080'
# Render instruction type
COORDINATES = Union[int, Tuple[int, int]]
INSTRUCTIONS = List[
Tuple[
str,
Collection[COORDINATES],
Optional[str],
Dict[str, Union[str, int]]
]
]
class TooManySections(BufferError):
"""Too many sections were provided. The image cannot be rendered."""
def __init__(self, n_sections: int) -> None:
"""Initialize the error with number of sections.
Args:
n_sections (int): number of sections that triggered error
"""
super().__init__(
f'You have too many ({n_sections}) sections to render. '
'Try picking fewer sections to send.'
)
@dataclass
class DashImage:
"""Represents a photo-dash image.
Attributes:
draw (ImageDraw.Draw): the rendering class that draws onto an image
module (str): the name of the module the image represents
sections (SECTIONS): a response given to the endpoint
title (str): title of the image; goes at the top of the image
"""
# dataclass attributes
module: str
title: str
sections: SECTIONS
# While y should not be initialized, it can be included to offset the image
# from the top edge of the canvas.
y: int = 0
def create(self) -> None:
"""Create a new image given parameters.
Raises:
TooManySections: if too many sections are to be rendered
"""
if not self.sections_fit():
raise TooManySections(len(self.sections))
with Image.new('RGB', config.CANVAS) as im:
self.draw = ImageDraw.Draw(im)
header = SectionText(self.y, self.title, TEXT_COLOR, TITLE_FONT)
self.render_instructions(header.instructions)
self.y = header.y
for section in self.sections:
try:
section_type = section['type']
value = section['value']
color = section['color']
if section_type == 'text':
text = SectionText(self.y, value, color, SECTION_FONT)
y = text.y
instructions = text.instructions
elif section_type == 'gauge':
colors = section['color']
values = section['range']
gauge = SectionGauge(self.y, value, values, colors)
y = gauge.y
instructions = gauge.instructions
self.render_instructions(instructions)
self.y = y
except KeyError as e:
config.LOGGER.warning(
'The section is malformed. Skipping...')
config.LOGGER.warning(f'Module: {self.module}')
config.LOGGER.warning(f'More info: {e}')
continue
except NameError as e:
config.LOGGER.warning(
'Could not determine type of section. Skipping...')
config.LOGGER.warning(f'Module: {self.module}')
config.LOGGER.warning(f'More info: {e}')
continue
footer = SectionFooter(self.y)
self.render_instructions(footer.instructions)
self.dest = config.DEST / f'{self.module}.jpg'
im.save(self.dest, quality=85)
def delete(self) -> None:
"""Delete the image. This is mostly used for quiet hour images."""
file = Path(self.dest)
file.unlink()
def sections_fit(self) -> bool:
"""Check whether the sections fit in the image.
Returns:
bool: whether the sections will fit in the image (True)
or not (False)
"""
space = 0
for section in self.sections:
if section['type'] == 'text':
lines = len(wrap(section['value'], width=MAX_C_PER_LINE))
space += lines * SECTION_SPACING[section['type']]
else:
space += SECTION_SPACING[section['type']]
space += SPACER
space -= SPACER
free_space = (
config.LENGTH
- (TITLE_SIZE + SPACER)
- (FOOTER_SIZE + 2 * SPACER) # Add extra padding
- (2 * V_SPACER) # Additional vertical spacers
)
return free_space > space
def render_instructions(self, instructions: INSTRUCTIONS) -> None:
"""Render the instructions onto the image.
Args:
instructions (INSTRUCTIONS): a list of instructions
"""
for instruction in instructions:
command, coordinates, text, kwargs = instruction
try:
method = getattr(self.draw, command)
except AttributeError:
config.LOGGER.error(f'No such method {method}.')
continue
if command == 'text':
method(coordinates, text, **kwargs)
else:
method(coordinates, **kwargs)
@dataclass
class Section:
"""Represents an image section.
Attributes:
instructions (INSTRUCTIONS): a list of instructions for the rendering
command to draw onto the image
y (int): the vertical offset from the top edge of the image's canvas
"""
y: int
def __post_init__(self) -> None:
"""After initialization, create a list of rendering instructions.
An individual instruction is like so:
1. (str) type of render instruction for ImageDraw.Draw
2. (Tuple[int, int]) a x, y coordinate for the starting point of
the render
3. (str, None) text if required for section
4. (Dict[str, Union[str, int]]): kwargs for the render instruction
"""
self.instructions: INSTRUCTIONS = []
def _next_y(self, delta: int) -> None:
"""Get the next value for y given a delta.
To prevent vertical clutter, a small value (SPACER) will also pad y.
Args:
delta (int): amount to increase y
"""
self.y += delta + SPACER
@dataclass
class SectionText(Section):
"""Represents a text element on one line.
Attributes:
text (str): contents of the string
color (str): color in hex format
font (ImageFont.FreeTypeFont): the font & size used for the text
"""
text: str
color: str
font: ImageFont.FreeTypeFont
def __post_init__(self) -> None:
"""Create text and insert into drawing."""
super().__post_init__()
if self.font == TITLE_FONT:
self.y += V_SPACER
for line in wrap(self.text, width=MAX_C_PER_LINE):
self.instructions.append(
(
'text',
(H_SPACER, self.y),
line,
{'fill': self.color, 'font': self.font}
)
)
self._next_y(self.font.size)
@dataclass
class SectionFooter(Section):
"""Represents a specialized text element at the bottom of the image.
Currently contains the date.
Unlike other sections, the vertical offset is not required, because
the footer is rendered relative to the bottom right corner of the canvas.
Because of this characteristic, the footer also does not need to inherit
from the Section parent class.
"""
def __post_init__(self) -> None:
"""Create footer (text) for this image.
Footers currently only contain the date and time.
"""
super().__post_init__()
dt = pendulum.now()
message = f'Generated at: {dt.to_datetime_string()}'
self.instructions.append(
(
'text',
(config.WIDTH - H_SPACER, config.LENGTH - V_SPACER),
message,
{'fill': TEXT_COLOR, 'font': FOOTER_FONT, 'anchor': 'rs'}
)
)
@dataclass
class SectionGauge(Section):
"""Represents a gauge within an image.
Attributes:
colors (List[str]): a list of hex-format colors that correspond the
gauge sequentially
created_gauge_values (Dict[float, int]): a dictionary of to-be-rendered
gauge marks with keys being the marks and their values being the
horizontal offset from the left edge to that given mark
last_gauge_offset (int): the offset of the most recent mark that can be
rendered successfully; see last_gauge_value
last_gauge_value (float): the most recent mark that can be rendered
successfully; this value is also the furthest right mark from the
left edge
value (int): the value within a gauge
values (List[int]): a list of numeric marks on the gauge
"""
value: int
values: List[int]
colors: List[str]
def __post_init__(self) -> None:
"""Create gauge given a value and marks (values).
Args:
value (int): the reading to use
values (List[int]): numeric marks along the gauge
colors (List[int]): color to paint sections between marks
"""
super().__post_init__()
self.created_gauge_values: Dict[float, int] = {}
sort_values = sorted(self.values)
if self.values != sort_values:
config.LOGGER.warning('The values were unsorted.')
# config.LOGGER.warning(f'Module: {self.module}')
config.LOGGER.warning(f'Values: {self.values}')
end_a = sort_values[0]
end_b = sort_values[-1]
# The first mark will use the default text color.
self.colors.insert(0, TEXT_COLOR)
x0 = GAUGE_OFFSET
y0 = self.y + SECTION_FONT.size + SPACER
y1 = y0 + SECTION_FONT.size
last_x0 = x0
# Draw the gauge first
for val, color in zip(self.values, self.colors):
offset = self.get_offset(val, end_a, end_b)
if (getattr(self, 'last_gauge_value', None) is None
or not self.does_text_collide(val, offset)):
self.create_value(val, offset, color)
c0 = (last_x0, y0)
c1 = (offset, y1)
self.instructions.append(
('rectangle', (c0, c1), None, {'fill': color}))
last_x0 = offset
offset = self.get_offset(self.value, end_a, end_b)
if not self.does_value_collide(offset):
self.instructions.append(
(
'text',
(offset, self.y),
str(self.value),
{
'fill': TEXT_COLOR,
'font': SECTION_FONT,
'anchor': 'mt',
'stroke_width': GAUGE_VALUE_STROKE,
'stroke_fill': GAUGE_LINE_COLOR,
}
)
)
self.instructions.append(
(
'line',
((offset, y0), (offset, y1)),
None,
{
'fill': GAUGE_LINE_COLOR,
'width': GAUGE_LINE_WIDTH,
}
)
)
self._next_y(2 * SECTION_FONT.size + SPACER)
def create_value(self, value: int, offset: int, color: str) -> None:
"""Create a gauge value (mark).
Args:
value (int): a gauge value or mark
offset (int): horizontal offset for this current value
color (str): color in hex format
"""
self.instructions.append(
(
'text',
(offset, self.y),
str(value),
{
'fill': color,
'font': SECTION_FONT,
'anchor': 'mt',
}
)
)
self.last_gauge_value = value
self.last_gauge_offset = offset
self.created_gauge_values[value] = offset
def get_offset(self, value: int, end_a: int, end_b: int) -> int:
"""Get the current gauge offset.
end_a <= value <= end_b
Args:
value (int): the value to measure in gauge
end_a (int): the minimum of the gauge
end_b (int): the maximum of the gauge
Returns:
int: horizontal pixel offset
"""
length = end_b - end_a
return (
(value - end_a)
* GAUGE_WIDTH
// length
+ GAUGE_OFFSET
)
def does_text_collide(self, value: float, offset: int) -> bool:
"""Determine whether new text will collide with existing text.
Specifically, check the magnitude (number of digits) for both
value and last_val and check whether they may possibly overlap
in bounding box.
value should always be greater than or equal to
self.last_gauge_value.
Args:
value (float): the current value
offset (int): the current value's offset
Returns:
bool: whether text will collide (True) or not (False)
"""
width = self.get_number_half_width(value)
last_width = self.get_number_half_width(self.last_gauge_value)
config.LOGGER.info(f'value: {value}, last: {self.last_gauge_value}')
config.LOGGER.info(f'width: {width}, last_width: {last_width}')
return (offset - width) < (self.last_gauge_offset + last_width)
def does_value_collide(self, offset: int) -> bool:
"""Gauges whether the gauge value may collide with any mark.
Because some marks may not have been rendered,
self.created_gauge_values is used to ensure collision check with
only rendered marks.
Similar to does_gauge_text_collide but checks both closest smallest
and closest largest values.
Args:
offset (int): the current value's offset
Returns:
bool: whether text will collide (True) or not (False)
"""
if self.value in self.created_gauge_values:
return True
width = self.get_number_half_width(self.value)
# Not to be confused with dict.values(), these are keys.
values = list(self.created_gauge_values)
values.append(self.value)
values.sort()
index = values.index(self.value)
below = values[index - 1]
above = values[index + 1]
below_width = self.get_number_half_width(below)
if (offset - width) < (self.created_gauge_values[below] + below_width):
return True
above_width = self.get_number_half_width(above)
if (self.created_gauge_values[above] - above_width) < (offset + width):
return True
return False
def get_number_half_width(self, number: float) -> int:
"""Get half the pixel width of a number determined by the font.
Args:
number (float): the number to convert to half pixel width
Returns:
int: half the pixel width of a number, rounded up
"""
symbols = 0
# Handle negative sign
if number < 0:
symbols += 1
number = abs(number)
# Handle decimals
if number != int(number):
symbols += 1
if number >= 1:
digits = floor(log10(number)) + 1
else:
digits = 1
return ceil((digits + symbols) * SECTION_CHAR / 2)