write_tagged_pictures.py

Die Python-Datei des Beispiels „Eine Liste, deren Bilder ebenfalls sprechen“. Eine Teileliste, deren erste Spalte ein Bild statt eines Wortes ist. Jedes Bild trägt den Satz, den jemand an seiner Stelle hört, sodass in der Liste nichts für einen Leser verloren geht, der sie nicht sehen kann. Auf der Seite sind die Bilder einfach Bilder.

Python 468 Zeilen

Wofür dieses Beispiel da ist

Lesen Sie eine Teileliste am Telefon vor, und Sie sagen, was jedes Bild zeigt: den Deckel, das Typenschild, die kleine Temperaturanzeige. Eine Software, die ein Dokument vorliest, sagt gar nichts, denn ein Bild ist für sie nur ein Bild — und in einer Liste, in der das Bild die Spalte ist, die einen Artikel vom anderen unterscheidet, ist das keine verlorene Verzierung. Die ganze Zeile verstummt.

Was dieses Beispiel zeigt

  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
"""Writes a tagged parts list whose first column is a picture, not a word.

The Python twin of the `write_tagged_pictures` example in Rust: the same document,
through the binding rather than through the library directly.

A picture says nothing to something that reads a document aloud, so a tagged file
has to say it instead: each picture is marked as a figure of its own and carries the
words a reader hears in its place. That is what a cell's `alt` is for, and this is
what it comes to — a table whose every row is a row of the structure tree, whose text
cells are read as text, and whose picture cells are read as the sentence the catalogue
gave them.

The tree is not built by hand here: the table hands back the branch describing itself,
figures and all, from the same counter the page numbers its marks from.

Where `write_tagged` shows prose, headings and a table of figures, this shows the one
thing prose cannot: a picture inside a cell, standing for something a reader must be
told about.

The list is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
written. The language a document is in is part of what makes it readable aloud: the
structure tree carries the tag of the language its words are in, and it comes from the
same set of words as the words themselves.

Usage: python examples/write_tagged_pictures.py [out.pdf] [font.ttf]
       python examples/write_tagged_pictures.py out.pdf --archival
       python examples/write_tagged_pictures.py out.pdf --ua
       HQF_PDF_LANG=fr python examples/write_tagged_pictures.py
"""

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The pictures the list shows, committed with the tests.
PICTURES = (
    Path(__file__).resolve().parents[3] / "crates" / "hqf-pdf" / "tests" / "images"
)

# The left edge everything is set from.
MARGIN = 64.0

# The room the table has across an A4 page between the margins.
WIDTH = 595.276 - 2.0 * MARGIN

# The colour the heading row is painted on.
HEAD_FILL = hqf_pdf.Rgb.gray(0.88)


# The picture each part is shown by, under the committed images. A picture is the same
# picture in every language.
PART_PICTURES = ("logo.png", "hqf_development.png", "indexed_16colours.png")


@dataclass(frozen=True)
class Words:
    """Every word the list writes, in one language.

    The tag of the language is here too: a document that says nothing about the language
    its words are in cannot be read aloud properly, and it is one more thing a set of
    words has to get right.
    """

    # The tag the structure tree carries, saying what the words below are in.
    lang: str
    # The title the document is filed under, in its information dictionary and in its
    # metadata both.
    title: str
    # The line at the head of the page.
    heading: str
    # The heading of each column, in the order the columns are set.
    columns: tuple[str, str, str]
    # What each part is called, in the order the rows are written.
    names: tuple[str, str, str]
    # What each part is for.
    purposes: tuple[str, str, str]
    # What each picture is, said in words. A figure with nothing here is a figure
    # nothing can read out, and a validator says so.
    alts: tuple[str, str, str]
    # The paragraph under the list.
    closing: str
    # The page number at the foot, which is furniture rather than what the document
    # says.
    footer: str


# The list in English.
ENGLISH = Words(
    lang="en-GB",
    title="A tagged parts list",
    heading="Parts of the housing",
    columns=("Picture", "Part", "What it is for"),
    names=("Cover plate", "Rating label", "Heat scale"),
    purposes=(
        "Closes the housing once the board is seated.",
        "Carries the serial number and the supply it is rated for.",
        "Read against the winding to say how hot it is running.",
    ),
    alts=(
        "The house mark: a ring, one half blue and the other yellow.",
        "The maker's name, printed across the label in full.",
        "A band running from red at the top down to blue at the bottom.",
    ),
    closing=(
        "Every picture above is marked as a figure and carries the words a "
        "reader hears in its place, so nothing in this list is lost on somebody "
        "who cannot see it. The table itself is a branch of the structure tree: "
        "each row is a row there too, and each cell says which column it sits "
        "in."
    ),
    footer="Page 1 of 1",
)

# The list in French.
FRENCH = Words(
    lang="fr-FR",
    title="Une liste de pièces balisée",
    heading="Les pièces du boîtier",
    columns=("Image", "Pièce", "À quoi elle sert"),
    names=("Couvercle", "Plaque signalétique", "Échelle de température"),
    purposes=(
        "Ferme le boîtier une fois la carte en place.",
        "Indique le numéro de série et l’alimentation nominale.",
        "Posée sur le bobinage, indique la température à laquelle il fonctionne.",
    ),
    alts=(
        "La marque de la maison : un anneau, moitié bleu, moitié jaune.",
        "Le nom du fabricant, imprimé en entier sur l’étiquette.",
        "Une bande qui va du rouge en haut au bleu en bas.",
    ),
    closing=(
        ("Chaque image ci-dessus est balisée comme figure et s’accompagne des mots "
         "qu’on entend à sa place : rien de cette liste n’échappe à qui ne la voit "
         "pas. Le tableau lui-même est une branche de l’arbre de structure : chaque "
         "ligne y est aussi une ligne, et chaque cellule indique sa colonne.")
    ),
    footer="Page 1 sur 1",
)

# The list in Dutch.
DUTCH = Words(
    lang="nl-NL",
    title="Een getagde onderdelenlijst",
    heading="Onderdelen van de behuizing",
    columns=("Afbeelding", "Onderdeel", "Waarvoor het dient"),
    names=("Afdekplaat", "Typeplaatje", "Warmteschaal"),
    purposes=(
        "Sluit de behuizing zodra de print op zijn plaats zit.",
        "Vermeldt het serienummer en de voeding waarvoor het bestemd is.",
        "Wordt tegen de wikkeling afgelezen om te zeggen hoe warm ze draait.",
    ),
    alts=(
        "Het huismerk: een ring, de ene helft blauw en de andere geel.",
        "De naam van de fabrikant, voluit over het plaatje gedrukt.",
        "Een band die van rood bovenaan naar blauw onderaan loopt.",
    ),
    closing=(
        "Elke afbeelding hierboven is gemarkeerd als figuur en heeft de woorden die "
        "een lezer in haar plaats hoort, dus gaat niets van deze lijst verloren voor "
        "wie haar niet kan zien. De tabel zelf is een tak van de structuurboom: elke "
        "rij is daar ook een rij, en elke cel zegt in welke kolom ze staat."
    ),
    footer="Pagina 1 van 1",
)

# The list in Portuguese.
PORTUGUESE = Words(
    lang="pt-PT",
    title="Uma lista de peças etiquetada",
    heading="Peças da caixa",
    columns=("Imagem", "Peça", "Para que serve"),
    names=("Tampa", "Placa de características", "Escala térmica"),
    purposes=(
        "Fecha a caixa depois de assente a placa.",
        "Leva o número de série e a alimentação para que está dimensionada.",
        "Lê-se junto ao enrolamento para saber a que temperatura trabalha.",
    ),
    alts=(
        "A marca da casa: um anel, metade azul e metade amarelo.",
        "O nome do fabricante, impresso por extenso ao longo da placa.",
        "Uma faixa que vai do vermelho em cima ao azul em baixo.",
    ),
    closing=(
        "Cada imagem acima está marcada como figura e leva as palavras que um leitor "
        "ouve no seu lugar, por isso nada desta lista se perde para quem não a pode "
        "ver. A própria tabela é um ramo da árvore de estrutura: cada linha é também "
        "uma linha lá, e cada célula diz em que coluna está."
    ),
    footer="Página 1 de 1",
)

# The list in Italian.
ITALIAN = Words(
    lang="it-IT",
    title="Un elenco di pezzi marcato",
    heading="Pezzi del carter",
    columns=("Immagine", "Pezzo", "A cosa serve"),
    names=("Coperchio", "Targhetta dati", "Scala termica"),
    purposes=(
        "Chiude il carter una volta alloggiata la scheda.",
        "Porta il numero di serie e l’alimentazione per cui è dimensionato.",
        "Si legge sull’avvolgimento per sapere a che temperatura lavora.",
    ),
    alts=(
        "Il marchio della casa: un anello, metà blu e metà giallo.",
        "Il nome del produttore, stampato per intero lungo la targhetta.",
        "Una fascia che va dal rosso in alto al blu in basso.",
    ),
    closing=(
        "Ogni immagine qui sopra è marcata come figura e porta le parole che un "
        "lettore sente al suo posto, così niente di questo elenco va perso per chi "
        "non può vederlo. La tabella stessa è un ramo dell’albero di struttura: ogni "
        "riga è una riga anche lì, e ogni cella dice in quale colonna sta."
    ),
    footer="Pagina 1 di 1",
)

# The list in Spanish.
SPANISH = Words(
    lang="es-ES",
    title="Una lista de piezas etiquetada",
    heading="Piezas de la carcasa",
    columns=("Imagen", "Pieza", "Para qué sirve"),
    names=("Tapa", "Placa de características", "Escala térmica"),
    purposes=(
        "Cierra la carcasa una vez asentada la placa.",
        "Lleva el número de serie y la alimentación para la que está calculada.",
        "Se lee frente al bobinado para saber a qué temperatura funciona.",
    ),
    alts=(
        "La marca de la casa: un anillo, mitad azul y mitad amarilla.",
        "El nombre del fabricante, impreso entero a lo ancho de la placa.",
        "Una banda que va del rojo arriba al azul abajo.",
    ),
    closing=(
        "Cada imagen de arriba está marcada como figura y lleva las palabras que oye "
        "un lector en su lugar, así que nada de esta lista se pierde para quien no "
        "puede verla. La propia tabla es una rama del árbol de estructura: cada fila "
        "es también una fila allí, y cada celda dice en qué columna está."
    ),
    footer="Página 1 de 1",
)

# The list in German.
GERMAN = Words(
    lang="de-DE",
    title="Eine getaggte Stückliste",
    heading="Teile des Gehäuses",
    columns=("Bild", "Teil", "Wozu es dient"),
    names=("Deckplatte", "Typenschild", "Wärmeskala"),
    purposes=(
        "Schließt das Gehäuse, sobald die Platine sitzt.",
        "Trägt die Seriennummer und die Versorgung, für die es ausgelegt ist.",
        "Wird an der Wicklung abgelesen, um zu sagen, wie heiß sie läuft.",
    ),
    alts=(
        "Das Hauszeichen: ein Ring, eine Hälfte blau, die andere gelb.",
        "Der Name des Herstellers, voll ausgeschrieben quer über das Schild gedruckt.",
        "Ein Band, das oben rot beginnt und unten blau endet.",
    ),
    closing=(
        "Jedes Bild oben ist als Abbildung markiert und trägt die Worte, die ein "
        "Leser an seiner Stelle hört, also geht nichts in dieser Liste für jemanden "
        "verloren, der es nicht sehen kann. Die Tabelle selbst ist ein Zweig des "
        "Strukturbaums: Jede Zeile ist auch dort eine Zeile, und jede Zelle sagt, in "
        "welcher Spalte sie steht."
    ),
    footer="Seite 1 von 1",
)


# 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 heading(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    marks: hqf_pdf.Marks,
    page: int,
    words: Words,
) -> hqf_pdf.StructElement:
    """The heading, marked and numbered so that the tree can point at it."""
    number = marks.next_id()
    content.begin_tagged("H1", number)
    content.draw_text(handle, 18.0, MARGIN, 762.0, words.heading)
    content.end_marked()
    return hqf_pdf.StructElement("H1", children=[(page, number)])


def closing(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    marks: hqf_pdf.Marks,
    page: int,
    top: float,
    words: Words,
) -> hqf_pdf.StructElement:
    """The closing paragraph, broken into lines and marked as one run."""
    flow = hqf_pdf.TextFlow(
        handle, 10.0, leading=15.0, align=hqf_pdf.Align.Justify
    )
    lines = flow.break_lines(words.closing, WIDTH)
    numbers = flow.draw_tagged(content, lines, MARGIN, top, WIDTH, "P", marks)
    return hqf_pdf.StructElement("P", children=[(page, numbers[0])])


def parts_list(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    handles: list[hqf_pdf.ImageHandle],
    marks: hqf_pdf.Marks,
    page: int,
    words: Words,
) -> tuple[hqf_pdf.StructElement, float]:
    """The parts list, and the branch of the tree describing it.

    The pictures are drawn by the table, each into whatever rectangle its cell came
    to, and each marked as a figure carrying its own words.
    """
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.points(96.0),
            hqf_pdf.ColumnWidth.points(120.0),
            hqf_pdf.ColumnWidth.points(WIDTH - 216.0),
        ],
        WIDTH,
    )
    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8))
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.7)),
    )

    head_padding = hqf_pdf.Padding.symmetric(6.0, 5.0)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    handle,
                    10.0,
                    label,
                    align=hqf_pdf.Align.Left,
                    padding=head_padding,
                )
                for label in words.columns
            ],
            fill=HEAD_FILL,
        )
    )

    for image, name, purpose, alt in zip(
        handles, words.names, words.purposes, words.alts
    ):
        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell.image(
                        image,
                        alt=alt,
                        align=hqf_pdf.Align.Center,
                        valign=hqf_pdf.VAlign.Middle,
                        padding=hqf_pdf.Padding.uniform(5.0),
                    ),
                    hqf_pdf.Cell(
                        handle,
                        10.0,
                        name,
                        valign=hqf_pdf.VAlign.Middle,
                        padding=head_padding,
                    ),
                    hqf_pdf.Cell(
                        handle,
                        10.0,
                        purpose,
                        valign=hqf_pdf.VAlign.Middle,
                        padding=head_padding,
                    ),
                ],
                min_height=54.0,
            )
        )

    placement = table.fit(MARGIN, 736.0, 620.0)
    return placement.draw_tagged(content, page, marks), placement.bottom


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    archival = "--archival" in sys.argv
    ua = "--ua" in sys.argv
    sys.argv = [argument for argument in sys.argv if not argument.startswith("--")]
    # 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("tagged_pictures.pdf", language)).stem
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    if archival:
        document.set_conformance(hqf_pdf.PdfA.A3A)
    if ua:
        document.set_ua_conformance(hqf_pdf.PdfUa.One)
    if archival or ua:
        document.set_metadata(
            hqf_pdf.Metadata(
                title=words.title,
                producer="hqf-pdf",
                created="2026-07-26T09:30:00+02:00",
            )
        )
    document.set_info("Title", words.title)

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    handles = [
        document.add_image(hqf_pdf.Image.from_path(PICTURES / picture))
        for picture in PART_PICTURES
    ]

    content = hqf_pdf.Content()
    marks = hqf_pdf.Marks()
    children = [heading(content, handle, marks, 0, words)]
    table, bottom = parts_list(content, handle, handles, marks, 0, words)
    children.append(table)
    children.append(closing(content, handle, marks, 0, bottom - 24.0, words))

    # The page number is furniture, not what the document says, so it carries no number
    # and the tree never points at it.
    content.begin_artifact(hqf_pdf.Artifact.Footer)
    content.draw_text(handle, 9.0, MARGIN, 48.0, words.footer)
    content.end_marked()

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    document.set_structure(
        hqf_pdf.StructureTree(
            lang=words.lang,
            children=[
                hqf_pdf.StructElement(
                    "Document",
                    children=[hqf_pdf.StructElement("Sect", children=children)],
                )
            ],
        )
    )

    written = document.write(out)
    print(f"wrote {out} ({written} bytes)")


if __name__ == "__main__":
    main()