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
547
548
549
550
551
552
553
554
555 | """Lays every image the tests ship with on one page, each captioned with what the
file itself declares.
The Python twin of the `write_image_gallery` example in Rust.
Nothing in the captions is written by hand: each line is read back out of the image
after it was parsed, so the page is a statement of what the library understood rather
than of what the example was told. A file that declares nothing says so, which is the
point of showing it next to the ones that do.
What each caption says is written in the language `HQF_PDF_LANG` names. The names of
the files are not, and neither is `sRGB`: both are what is written on the disk and in
the file.
Usage: python examples/write_image_gallery.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_image_gallery.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# Every image committed for the tests.
IMAGES = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images"
# The page, and the grid laid over it.
MARGIN = 30.0
COLUMNS = 4
ROWS = 6
# The tallest and widest a thumbnail is drawn.
THUMBNAIL = (110.0, 92.0)
# The caption under each thumbnail.
CAPTION_SIZE = 5.6
CAPTION_LEADING = 7.4
# Ink.
TEXT = hqf_pdf.Rgb(0.15, 0.16, 0.2)
FADED = hqf_pdf.Rgb(0.42, 0.44, 0.5)
TILE = hqf_pdf.Rgb(0.95, 0.96, 0.97)
# The name of the colour profile a file may declare it was read through. It is what the
# profile is called, not a word of any language.
SRGB = "sRGB"
# The name of the space a photograph its camera says it took in Adobe RGB (1998) is read
# through, as IEC 61966-2-5 calls it.
OPRGB = "opRGB"
@dataclass(frozen=True)
class Plural:
"""A word in its two numbers.
English and French both keep the singular for one and take the plural from two
upwards, which is the whole of the rule the captions need: a count of bits is never
nought, and a table of colours never holds fewer than two.
"""
# The form the word takes for one.
one: str
# The form it takes for every other count.
many: str
def of(self, count: int) -> str:
"""The form this word takes for ``count``."""
return self.one if count == 1 else self.many
@dataclass(frozen=True)
class Words:
"""The words the captions are written in, one set per language.
The names of the files are not among them, and neither is the name of the colour
profile a file may declare it was read through.
"""
# What the page is called, drawn at its head.
title: str
# What the document is called in what the file says of itself, which is a name
# rather than the sentence drawn on the page.
file_title: str
# What stands between the two sides of a picture, in pixels and in dots.
by: str
# What a measurement in pixels is called.
pixels: str
# What a depth of one and of more than one is called.
bits: Plural
# What a resolution is called.
dots: str
# What one pixel of a grey picture stands for.
grey: str
# What one pixel of a three-channel picture stands for.
rgb: str
# What one pixel of a four-ink picture stands for.
cmyk: str
# What stands before the size of a palette.
table_of: str
# What a palette holds, of one colour and of more.
colours: Plural
# What a picture in a space of none of those kinds stands for.
other_space: str
# What stands before the way up a file declares.
seen: str
# The ways up, in the order of the numbers a file names them by: mirrored left to
# right, upside down, mirrored top to bottom, mirrored and turned left, turned
# right, mirrored and turned right, turned left, and last the one a number nothing
# names falls back to.
ways_up: tuple[str, ...]
# What a picture that carries an opacity for every pixel declares.
alpha: str
# What a picture that drops one colour declares.
color_key: str
# What stands before the name of the profile a picture was read through.
read_through: str
# What a file that declares nothing beyond its shape says instead.
nothing_else: str
# The captions in English.
ENGLISH = Words(
title="Every picture the tests ship with, and what each file says about itself",
file_title="hqf-pdf image gallery",
by="by",
pixels="pixels",
bits=Plural(one="bit", many="bits"),
dots="dots to the inch",
grey="grey",
rgb="red, green, blue",
cmyk="four inks",
table_of="a table of",
colours=Plural(one="colour", many="colours"),
other_space="colours of some other kind",
seen="seen",
ways_up=(
"mirrored left to right",
"upside down",
"mirrored top to bottom",
"mirrored, turned left",
"turned right",
"mirrored, turned right",
"turned left",
"the way it is stored",
),
alpha="opacity per pixel",
color_key="one colour left out",
read_through="read through",
nothing_else="declaring nothing else of itself",
)
# The captions in French.
FRENCH = Words(
title="Toutes les images livrées avec les tests, et ce que chaque fichier dit "
"de lui-même",
file_title="Galerie d’images hqf-pdf",
by="sur",
pixels="pixels",
bits=Plural(one="bit", many="bits"),
dots="points par pouce",
grey="du gris",
rgb="du rouge, du vert, du bleu",
cmyk="quatre encres",
table_of="une table de",
colours=Plural(one="couleur", many="couleurs"),
other_space="des couleurs d’un autre genre",
seen="vue",
ways_up=(
"en miroir gauche-droite",
"à l’envers",
"en miroir haut-bas",
"en miroir, tournée à gauche",
"tournée à droite",
"en miroir, tournée à droite",
"tournée à gauche",
"telle qu’elle est stockée",
),
alpha="opacité par pixel",
color_key="une couleur laissée de côté",
read_through="lue à travers",
nothing_else="ne déclarant rien d’autre",
)
# The captions in Dutch.
DUTCH = Words(
title="Elke afbeelding die bij de tests hoort, en wat elk bestand over zichzelf zegt",
file_title="Afbeeldingengalerij van hqf-pdf",
by="bij",
pixels="pixels",
bits=Plural(one="bit", many="bits"),
dots="punten per inch",
grey="grijs",
rgb="rood, groen, blauw",
cmyk="vier inkten",
table_of="een tabel van",
colours=Plural(one="kleur", many="kleuren"),
other_space="kleuren van een andere soort",
seen="gezien",
ways_up=(
"links-rechts gespiegeld",
"ondersteboven",
"boven-onder gespiegeld",
"gespiegeld, naar links gedraaid",
"naar rechts gedraaid",
"gespiegeld, naar rechts gedraaid",
"naar links gedraaid",
"zoals ze is opgeslagen",
),
alpha="dekking per pixel",
color_key="één kleur weggelaten",
read_through="gelezen via",
nothing_else="zonder verder iets over zichzelf te zeggen",
)
# The captions in Portuguese.
PORTUGUESE = Words(
title="Cada imagem que acompanha os testes, e o que cada ficheiro diz de si mesmo",
file_title="Galeria de imagens do hqf-pdf",
by="por",
pixels="píxeis",
bits=Plural(one="bit", many="bits"),
dots="pontos por polegada",
grey="cinzento",
rgb="vermelho, verde, azul",
cmyk="quatro tintas",
table_of="uma tabela de",
colours=Plural(one="cor", many="cores"),
other_space="cores de outro tipo",
seen="vista",
ways_up=(
"espelhada da esquerda para a direita",
"de pernas para o ar",
"espelhada de cima para baixo",
"espelhada, rodada para a esquerda",
"rodada para a direita",
"espelhada, rodada para a direita",
"rodada para a esquerda",
"tal como está guardada",
),
alpha="opacidade por píxel",
color_key="uma cor excluída",
read_through="lida através de",
nothing_else="sem declarar mais nada de si",
)
# The captions in Italian.
ITALIAN = Words(
title="Ogni immagine fornita con i test, e ciò che ogni file dice di sé",
file_title="Galleria di immagini di hqf-pdf",
by="per",
pixels="pixels",
bits=Plural(one="bit", many="bits"),
dots="punti per pollice",
grey="grigio",
rgb="rosso, verde, blu",
cmyk="quattro inchiostri",
table_of="una tabella di",
colours=Plural(one="colore", many="colori"),
other_space="colori di altro tipo",
seen="vista",
ways_up=(
"specchiata da sinistra a destra",
"capovolta",
"specchiata dall’alto in basso",
"specchiata, ruotata a sinistra",
"ruotata a destra",
"specchiata, ruotata a destra",
"ruotata a sinistra",
"com’è memorizzata",
),
alpha="opacità per pixel",
color_key="un colore escluso",
read_through="letta tramite",
nothing_else="senza dichiarare altro di sé",
)
# The captions in Spanish.
SPANISH = Words(
title="Cada imagen que traen las pruebas, y lo que cada archivo dice de sí mismo",
file_title="Galería de imágenes de hqf-pdf",
by="por",
pixels="píxeles",
bits=Plural(one="bit", many="bits"),
dots="puntos por pulgada",
grey="gris",
rgb="rojo, verde, azul",
cmyk="cuatro tintas",
table_of="una tabla de",
colours=Plural(one="color", many="colores"),
other_space="colores de otro tipo",
seen="vista",
ways_up=(
"reflejada de izquierda a derecha",
"cabeza abajo",
"reflejada de arriba abajo",
"reflejada, girada a la izquierda",
"girada a la derecha",
"reflejada, girada a la derecha",
"girada a la izquierda",
"tal como está guardada",
),
alpha="opacidad por píxel",
color_key="un color excluido",
read_through="leída mediante",
nothing_else="sin declarar nada más de sí misma",
)
# The captions in German.
GERMAN = Words(
title="Jedes Bild, das die Tests mitbringen, und was jede Datei über sich sagt",
file_title="hqf-pdf-Bildergalerie",
by="mal",
pixels="Pixel",
bits=Plural(one="Bit", many="Bit"),
dots="Punkte pro Zoll",
grey="Grau",
rgb="Rot, Grün, Blau",
cmyk="vier Farben",
table_of="eine Tabelle mit",
colours=Plural(one="Farbe", many="Farben"),
other_space="Farben anderer Art",
seen="Ansicht:",
ways_up=(
"von links nach rechts gespiegelt",
"auf dem Kopf",
"von oben nach unten gespiegelt",
"gespiegelt, nach links gedreht",
"nach rechts gedreht",
"gespiegelt, nach rechts gedreht",
"nach links gedreht",
"so, wie es gespeichert ist",
),
alpha="Deckkraft je Pixel",
color_key="eine Farbe ausgespart",
read_through="gelesen über",
nothing_else="gibt sonst nichts über sich an",
)
# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}
def colour_of(image: hqf_pdf.Image, words: Words) -> str:
"""What one pixel of the image stands for, in the fewest words that still say it."""
palette = image.color_space.palette
if palette is not None:
colours = len(palette) // 3
return f"{words.table_of} {colours} {words.colours.of(colours)}"
return {1: words.grey, 3: words.rgb, 4: words.cmyk}.get(
image.color_space.components, words.other_space
)
def facts(image: hqf_pdf.Image, words: Words) -> list[str]:
"""What the file says about itself, one statement at a time.
A file that says nothing beyond its shape says so: the point of the page is that
both kinds sit side by side.
"""
bits = image.bits_per_component
facts = [
f"{image.width} {words.by} {image.height} {words.pixels}",
colour_of(image, words),
f"{bits} {words.bits.of(bits)}",
]
stated = []
resolution = image.resolution
if resolution is not None:
stated.append(
f"{resolution.x:.0f} {words.by} {resolution.y:.0f} {words.dots}"
)
orientation = image.orientation
if orientation is not None:
stated.append(f"{words.seen} {way_up(words, orientation.tag)}")
if image.has_alpha:
stated.append(words.alpha)
if image.color_key is not None:
stated.append(words.color_key)
if image.icc_profile is not None:
space = OPRGB if image.icc_profile == hqf_pdf.adobe_rgb_icc_profile() else SRGB
stated.append(f"{words.read_through} {space}")
facts.extend(stated if stated else [words.nothing_else])
return facts
def packed(font: hqf_pdf.FontHandle, width: float, statements: list[str]) -> list[str]:
"""The statements laid end to end, broken into lines that fit ``width``.
Nothing is dropped: a caption that will not fit on one line takes as many as it
needs, which is what keeps the page a full account of what was read.
"""
lines: list[str] = []
for statement in statements:
joined = f"{lines[-1]}, {statement}" if lines else ""
if lines and font.measure(joined, CAPTION_SIZE) <= width:
lines[-1] = joined
else:
lines.append(statement)
return lines
def way_up(words: Words, tag: int) -> str:
"""The way up an ``Exif`` header names by its number, in words. A number nothing
names falls to the last of them."""
if 2 <= tag <= 8:
return words.ways_up[tag - 2]
return words.ways_up[7]
def text(
content: hqf_pdf.Content,
font: hqf_pdf.FontHandle,
size: float,
at: tuple[float, float],
colour: hqf_pdf.Rgb,
s: str,
) -> None:
"""Draws a line of text, left-aligned, in a colour of its own."""
content.set_fill(colour)
content.draw_text(font, size, at[0], at[1], s)
def text_fitted(
content: hqf_pdf.Content,
font: hqf_pdf.FontHandle,
size: float,
at: tuple[float, float],
width: float,
colour: hqf_pdf.Rgb,
s: str,
) -> None:
"""Draws a line of text, shortened until it fits the width it is given."""
line = s
while font.measure(line, size) > width and len(line) > 1:
line = line[:-2] + "…"
text(content, font, size, at, colour, line)
def tile(
content: hqf_pdf.Content,
font: hqf_pdf.FontHandle,
handle: hqf_pdf.ImageHandle,
lines: list[str],
at: tuple[float, float],
cell: tuple[float, float],
) -> None:
"""Draws one tile: the picture inside its box, and what the file says under it."""
x, y = at
cell_width, cell_height = cell
caption_height = CAPTION_LEADING * len(lines)
box_height = cell_height - caption_height - 6.0
content.set_fill(TILE)
content.rect(x, y + caption_height + 6.0, cell_width, box_height)
content.fill()
# The picture keeps its proportions inside the box, and sits in the middle of it.
width, height = handle.fit_within(
min(THUMBNAIL[0], cell_width - 8.0), min(THUMBNAIL[1], box_height)
)
content.draw_image(
handle,
x + (cell_width - width) / 2.0,
y + caption_height + 6.0 + (box_height - height) / 2.0,
width,
height,
)
for index, line in enumerate(lines):
colour = TEXT if index == 0 else FADED
text_fitted(
content,
font,
CAPTION_SIZE,
(x, y + caption_height - CAPTION_LEADING * (index + 1) + 2.0),
cell_width,
colour,
line,
)
def main() -> None:
language = _language.from_environment()
words = _language.words_of(WORDS, language)
# A named file is written as named; the default one carries the language, so the two
# languages do not overwrite each other in `tmp/`.
out = _out.output_path(
Path(_language.file_name("image_gallery.pdf", language)).stem
)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
document.set_info("Title", words.file_title)
font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
page = hqf_pdf.Page.a4()
cell_width = (page.width - 2.0 * MARGIN) / COLUMNS - 6.0
tiles = []
for path in sorted(path for path in IMAGES.iterdir() if path.is_file()):
image = hqf_pdf.Image.from_path(path)
lines = [path.name, *packed(font, cell_width, facts(image, words))]
tiles.append((document.add_image(image), lines))
content = hqf_pdf.Content()
text(
content,
font,
13.0,
(MARGIN, page.height - MARGIN - 10.0),
TEXT,
words.title,
)
top = page.height - MARGIN - 34.0
cell_height = (top - MARGIN) / ROWS
for index, (handle, lines) in enumerate(tiles):
column, row = index % COLUMNS, index // COLUMNS
if row >= ROWS:
print(
f"{len(tiles)} pictures do not fit on one page; the rest are left off"
)
break
tile(
content,
font,
handle,
lines,
(MARGIN + (cell_width + 6.0) * column, top - cell_height * (row + 1)),
(cell_width, cell_height - 6.0),
)
page.set_content(content)
document.add_page(page)
written = document.write(out)
print(f"wrote {out}: {written} bytes, {len(tiles)} pictures")
if __name__ == "__main__":
main()
|