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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599 | """The same numbers, painted through spaces that say what they mean.
The Python twin of the `write_calibrated_color` example in Rust. A calibrated
space says what white the numbers are measured against, what exponent they are
raised to and — for colour — what the three primaries actually reach, so the same
numbers are the same colour wherever the file is opened.
A second page paints the same row and the same ramp as plain device numbers, naming no
space, and says on the page itself which calibrated space plain RGB and plain grey mean
there: a reader goes by the page's default spaces. That page is also composited as an
isolated group blended in the ordinary space.
What the page reads is held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn. The numbers the bands are painted from are not language: they are
the same colours whoever reads the page.
Usage: python examples/write_calibrated_color.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_calibrated_color.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# The left edge of everything, and how wide a row runs.
LEFT = 70.0
RUN = 455.0
# The white every calibrated space on the page is measured against, as CIE XYZ.
WHITE = (0.9505, 1.0, 1.089)
# The six colours the first three rows paint, each as three numbers.
COLORS = [
[0.80, 0.10, 0.10],
[0.90, 0.50, 0.10],
[0.90, 0.85, 0.20],
[0.15, 0.55, 0.30],
[0.15, 0.35, 0.70],
[0.45, 0.20, 0.55],
]
# The size of one colour swatch, and the gap to the next.
SWATCH = (70.0, 55.0)
SWATCH_GAP = 7.0
# How many steps the grey ramp is cut into, and how tall it stands.
STEPS = 10
RAMP_HEIGHT = 45.0
# The darkest black the wider colour space and the bent grey reach, as CIE XYZ: a
# paper's black that reflects a little light rather than none.
BLACK = (0.0080, 0.0083, 0.0069)
@dataclass(frozen=True)
class Words:
"""Every word the page draws, in one language.
The numbers the bands are painted from are not here: three numbers are the same
three numbers in every language.
"""
# The line at the head of the page.
title: str
# The two lines under it, saying that nothing below was painted twice.
intro: tuple[str, str]
# The heading of each panel, and the line under it.
panels: tuple[tuple[str, str], tuple[str, str]]
# The caption each band stands under, in the order the bands are painted.
captions: tuple[str, str, str, str, str, str]
# The three lines at the foot of the page.
closing: tuple[str, str, str]
# The line at the head of the second page.
defaults_title: str
# The two lines under it, saying what the page does.
defaults_intro: tuple[str, str]
# What stands over the row and over the ramp of the second page.
defaults_captions: tuple[str, str]
# What the second page says of the group it is composited as.
group_note: str
# The page in English.
ENGLISH = Words(
title="The same numbers, through spaces that say what they mean",
intro=(
"Nothing below was painted twice with different numbers. Each band "
"holds the very same numbers as",
"the one above it, and what changes is the space they are said in.",
),
panels=(
(
"Six colours, three ways of meaning them",
"The three numbers are the same in every band. The primaries under them "
"are not.",
),
(
"One grey ramp, three exponents",
"Ten steps from 0.05 to 0.95, painted with the same ten numbers each time.",
),
),
captions=(
"Left to the device",
"Through one set of primaries",
"Through a wider set of primaries, over a measured black",
"Left to the device",
"Measured, raised to 1",
"Measured, raised to 2.2, over a measured black",
),
closing=(
"A calibrated space carries its measurement in a handful of numbers "
"rather than in a profile,",
"so a file states what its colours are without embedding anything "
"and without asking the",
"reader to have the right profile installed.",
),
defaults_title="The same device numbers, read the way the page says",
defaults_intro=(
"Nothing below names a space: every colour is a plain rg or g. The page itself",
"says which calibrated space plain numbers mean, and a reader goes by it.",
),
defaults_captions=(
"rg as written; the page's default RGB is the wider calibrated space",
"g as written; the page's default grey is the grey raised to 2.2",
),
group_note="The page is composited as a group blended in the ordinary space, on its own.",
)
# The page in French.
FRENCH = Words(
title="Les mêmes nombres, dans des espaces qui disent ce qu’ils signifient",
intro=(
("Rien ci-dessous n’a été peint deux fois avec des nombres différents. Chaque "
"bande reprend les mêmes"),
("nombres que celle du dessus ; ce qui change, c’est l’espace dans lequel on "
"les exprime."),
),
panels=(
(
"Six couleurs, trois façons de les définir",
("Les trois nombres sont les mêmes dans chaque bande. Les primaires "
"sous-jacentes, non."),
),
(
"Un dégradé de gris, trois exposants",
("Dix paliers de 0.05 à 0.95, peints chaque fois avec les dix mêmes "
"nombres."),
),
),
captions=(
"Laissé à l’appareil",
"Rapporté à un jeu de primaires",
"Rapporté à des primaires plus larges, sur un noir mesuré",
"Laissé à l’appareil",
"Mesuré, exposant 1",
"Mesuré, exposant 2,2, sur un noir mesuré",
),
closing=(
("Un espace calibré exprime sa mesure en une poignée de nombres plutôt que par"
" un profil,"),
("si bien qu’un fichier dit ce que sont ses couleurs sans rien incorporer et "
"sans exiger"),
"que le logiciel de lecture ait le bon profil installé.",
),
defaults_title="Les mêmes nombres, lus comme l’indique la page",
defaults_intro=(
(
"Rien ci-dessous ne nomme d’espace : chaque couleur est un simple rg ou g. "
"La page dit"
),
(
"elle-même quel espace calibré ces nombres désignent ; le logiciel de "
"lecture s’y tient."
),
),
defaults_captions=(
(
"rg tel qu’écrit ; le RVB par défaut de la page est l’espace calibré plus "
"large"
),
(
"g tel qu’écrit ; le gris par défaut de la page est le gris élevé à la "
"puissance 2,2"
),
),
group_note="La page est composée comme un groupe isolé, fusionné dans l’espace ordinaire.",
)
# The page in Dutch.
DUTCH = Words(
title="Dezelfde getallen, in ruimten die zeggen wat ze betekenen",
intro=(
"Niets hieronder is twee keer met andere getallen ingekleurd. Elke band bevat "
"dezelfde getallen",
"als die erboven; alleen de ruimte waarin ze worden uitgedrukt, verandert.",
),
panels=(
(
"Zes kleuren, drie manieren om ze op te vatten",
"De drie getallen zijn in elke band gelijk. De primaire kleuren eronder "
"niet.",
),
(
"Eén grijsverloop, drie exponenten",
"Tien stappen van 0,05 tot 0,95, telkens met dezelfde tien getallen geschilderd.",
),
),
captions=(
"Aan het apparaat overgelaten",
"Via één set primaire kleuren",
"Via ruimere primaire kleuren, boven een gemeten zwart",
"Aan het apparaat overgelaten",
"Gemeten, tot de macht 1",
"Gemeten, tot de macht 2,2, boven een gemeten zwart",
),
closing=(
"Een gekalibreerde ruimte legt haar meting vast in een handvol getallen in "
"plaats van in een profiel,",
"dus zegt een bestand wat zijn kleuren zijn zonder iets in te sluiten en "
"zonder van de",
"lezer te vragen dat het juiste profiel geïnstalleerd is.",
),
defaults_title="Dezelfde apparaatgetallen, gelezen zoals de pagina zegt",
defaults_intro=(
"Niets hieronder noemt een ruimte: elke kleur is een gewone rg of g. De pagina zelf",
"zegt welke gekalibreerde ruimte gewone getallen betekenen, en een lezer volgt haar.",
),
defaults_captions=(
"rg zoals geschreven; de standaard-RGB van de pagina is de ruimere gekalibreerde ruimte",
"g zoals geschreven; het standaardgrijs van de pagina is het grijs tot de macht 2,2",
),
group_note="De pagina wordt samengesteld als een geïsoleerde groep, gemengd in de gewone ruimte.",
)
# The page in Portuguese.
PORTUGUESE = Words(
title="Os mesmos números, em espaços que dizem o que significam",
intro=(
"Nada abaixo foi pintado duas vezes com números diferentes. Cada faixa tem os "
"mesmos números que",
"a de cima, e o que muda é o espaço em que são ditos.",
),
panels=(
(
"Seis cores, três formas de as entender",
"Os três números são iguais em cada faixa. Os primários por baixo não.",
),
(
"Uma rampa de cinzentos, três expoentes",
"Dez passos de 0,05 a 0,95, pintados de cada vez com os mesmos dez números.",
),
),
captions=(
"Entregue ao dispositivo",
"Através de um conjunto de primários",
"Através de primários mais amplos, sobre um preto medido",
"Entregue ao dispositivo",
"Medido, elevado a 1",
"Medido, elevado a 2,2, sobre um preto medido",
),
closing=(
"Um espaço calibrado leva a sua medida em meia dúzia de números em vez de um "
"perfil,",
"por isso um ficheiro diz quais são as suas cores sem incorporar nada e sem "
"pedir ao",
"leitor que tenha instalado o perfil certo.",
),
defaults_title="Os mesmos números de dispositivo, lidos como diz a página",
defaults_intro=(
"Nada abaixo nomeia um espaço: cada cor é um simples rg ou g. A própria página",
"diz que espaço calibrado significam os números simples, e o leitor segue-a.",
),
defaults_captions=(
"rg tal como escrito; o RGB por omissão da página é o espaço calibrado mais amplo",
"g tal como escrito; o cinzento por omissão da página é o cinzento elevado a 2,2",
),
group_note="A página é composta como um grupo misturado no espaço corrente, por si só.",
)
# The page in Italian.
ITALIAN = Words(
title="Gli stessi numeri, in spazi che dicono cosa significano",
intro=(
"Niente qui sotto è stato dipinto due volte con numeri diversi. Ogni fascia "
"porta gli stessi numeri di",
"quella sopra, e ciò che cambia è lo spazio in cui sono espressi.",
),
panels=(
(
"Sei colori, tre modi di intenderli",
"I tre numeri sono uguali in ogni fascia. I primari sottostanti no.",
),
(
"Una scala di grigi, tre esponenti",
"Dieci passi da 0,05 a 0,95, dipinti ogni volta con gli stessi dieci numeri.",
),
),
captions=(
"Lasciato al dispositivo",
"Attraverso un insieme di primari",
"Attraverso primari più ampi, su un nero misurato",
"Lasciato al dispositivo",
"Misurato, elevato a 1",
"Misurato, elevato a 2,2, su un nero misurato",
),
closing=(
"Uno spazio calibrato porta la sua misura in pochi numeri anziché in un "
"profilo,",
"così un file dice quali sono i suoi colori senza incorporare nulla e senza "
"chiedere al",
"programma di lettura di avere installato il profilo giusto.",
),
defaults_title="Gli stessi numeri di dispositivo, letti come dice la pagina",
defaults_intro=(
"Niente qui sotto nomina uno spazio: ogni colore è un semplice rg o g. La pagina stessa",
"dice in quale spazio calibrato si leggono i numeri semplici, e il programma di lettura la segue.",
),
defaults_captions=(
"rg così com’è; l’RGB predefinito della pagina è lo spazio calibrato più ampio",
"g così com’è; il grigio predefinito della pagina è il grigio elevato a 2,2",
),
group_note="La pagina è composta come un gruppo fuso nello spazio ordinario, da sola.",
)
# The page in Spanish.
SPANISH = Words(
title="Los mismos números, en espacios que dicen lo que significan",
intro=(
"Nada de abajo se pintó dos veces con números distintos. Cada banda lleva los "
"mismos números que",
"la de encima, y lo que cambia es el espacio en que se expresan.",
),
panels=(
(
"Seis colores, tres formas de entenderlos",
"Los tres números son iguales en cada banda. Los primarios de debajo, no.",
),
(
"Una rampa de grises, tres exponentes",
"Diez pasos de 0,05 a 0,95, pintados cada vez con los mismos diez números.",
),
),
captions=(
"Según el dispositivo",
"Con un juego de primarios",
"Con un juego de primarios más amplio, sobre un negro medido",
"Según el dispositivo",
"Medido, elevado a 1",
"Medido, elevado a 2,2, sobre un negro medido",
),
closing=(
"Un espacio calibrado lleva su medida en unos pocos números en lugar de un "
"perfil,",
"así que un archivo dice cuáles son sus colores sin incrustar nada y sin "
"pedir al",
"lector que tenga instalado el perfil adecuado.",
),
defaults_title="Los mismos números de dispositivo, leídos como dice la página",
defaults_intro=(
"Nada de abajo nombra un espacio: cada color es un simple rg o g. La propia página",
"dice qué espacio calibrado significan los números simples, y el lector la sigue.",
),
defaults_captions=(
"rg tal cual; el RGB por defecto de la página es el espacio calibrado más amplio",
"g tal cual; el gris por defecto de la página es el gris elevado a 2,2",
),
group_note="La página se compone como un grupo mezclado en el espacio ordinario, por sí sola.",
)
# The page in German.
GERMAN = Words(
title="Dieselben Zahlen in Farbräumen, die sagen, was sie bedeuten",
intro=(
"Nichts unten wurde zweimal mit verschiedenen Zahlen gemalt. Jedes Band "
"enthält genau dieselben",
"Zahlen wie das darüber; was sich ändert, ist der Farbraum, in dem sie gelten.",
),
panels=(
(
"Sechs Farben, drei Lesarten",
"Die drei Zahlen sind in jedem Band dieselben. Die Primärfarben dahinter "
"nicht.",
),
(
"Ein Graukeil, drei Exponenten",
"Zehn Stufen von 0,05 bis 0,95, jedes Mal mit denselben zehn Zahlen gemalt.",
),
),
captions=(
"Dem Gerät überlassen",
"Über einen Satz Primärfarben",
"Über einen weiteren Satz Primärfarben, über einem gemessenen Schwarz",
"Dem Gerät überlassen",
"Gemessen, hoch 1",
"Gemessen, hoch 2,2, über einem gemessenen Schwarz",
),
closing=(
"Ein kalibrierter Farbraum trägt seine Messung in einer Handvoll Zahlen statt "
"in einem Profil,",
"also sagt eine Datei, was ihre Farben sind, ohne etwas einzubetten und ohne "
"vom Leser zu",
"verlangen, dass das richtige Profil installiert ist.",
),
defaults_title="Dieselben Gerätezahlen, so gelesen, wie die Seite es sagt",
defaults_intro=(
"Nichts unten nennt einen Farbraum: Jede Farbe ist ein schlichtes rg oder g. Die Seite selbst",
"sagt, welchen kalibrierten Farbraum schlichte Zahlen meinen, und ein Leser richtet sich danach.",
),
defaults_captions=(
"rg wie geschrieben; das Standard-RGB der Seite ist der weitere kalibrierte Farbraum",
"g wie geschrieben; das Standardgrau der Seite ist das Grau hoch 2,2",
),
group_note="Die Seite wird als Gruppe zusammengesetzt, für sich im gewöhnlichen Farbraum gemischt.",
)
# 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 caption(content, font, y, line):
"""Write the small caption a band stands under."""
content.save_state()
content.set_fill(hqf_pdf.Color.gray(0.45))
content.draw_text(font, 8.0, LEFT, y, line)
content.restore_state()
def panel_heading(content, font, y, title, under):
"""Draw one panel's heading, with the line under it."""
content.save_state()
content.set_fill(hqf_pdf.Color.gray(0.2))
content.draw_text(font, 11.0, LEFT, y, title)
content.set_fill(hqf_pdf.Color.gray(0.45))
content.draw_text(font, 8.0, LEFT, y - 15.0, under)
content.restore_state()
def band(content, space, bottom):
"""Paint the six colours across, in `space`; without one, left to the device."""
x = LEFT
for color in COLORS:
content.save_state()
if space is None:
content.set_fill(hqf_pdf.Rgb(color[0], color[1], color[2]))
else:
content.set_fill_space(space)
content.set_fill_components(color)
content.rect(x, bottom, SWATCH[0], SWATCH[1])
content.fill()
content.restore_state()
x += SWATCH[0] + SWATCH_GAP
def ramp(content, space, bottom):
"""Paint the grey ramp across, in `space`; without one, left to the device."""
width = RUN / STEPS
x = LEFT
grey = 0.05
for _ in range(STEPS):
content.save_state()
if space is None:
content.set_fill(hqf_pdf.Color.gray(grey))
else:
content.set_fill_space(space)
content.set_fill_components([grey])
content.rect(x, bottom, width, RAMP_HEIGHT)
content.fill()
content.restore_state()
x += width
grey += 0.1
def heading(content, font, words):
"""Draw the title and the two lines saying what the page is showing."""
content.draw_text(font, 15.0, LEFT, 780.0, words.title)
content.save_state()
content.set_fill(hqf_pdf.Color.gray(0.35))
content.draw_text(font, 10.0, LEFT, 762.0, words.intro[0])
content.draw_text(font, 10.0, LEFT, 748.0, words.intro[1])
content.restore_state()
def closing(content, font, words):
"""Draw the closing note."""
content.save_state()
content.set_fill(hqf_pdf.Color.gray(0.35))
for y, line in zip([140.0, 126.0, 112.0], words.closing):
content.draw_text(font, 9.0, LEFT, y, line)
content.restore_state()
def defaults_page(font, words, rgb, gray, blended) -> hqf_pdf.Page:
"""The second page: the row and the ramp in plain device numbers, the page reading
plain RGB through `rgb` and plain grey through `gray`, and composited as an isolated
group blended in `blended`."""
content = hqf_pdf.Content()
content.draw_text(font, 15.0, LEFT, 780.0, words.defaults_title)
content.save_state()
content.set_fill(hqf_pdf.Color.gray(0.35))
content.draw_text(font, 10.0, LEFT, 762.0, words.defaults_intro[0])
content.draw_text(font, 10.0, LEFT, 748.0, words.defaults_intro[1])
content.restore_state()
caption(content, font, 706.0, words.defaults_captions[0])
band(content, None, 648.0)
caption(content, font, 632.0, words.defaults_captions[1])
ramp(content, None, 584.0)
content.save_state()
content.set_fill(hqf_pdf.Color.gray(0.35))
content.draw_text(font, 9.0, LEFT, 550.0, words.group_note)
content.restore_state()
page = hqf_pdf.Page.a4()
page.set_content(content)
page.set_default_rgb(rgb)
page.set_default_gray(gray)
page.set_group(hqf_pdf.PageGroup(blended, isolated=True))
return page
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("calibrated.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
ordinary = document.add_color_space(
hqf_pdf.CalRgb(WHITE)
.gamma((2.2, 2.2, 2.2))
.primaries(
(0.4124, 0.2126, 0.0193),
(0.3576, 0.7152, 0.1192),
(0.1805, 0.0722, 0.9505),
)
)
wider = document.add_color_space(
hqf_pdf.CalRgb(WHITE)
.gamma((2.2, 2.2, 2.2))
.primaries(
(0.5767, 0.2974, 0.0270),
(0.1856, 0.6273, 0.0707),
(0.1882, 0.0753, 0.9911),
)
.black_point(BLACK)
)
straight = document.add_color_space(hqf_pdf.CalGray(WHITE).gamma(1.0))
bent = document.add_color_space(
hqf_pdf.CalGray(WHITE).gamma(2.2).black_point(BLACK)
)
content = hqf_pdf.Content()
heading(content, font, words)
panel_heading(content, font, 706.0, words.panels[0][0], words.panels[0][1])
caption(content, font, 668.0, words.captions[0])
band(content, None, 610.0)
caption(content, font, 594.0, words.captions[1])
band(content, ordinary, 536.0)
caption(content, font, 520.0, words.captions[2])
band(content, wider, 462.0)
panel_heading(content, font, 420.0, words.panels[1][0], words.panels[1][1])
caption(content, font, 382.0, words.captions[3])
ramp(content, None, 334.0)
caption(content, font, 318.0, words.captions[4])
ramp(content, straight, 270.0)
caption(content, font, 254.0, words.captions[5])
ramp(content, bent, 206.0)
closing(content, font, words)
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
document.add_page(defaults_page(font, words, wider, bent, ordinary))
written = document.write(out)
print(
f"wrote {out}: {written} bytes, {len(COLORS)} colours and {STEPS} greys "
f"painted three times each"
)
if __name__ == "__main__":
main()
|