A register whose every part says where it came from

Two sittings bound into one file. Each page carries a record of its own — what it is, whose hand wrote it, when — the photograph on the second page carries one too, and each transcription is tied to the page it transcribes rather than to the file at large. Tying an attached file to anything but the whole document only exists from PDF 2.0 on, so the file declares 2.0.

Python write_provenance.py 428 lines
  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
"""A file whose every part says where it came from.

The Python twin of the `write_provenance` example in Rust. A document says what
it is, and that has always been written once, for the whole file. It is not
enough for anything assembled out of pieces: a register bound from two sittings,
a scan whose plate belongs to somebody other than whoever holds the paper. Here
each page carries a packet of its own, the plate on the second page carries one
too, and the transcription of each sitting is tied to the page it transcribes
rather than to the file at large.

Tying a carried file to anything but the document as a whole arrived with PDF
2.0, so the file declares 2.0. Nothing is raised on the caller's behalf: a file
that tied one while declaring less would be refused rather than written.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set the register is bound in. Every one of them is written twice: once on the
page and once in the packet the page carries, from the one set, so that what a
person reads and what a machine reads cannot drift apart. What is not a word
stands apart from them — the names the carried files are looked up by, the
clerks' own names, and the dates the sittings were written down.

Usage: python examples/write_provenance.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_provenance.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# A4, in points.
SHEET = (595.276, 841.890)

# How far in from the edge of the sheet everything is set.
MARGIN = 64.0

# How far in from the left edge what a part says stands, leaving the label to its left.
SAID = 220.0

# How wide the plate is drawn on the page, in points.
PLATE = 180.0

# The name the record of the scan is carried under.
SCAN = "plate-12-scan.xml"

# The two sittings the register is bound from: who wrote each down, when, and the name
# its transcription is carried under. What the page says of it is a word, and stands in
# `Words` under the same order.
SITTINGS = (
    ("R. Delaunay", "1911-03-14T09:00:00+01:00", "first-sitting.xml"),
    ("M. Aubert", "1911-06-02T14:30:00+02:00", "second-sitting.xml"),
)


@dataclass(frozen=True)
class Words:
    """Every word the register is bound in, in one language."""

    # What the file says it is.
    title: str
    # What each sitting is called, in its band and in its own packet.
    sittings: tuple[str, str]
    # What whoever wrote a sitting down is called, set after their name.
    clerk: str
    # What a page says it is about.
    subject: str
    # What each page says under its band.
    lines: tuple[tuple[str, str, str], tuple[str, str, str]]
    # The heading over what a page says of itself, the one over what the file carries,
    # and the one over what the plate says of itself.
    headings: tuple[str, str, str]
    # What a part is asked about: its title, the hand that wrote it, when it was
    # written, and the file tied to it.
    asked: tuple[str, str, str, str]
    # What claims each carried file, in the order they are carried.
    claimed_by: tuple[str, str, str]
    # The row that says the file at large claims none of them.
    at_large: tuple[str, str]
    # What the plate is called, on the page and in its own packet.
    plate: str
    # What the plate is asked, and who answers to it.
    holder: tuple[str, str]
    # What the plate says it is about.
    plate_subject: str
    # What each carried file says it is: a transcription, and the record of a scan.
    carried: tuple[str, str]
    # The closing note at the foot of the last page.
    closing: tuple[str, str, str, str]

    def hand(self, index: int) -> str:
        """Who wrote the sitting at `index` down: their name, then what such a person is
        called."""
        return f"{SITTINGS[index][0]}, {self.clerk}"


# The register in English.
ENGLISH = Words(
    title="A register bound from two sittings",
    sittings=("First sitting", "Second sitting"),
    clerk="clerk",
    subject="One sitting of the register",
    lines=(
        (
            "This page carries a packet of its own, saying what it is, whose hand",
            "wrote it and when. The file says nothing on its behalf: read the page",
            "out of the file and what it says travels with it.",
        ),
        (
            "The plate below is a part in its own right. It says who holds it, which",
            "is not who holds the paper, and it carries the record of the scan it",
            "came off — tied to the plate, not to the file.",
        ),
    ),
    headings=(
        "What this page says about itself",
        "What this file carries, and which part claims it",
        "What the plate says about itself",
    ),
    asked=(
        "Its title",
        "The hand that wrote it",
        "When it was written",
        "The file tied to it",
    ),
    claimed_by=(
        "The first page",
        "The second page",
        "The plate on the second page",
    ),
    at_large=("Claimed by the file at large", "nothing"),
    plate="Plate 12, second sitting",
    holder=("Who holds it", "Departmental archive"),
    plate_subject="The plate, which is held apart from the paper",
    carried=("The sitting, transcribed", "How the plate was scanned"),
    closing=(
        "Every carried file is offered to every reader through the list of embedded",
        "files, whichever part of the document claims it. What the tie adds is which",
        "part it belongs to — and a file one part claims leaves the tie the document",
        "itself holds, so nothing is ever said to belong to two things at once.",
    ),
)

# The register in French.
FRENCH = Words(
    title="Un registre relié à partir de deux séances",
    sittings=("Première séance", "Deuxième séance"),
    clerk="greffier",
    subject="Une séance du registre",
    lines=(
        (
            "Cette page porte son propre paquet, qui dit ce qu'elle est, de quelle",
            "main elle a été écrite et quand. Le fichier ne dit rien à sa place :",
            "sortez la page du fichier et ce qu'elle dit part avec elle.",
        ),
        (
            "La planche ci-dessous est une pièce à part entière. Elle dit qui la",
            "détient, qui n'est pas celui qui détient le papier, et elle porte le",
            "relevé de la numérisation d'où elle vient — lié à elle, pas au fichier.",
        ),
    ),
    headings=(
        "Ce que cette page dit d'elle-même",
        "Ce que ce fichier porte, et quelle partie le revendique",
        "Ce que la planche dit d'elle-même",
    ),
    asked=(
        "Son titre",
        "La main qui l'a écrite",
        "Quand elle a été écrite",
        "Le fichier qui lui est lié",
    ),
    claimed_by=(
        "La première page",
        "La deuxième page",
        "La planche de la deuxième page",
    ),
    at_large=("Revendiqué par le fichier entier", "rien"),
    plate="Planche 12, deuxième séance",
    holder=("Qui la détient", "Archives départementales"),
    plate_subject="La planche, détenue à part du papier",
    carried=("La séance, transcrite", "Comment la planche a été numérisée"),
    closing=(
        "Chaque fichier porté est proposé à tout lecteur par la liste des pièces",
        "jointes, quelle que soit la partie du document qui le revendique. Le lien",
        "ajoute à quelle partie il appartient — et un fichier qu'une partie revendique",
        "quitte le lien que le document tient, donc rien n'est jamais à deux choses.",
    ),
)

# 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 plate():
    """The plate: a square of grey read off a pattern, needing no file beside it."""
    side = 64
    samples = bytes(
        ((across * 4) ^ (down * 4)) & 0xFF
        for down in range(side)
        for across in range(side)
    )
    return hqf_pdf.Image.from_gray(side, side, samples)


def head(content, font, words, index):
    """Draw the band across the head of a page, and the lines under it."""
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.16, 0.20, 0.26))
    content.rect(0.0, SHEET[1] - 96.0, SHEET[0], 96.0)
    content.fill()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.draw_text(font, 20.0, MARGIN, SHEET[1] - 58.0, words.sittings[index])
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.25))
    y = SHEET[1] - 140.0
    for line in words.lines[index]:
        content.draw_text(font, 11.0, MARGIN, y, line)
        y -= 18.0
    content.restore_state()


def says(content, font, top, heading, rows):
    """Draw what one part of the file says about itself, as a pair of columns."""
    content.save_state()
    content.set_stroke(hqf_pdf.Color.gray(0.82))
    content.set_line_width(0.4)
    content.move_to(MARGIN, top)
    content.line_to(SHEET[0] - MARGIN, top)
    content.stroke()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.1))
    content.draw_text(font, 13.0, MARGIN, top - 28.0, heading)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.3))
    y = top - 56.0
    for said, written in rows:
        content.draw_text(font, 11.0, MARGIN, y, said)
        content.draw_text(font, 10.0, MARGIN + SAID, y, written)
        y -= 20.0
    content.restore_state()


def foot(content, font, words):
    """Draw the closing note, at the foot of the last page."""
    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.45))
    y = 178.0
    for line in words.closing:
        content.draw_text(font, 10.5, MARGIN, y, line)
        y -= 17.0
    content.set_fill(hqf_pdf.Color.gray(0.5))
    content.draw_text(font, 8.0, MARGIN, 62.0, "HQF Development")
    content.restore_state()


def first_sheet(font, words):
    """The first page: what it says of itself, and the transcription tied to it."""
    content = hqf_pdf.Content()
    head(content, font, words, 0)
    says(
        content,
        font,
        SHEET[1] - 220.0,
        words.headings[0],
        (
            (words.asked[0], words.sittings[0]),
            (words.asked[1], words.hand(0)),
            (words.asked[2], SITTINGS[0][1]),
            (words.asked[3], SITTINGS[0][2]),
        ),
    )
    says(
        content,
        font,
        SHEET[1] - 380.0,
        words.headings[1],
        (
            (SITTINGS[0][2], words.claimed_by[0]),
            (SITTINGS[1][2], words.claimed_by[1]),
            (SCAN, words.claimed_by[2]),
            (words.at_large[0], words.at_large[1]),
        ),
    )
    return content


def second_sheet(font, image, words):
    """The second page: the plate, what it says of itself, and the note."""
    content = hqf_pdf.Content()
    head(content, font, words, 1)

    top = SHEET[1] - 220.0
    content.draw_image(image, MARGIN, top - PLATE, PLATE, PLATE)
    content.save_state()
    content.set_stroke(hqf_pdf.Color.gray(0.7))
    content.set_line_width(0.5)
    content.rect(MARGIN, top - PLATE, PLATE, PLATE)
    content.stroke()
    content.set_fill(hqf_pdf.Color.gray(0.45))
    content.draw_text(font, 9.0, MARGIN, top - PLATE - 14.0, words.plate)
    content.restore_state()

    says(
        content,
        font,
        top - PLATE - 44.0,
        words.headings[2],
        (
            (words.asked[0], words.plate),
            (words.holder[0], words.holder[1]),
            (words.asked[3], SCAN),
        ),
    )
    foot(content, font, words)
    return content


def said_by(words, index):
    """The packet a page speaks in: what it is, whose hand wrote it, and when."""
    return hqf_pdf.Xmp.facts(
        hqf_pdf.Metadata(
            title=words.sittings[index],
            author=words.hand(index),
            subject=words.subject,
            created=SITTINGS[index][1],
        )
    )


def transcription(words, index):
    """A transcription carried inside the file, under the name it is looked up by."""
    return hqf_pdf.Attachment(
        SITTINGS[index][2],
        words.carried[0],
        "text/xml",
        hqf_pdf.Relationship.Alternative,
        SITTINGS[index][1],
        f'<sitting hand="{words.hand(index)}"/>\n'.encode(),
    )


def bind(document, font, image, words, carried):
    """The two pages, each carrying its own packet and the file tied to it."""
    first = hqf_pdf.Page(SHEET[0], SHEET[1])
    first.set_content(first_sheet(font, words))
    first.set_metadata(said_by(words, 0))
    first.set_associated_files([carried[0]])
    document.add_page(first)

    second = hqf_pdf.Page(SHEET[0], SHEET[1])
    second.set_content(second_sheet(font, image, words))
    second.set_metadata(said_by(words, 1))
    second.set_associated_files([carried[1]])
    document.add_page(second)


def main():
    """Write the register, and say where it went."""
    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("provenance.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    # Each transcription is claimed by the page it transcribes; the record of the scan
    # is claimed by the plate itself. Nothing here is claimed by the file at large, so
    # the file ties nothing to its catalogue.
    carried = [
        document.attach(transcription(words, 0)),
        document.attach(transcription(words, 1)),
    ]
    scan = document.attach(
        hqf_pdf.Attachment(
            SCAN,
            words.carried[1],
            "text/xml",
            hqf_pdf.Relationship.Supplement,
            "2026-02-19T11:05:00+01:00",
            b'<scan dpi="600" bits="8"/>\n',
        )
    )

    image = document.add_image(
        plate()
        .with_metadata(
            hqf_pdf.Xmp.facts(
                hqf_pdf.Metadata(
                    title=words.plate,
                    author=words.holder[1],
                    subject=words.plate_subject,
                )
            )
        )
        .associated_with([scan])
    )

    bind(document, font, image, words, carried)

    # Tying a carried file to anything but the document as a whole is ISO 32000-2, so
    # the file says 2.0 on its first line.
    document.set_version(hqf_pdf.Version.V2_0)
    document.set_metadata(hqf_pdf.Metadata(title=words.title, producer="hqf-pdf"))

    written = document.to_bytes()
    out.write_bytes(written)
    print(f"wrote {out}: {len(written)} bytes, every part saying where it came from")


if __name__ == "__main__":
    main()