write_image_gallery.py

The Python file of the “A gallery of picture formats” example. The four picture formats read — JPEG, PNG, BMP and TIFF — shown across every picture shipped with the library, each captioned with what its own file declares.

Python 395 lines

What this example is for

Before choosing a library the question is nearly always the same: will it read the pictures we already have? We read these four formats. JPEG, which is what a camera and a telephone produce. PNG, which is what a screenshot comes in, and what a logo with transparent parts comes in. BMP, the plain uncompressed one older software still writes. And TIFF, which is what a scanner and a fax machine write, whole batches of sheets at a time. Between them they cover what comes off a camera, off a screen, off a scanner and off an older machine, which is very nearly everything a working document is built from.

What this example shows

  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
"""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"


@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",
)

# 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}


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:
        stated.append(f"{words.read_through} {SRGB}")

    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()