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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087 | """Writes pictures made in memory and read from files, each drawn under a setting of its
own, with what the image says of itself under it.
The Python twin of the `write_image_settings` example in Rust: the same pages, through
the binding rather than through the library directly.
The first page builds its pictures from samples: red, green and blue; cyan, magenta,
yellow and black; four-bit places in a table of colours; and samples carrying their own
opacity. It then shows them through a colour key, a soft mask, a stencil mask and as a
stencil, decoded upside down, smoothed and not, read through a colour profile under a
rendering intent, stripped of their opacity, laid down in one and in two inks named for
the press, and held within a clipping path. The pictures that let the page through stand
over a grey band, so what they leave out shows.
The second page turns one picture every way a camera may have stored it, and reads
pictures from files through the constructor made for each format, saying what size they
come out at a given resolution and what resolution they state; the last of them lies on
a layer a reader can hide. Its last picture is read as measured colour, CIE 1976 L*a*b*
against the D50 white.
The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set the
pages are written in.
Usage: python examples/write_image_settings.py [out.pdf]
HQF_PDF_LANG=fr python examples/write_image_settings.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# Where the committed fonts and pictures are.
TESTS = _out.ROOT / "crates" / "hqf-pdf" / "tests"
# How far in from the left edge of the sheet the grid starts, in points.
LEFT = 56.0
# How far apart two cells of the grid are across, in points.
ACROSS = 124.0
# How far apart two rows of the grid are down, in points.
DOWN = 170.0
# How wide and tall a picture is drawn, in points.
SIDE = 90.0
# Where the top of the first row of pictures sits, in points up from the foot of the
# sheet.
FIRST_ROW = 740.0
# The size the captions are set at, in points.
CAPTION = 7.5
# How many pixels across and down the pictures made in memory are.
TILE = 32
@dataclass(frozen=True)
class Words:
"""Every word the pages say, in one language."""
# The first page's heading, and what the file says of itself.
title: str
# The second page's heading.
files: str
# What each picture of the first page is, in the order it is drawn.
made: tuple[str, ...]
# Yes, then no.
yes_no: tuple[str, str]
# A picture's size and components; `{width}`, `{height}` and `{count}` stand for
# them.
size: str
# The width of a component; `{bits}` stands for it.
bits: str
# Whether a picture carries a soft mask; `{answer}` stands for it.
soft: str
# The ranges a colour key leaves out; `{ranges}` stands for them.
keyed: str
# Whether a picture carries a stencil mask; `{answer}` stands for it.
stencil_mask: str
# Whether a picture is a stencil; `{answer}` stands for it.
stencil: str
# The ranges a picture is decoded through; `{ranges}` stands for them.
decoded: str
# Whether a picture is smoothed; `{answer}` stands for it.
smoothed: str
# A picture's profile and intent; `{bytes}` and `{intent}` stand for how long the
# profile is and the intent.
profile: str
# The four rendering intents: perceptual, relative colorimetric, saturation,
# absolute colorimetric.
intents: tuple[str, str, str, str]
# How many components a pixel carries; `{count}` stands for them.
components: str
# A clipping path; `{contours}` and `{knots}` stand for how many.
path: str
# What each orientation is, in the order of the tags one to eight.
orientations: tuple[str, ...]
# An orientation's tag and whether it swaps the axes; `{tag}` and `{swap}` stand for
# them.
tag: str
# Whether the axes are swapped: yes, then no.
swaps: tuple[str, str]
# The start of an orientation's matrix; `{matrix}` stands for it.
matrix: str
# What each file picture is, in the order it is drawn.
read: tuple[str, str, str, str]
# A picture's size at 300 dots to the inch; `{width}` and `{height}` stand for it.
at_dpi: str
# The resolution a picture states; `{x}`, `{y}` and `{square}` stand for it.
stated: str
# Whether it is the same both ways: yes, then no.
square: tuple[str, str]
# What a picture stating no resolution is said to state.
unstated: str
# How many extra channels a TIFF names; `{count}` stands for them.
channels: str
# The name of the layer the last picture lies on.
layer: str
# Where the last picture lies; `{layer}` stands for the layer.
on_layer: str
# What stands under the letter drawn inline.
inline: str
# What stands under the picture read as measured colour.
measured: str
# The pages in English.
ENGLISH = Words(
title="Pictures made in memory, and what each is told",
files="One picture turned eight ways, and pictures read from files",
made=(
"From red, green and blue",
"From four process inks",
"From a table of colours",
"From samples with opacity",
"Through a colour key",
"Through a soft mask",
"Through a stencil mask",
"A stencil in the page's colour",
"Decoded upside down",
"Smoothed when enlarged",
"Left as its pixels",
"A profile and an intent",
"Its opacity dropped",
"In one press ink",
"In two press inks",
"Held within a clipping path",
),
yes_no=(
"yes",
"no",
),
size="{width} × {height} px, {count} components",
bits="{bits} bits a component",
soft="soft mask: {answer}",
keyed="keyed out: {ranges}",
stencil_mask="stencil mask: {answer}",
stencil="stencil: {answer}",
decoded="decoded: {ranges}",
smoothed="smoothed: {answer}",
profile="profile {bytes} bytes, {intent}",
intents=(
"perceptual",
"relative colorimetric",
"saturation",
"absolute colorimetric",
),
components="components a pixel: {count}",
path="contours: {contours}; knots: {knots}",
orientations=(
"Upright",
"Mirrored left to right",
"Upside down",
"Mirrored top to bottom",
"Mirrored, turned left",
"Turned right",
"Mirrored, turned right",
"Turned left",
),
tag="tag {tag}; {swap}",
swaps=(
"axes swapped",
"axes kept",
),
matrix="matrix [{matrix}]",
read=(
"A PNG, read as a PNG",
"A JPEG, read as a JPEG",
"A BMP, read as a BMP",
"A TIFF, read as a TIFF",
),
at_dpi="at 300 dpi: {width} × {height} pt",
stated="{x} × {y} dpi, {square}",
square=(
"square",
"not square",
),
unstated="states no resolution",
channels="extra channels named: {count}",
layer="Photographs",
on_layer="on the layer “{layer}”",
inline="the letter, written into the page's own stream",
measured="Read as measured colour, L*a*b*",
)
# The pages in French.
FRENCH = Words(
title="Des images créées en mémoire, et ce qu’on dit à chacune",
files="Une image en huit sens, et des images de fichiers",
made=(
"En rouge, vert et bleu",
"En quadrichromie",
"D’après une table de couleurs",
"Avec sa propre opacité",
"Par une clé de couleur",
"Par un masque progressif",
"Par un masque au pochoir",
"En pochoir, couleur de la page",
"Décodée à l’envers",
"Lissée quand on l’agrandit",
"Laissée en pixels",
"Un profil et une intention",
"Son opacité retirée",
"En une encre d’imprimerie",
"En deux encres d’imprimerie",
"Dans un tracé de détourage",
),
yes_no=(
"oui",
"non",
),
size="{width} × {height} px, {count} composantes",
bits="{bits} bits par composante",
soft="masque progressif : {answer}",
keyed="exclues : {ranges}",
stencil_mask="masque au pochoir : {answer}",
stencil="pochoir : {answer}",
decoded="décodage : {ranges}",
smoothed="lissée : {answer}",
profile="profil {bytes} octets, {intent}",
intents=(
"perceptuelle",
"colorimétrique relative",
"saturation",
"colorimétrique absolue",
),
components="composantes par pixel : {count}",
path="contours : {contours} ; nœuds : {knots}",
orientations=(
"À l’endroit",
"En miroir de gauche à droite",
"À l’envers",
"En miroir de haut en bas",
"En miroir, tournée à gauche",
"Tournée à droite",
"En miroir, tournée à droite",
"Tournée à gauche",
),
tag="étiquette {tag} ; {swap}",
swaps=(
"axes échangés",
"axes gardés",
),
matrix="matrice [{matrix}]",
read=(
"Un PNG, lu comme un PNG",
"Un JPEG, lu comme un JPEG",
"Un BMP, lu comme un BMP",
"Un TIFF, lu comme un TIFF",
),
at_dpi="à 300 ppp : {width} × {height} pt",
stated="{x} × {y} ppp, {square}",
square=(
"carrée",
"non carrée",
),
unstated="n’indique aucune résolution",
channels="autres canaux nommés : {count}",
layer="Photographies",
on_layer="sur le calque « {layer} »",
inline="la lettre, écrite dans le flux de la page même",
measured="Lue en couleur mesurée, L*a*b*",
)
# The pages in Dutch.
DUTCH = Words(
title="Afbeeldingen uit het geheugen, en hun instellingen",
files="Eén afbeelding in acht standen, en beelden uit bestanden",
made=(
"Uit rood, groen en blauw",
"Uit vier procesinkten",
"Uit een kleurentabel",
"Uit waarden met dekking",
"Via een kleursleutel",
"Via een zacht masker",
"Via een sjabloonmasker",
"Sjabloon in paginakleur",
"Ondersteboven gedecodeerd",
"Gladgemaakt bij vergroten",
"Als pixels gelaten",
"Een profiel en een intentie",
"Dekking verlaagd",
"In één persinkt",
"In twee persinkten",
"Binnen een uitknippad",
),
yes_no=(
"ja",
"nee",
),
size="{width} × {height} px, {count} componenten",
bits="{bits} bits per component",
soft="zacht masker: {answer}",
keyed="sleutel: {ranges}",
stencil_mask="sjabloonmasker: {answer}",
stencil="sjabloon: {answer}",
decoded="gedecodeerd: {ranges}",
smoothed="gladgemaakt: {answer}",
profile="profiel {bytes} bytes, {intent}",
intents=(
"perceptueel",
"relatief colorimetrisch",
"verzadiging",
"absoluut colorimetrisch",
),
components="componenten per pixel: {count}",
path="contouren: {contours}; knopen: {knots}",
orientations=(
"Rechtop",
"Links-rechts gespiegeld",
"Ondersteboven",
"Boven-onder gespiegeld",
"Gespiegeld, linksom gedraaid",
"Rechtsom gedraaid",
"Gespiegeld, rechtsom gedraaid",
"Linksom gedraaid",
),
tag="tag {tag}; {swap}",
swaps=(
"assen verwisseld",
"assen behouden",
),
matrix="matrix [{matrix}]",
read=(
"Een PNG, gelezen als PNG",
"Een JPEG, gelezen als JPEG",
"Een BMP, gelezen als BMP",
"Een TIFF, gelezen als TIFF",
),
at_dpi="op 300 dpi: {width} × {height} pt",
stated="{x} × {y} dpi, {square}",
square=(
"vierkant",
"niet vierkant",
),
unstated="vermeldt geen resolutie",
channels="extra kanalen met een naam: {count}",
layer="Foto’s",
on_layer="op de laag „{layer}”",
inline="de letter, geschreven in de eigen stroom van de pagina",
measured="Gelezen als gemeten L*a*b*-kleur",
)
# The pages in Portuguese.
PORTUGUESE = Words(
title="Imagens feitas em memória, e o que se diz a cada uma",
files="Uma imagem em oito orientações e imagens de ficheiros",
made=(
"De vermelho, verde e azul",
"De quadricromia",
"De uma tabela de cores",
"De amostras com opacidade",
"Com uma chave de cor",
"Com uma máscara suave",
"Com uma máscara de estêncil",
"Um estêncil na cor da página",
"Descodificada invertida",
"Suavizada ao ampliar",
"Deixada nos seus píxeis",
"Um perfil e uma intenção",
"Opacidade reduzida",
"Numa tinta de gráfica",
"Em duas tintas de gráfica",
"Num traçado de recorte",
),
yes_no=(
"sim",
"não",
),
size="{width} × {height} px, {count} componentes",
bits="{bits} bits por componente",
soft="máscara suave: {answer}",
keyed="exclui {ranges}",
stencil_mask="máscara de estêncil: {answer}",
stencil="estêncil: {answer}",
decoded="descodificada: {ranges}",
smoothed="suavizada: {answer}",
profile="perfil {bytes} bytes, {intent}",
intents=(
"percetual",
"colorimétrica relativa",
"saturação",
"colorimétrica absoluta",
),
components="componentes por píxel: {count}",
path="contornos: {contours}; nós: {knots}",
orientations=(
"Na posição normal",
"Espelhada na horizontal",
"De pernas para o ar",
"Espelhada na vertical",
"Espelhada, rodada à esquerda",
"Rodada à direita",
"Espelhada, rodada à direita",
"Rodada à esquerda",
),
tag="etiqueta {tag}; {swap}",
swaps=(
"eixos trocados",
"eixos mantidos",
),
matrix="matriz [{matrix}]",
read=(
"Um PNG, lido como PNG",
"Um JPEG, lido como JPEG",
"Um BMP, lido como BMP",
"Um TIFF, lido como TIFF",
),
at_dpi="a 300 ppp: {width} × {height} pt",
stated="{x} × {y} ppp, {square}",
square=(
"quadrado",
"não quadrado",
),
unstated="não indica resolução",
channels="canais extra com nome: {count}",
layer="Fotografias",
on_layer="na camada «{layer}»",
inline="a letra, escrita no próprio fluxo da página",
measured="Lida como cor medida em L*a*b*",
)
# The pages in Italian.
ITALIAN = Words(
title="Immagini create in memoria, e ciò che si dice a ciascuna",
files="Un’immagine ruotata in otto modi, e immagini lette da file",
made=(
"Da rosso, verde e blu",
"In quadricromia",
"Da una tabella di colori",
"Da campioni con opacità",
"Con una chiave di colore",
"Con una maschera morbida",
"Con una maschera a stencil",
"Stencil nel colore di pagina",
"Decodificata capovolta",
"Smussata quando ingrandita",
"Non smussata",
"Profilo e intento di rendering",
"Opacità ridotta",
"In un inchiostro da stampa",
"In due inchiostri da stampa",
"In un tracciato di ritaglio",
),
yes_no=(
"sì",
"no",
),
size="{width} × {height} px, {count} componenti",
bits="{bits} bit per componente",
soft="maschera morbida: {answer}",
keyed="esclude {ranges}",
stencil_mask="maschera a stencil: {answer}",
stencil="stencil: {answer}",
decoded="decodificata: {ranges}",
smoothed="smussata: {answer}",
profile="profilo: {bytes} byte, {intent}",
intents=(
"percettivo",
"colorimetrico relativo",
"saturazione",
"colorimetrico assoluto",
),
components="componenti per pixel: {count}",
path="contorni: {contours}; nodi: {knots}",
orientations=(
"Diritta",
"Specchiata in orizzontale",
"Capovolta",
"Specchiata in verticale",
"Specchiata, ruotata a sinistra",
"Ruotata a destra",
"Specchiata, ruotata a destra",
"Ruotata a sinistra",
),
tag="tag {tag}; {swap}",
swaps=(
"assi scambiati",
"assi mantenuti",
),
matrix="matrice [{matrix}]",
read=(
"Un PNG, letto come PNG",
"Un JPEG, letto come JPEG",
"Un BMP, letto come BMP",
"Un TIFF, letto come TIFF",
),
at_dpi="a 300 dpi: {width} × {height} pt",
stated="{x} × {y} dpi, {square}",
square=(
"quadrati",
"non quadrati",
),
unstated="non indica risoluzione",
channels="canali extra con nome: {count}",
layer="Fotografie",
on_layer="sul livello «{layer}»",
inline="la lettera, scritta nel flusso proprio della pagina",
measured="Letta come colore CIE L*a*b*",
)
# The pages in Spanish.
SPANISH = Words(
title="Imágenes en memoria y lo que se indica a cada una",
files="Una imagen en ocho orientaciones, e imágenes de archivos",
made=(
"De rojo, verde y azul",
"De cuatricromía",
"De una tabla de colores",
"De muestras con opacidad",
"Con una clave de color",
"Con una máscara suave",
"Con una máscara de estarcido",
"Estarcido en color de página",
"Decodificada cabeza abajo",
"Suavizada al ampliarse",
"Dejada en sus píxeles",
"Un perfil y una intención",
"Su opacidad rebajada",
"En una tinta de imprenta",
"En dos tintas de imprenta",
"En un trazado de recorte",
),
yes_no=(
"sí",
"no",
),
size="{width} × {height} px, {count} componentes",
bits="{bits} bits por componente",
soft="máscara suave: {answer}",
keyed="excluye {ranges}",
stencil_mask="máscara de estarcido: {answer}",
stencil="estarcido: {answer}",
decoded="decodificada: {ranges}",
smoothed="suavizada: {answer}",
profile="perfil: {bytes} bytes, {intent}",
intents=(
"perceptual",
"colorimétrica relativa",
"saturación",
"colorimétrica absoluta",
),
components="componentes por píxel: {count}",
path="contornos: {contours}; nodos: {knots}",
orientations=(
"Sin girar",
"Volteada en horizontal",
"Cabeza abajo",
"Volteada en vertical",
"Reflejada, girada a la izquierda",
"Girada a la derecha",
"Reflejada, girada a la derecha",
"Girada a la izquierda",
),
tag="etiqueta {tag}; {swap}",
swaps=(
"ejes intercambiados",
"ejes conservados",
),
matrix="matriz [{matrix}]",
read=(
"Un PNG, leído como PNG",
"Un JPEG, leído como JPEG",
"Un BMP, leído como BMP",
"Un TIFF, leído como TIFF",
),
at_dpi="a 300 ppp: {width} × {height} pt",
stated="{x} × {y} ppp, {square}",
square=(
"cuadrado",
"no cuadrado",
),
unstated="no indica resolución",
channels="canales extra con nombre: {count}",
layer="Fotografías",
on_layer="en la capa «{layer}»",
inline="la letra, escrita en el propio flujo de la página",
measured="Leída como color medido, L*a*b*",
)
# The pages in German.
GERMAN = Words(
title="Bilder aus dem Speicher und was jedem mitgegeben wird",
files="Ein Bild, achtfach gedreht, und Bilder aus Dateien",
made=(
"Aus Rot, Grün und Blau",
"Aus vier Prozessfarben",
"Aus einer Farbtabelle",
"Aus Werten mit Deckkraft",
"Über einen Farbschlüssel",
"Über eine weiche Maske",
"Über eine Schablonenmaske",
"Schablone in Seitenfarbe",
"Invertiert dekodiert",
"Beim Vergrößern geglättet",
"Als Pixel belassen",
"Profil und Wiedergabeabsicht",
"Mit verringerter Deckkraft",
"In einer Druckfarbe",
"In zwei Druckfarben",
"In einem Schnittpfad",
),
yes_no=(
"ja",
"nein",
),
size="{width} × {height} px, {count} Komponenten",
bits="{bits} Bit je Komponente",
soft="weiche Maske: {answer}",
keyed="ausgespart: {ranges}",
stencil_mask="Schablonenmaske: {answer}",
stencil="Schablone: {answer}",
decoded="dekodiert: {ranges}",
smoothed="geglättet: {answer}",
profile="Profil {bytes} Bytes, {intent}",
intents=(
"perzeptiv",
"relativ farbmetrisch",
"Sättigung",
"absolut farbmetrisch",
),
components="Komponenten je Pixel: {count}",
path="Konturen: {contours}; Knoten: {knots}",
orientations=(
"Aufrecht",
"Links-rechts gespiegelt",
"Auf dem Kopf",
"Oben-unten gespiegelt",
"Gespiegelt, links gedreht",
"Nach rechts gedreht",
"Gespiegelt, rechts gedreht",
"Nach links gedreht",
),
tag="Wert {tag}; {swap}",
swaps=(
"Achsen vertauscht",
"Achsen beibehalten",
),
matrix="Matrix [{matrix}]",
read=(
"Ein PNG, als PNG gelesen",
"Ein JPEG, als JPEG gelesen",
"Ein BMP, als BMP gelesen",
"Ein TIFF, als TIFF gelesen",
),
at_dpi="bei 300 dpi: {width} × {height} pt",
stated="{x} × {y} dpi, {square}",
square=(
"quadratisch",
"rechteckig",
),
unstated="gibt keine Auflösung an",
channels="benannte Zusatzkanäle: {count}",
layer="Fotos",
on_layer="auf der Ebene „{layer}“",
inline="der Buchstabe, in den eigenen Datenstrom der Seite geschrieben",
measured="Als L*a*b*-Messwerte gelesen",
)
# 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}
# The four rendering intents, in the order `Words.intents` names them.
INTENTS = (
hqf_pdf.RenderingIntent.perceptual(),
hqf_pdf.RenderingIntent.relative_colorimetric(),
hqf_pdf.RenderingIntent.saturation(),
hqf_pdf.RenderingIntent.absolute_colorimetric(),
)
def number(value: float) -> str:
"""`value` written the shortest way that reads back as it, a whole number without
its point."""
return str(int(value)) if value == int(value) else repr(value)
def rgb_samples() -> bytes:
"""Red rising across the tile, green rising down it, a steady blue."""
return bytes(
value
for y in range(TILE)
for x in range(TILE)
for value in (min(x * 8, 255), min(y * 8, 255), 128)
)
def cmyk_samples() -> bytes:
"""Cyan rising across the tile, magenta rising down it, no yellow, no black."""
return bytes(
value
for y in range(TILE)
for x in range(TILE)
for value in (min(x * 8, 255), min(y * 8, 255), 0, 0)
)
def gray_ramp() -> bytes:
"""A grey rising across the tile."""
return bytes(min(x * 8, 255) for __ in range(TILE) for x in range(TILE))
def lab_samples() -> bytes:
"""A steady lightness, the green-to-red number rising across the tile and the
blue-to-yellow one rising down it, each byte read over the range of `lab_space`."""
return bytes(
value
for y in range(TILE)
for x in range(TILE)
for value in (180, min(x * 8, 255), min(y * 8, 255))
)
def lab_space() -> hqf_pdf.ImageSpace:
"""CIE 1976 L*a*b* against the D50 white, both colour numbers running from −128 to
127."""
return hqf_pdf.ImageSpace.lab(
hqf_pdf.Lab((0.9642, 1.0, 0.8249)).range((-128.0, 127.0, -128.0, 127.0))
)
def checker_bits() -> bytes:
"""Squares of eight pixels, one bit a pixel, alternately set and clear."""
return bytes(
0xFF if (column + y // 8) % 2 == 0 else 0x00
for y in range(TILE)
for column in range(TILE // 8)
)
def indexed() -> tuple[bytes, bytes]:
"""A table of sixteen colours, and the tile's pixels as four-bit places in it, two
to a byte."""
palette = bytes(
value
for entry in range(16)
for value in (entry * 16, 255 - entry * 16, entry * 8)
)
samples = bytes(
((x + y) % 16) << 4 | ((x + 1 + y) % 16)
for y in range(TILE)
for x in range(0, TILE, 2)
)
return palette, samples
def letter_f() -> bytes:
"""A letter F on white, eight pixels by twelve, which shows which way it was
turned."""
rows = ["########", "########"] + ["##......"] * 2 + ["######.."] * 2
rows += ["##......"] * 6
return bytes(
value
for row in rows
for mark in row
for value in ((20, 20, 20) if mark == "#" else (255, 255, 255))
)
def two_inks() -> hqf_pdf.DeviceN:
"""Two inks named for the press, and the program laying them down on the four
process plates: the first ink is all cyan, the second all yellow."""
body = [hqf_pdf.Op.integer(0), hqf_pdf.Op.exchange(), hqf_pdf.Op.integer(0)]
return hqf_pdf.DeviceN(
["Harbour Cyan", "Harbour Yellow"],
hqf_pdf.DeviceSpace.Cmyk,
hqf_pdf.Calculation([(0.0, 1.0)] * 2, [(0.0, 1.0)] * 4, body),
)
def yes_no(answer: bool, words: Words) -> str:
"""`answer` in `words`."""
return words.yes_no[0] if answer else words.yes_no[1]
def ranges(pairs) -> str:
"""`pairs` as the page writes them."""
return ", ".join(f"{number(low)}–{number(high)}" for low, high in pairs)
def diamond() -> hqf_pdf.ClippingPath:
"""A clipping path with one contour: a diamond whose sides bow outwards."""
knots = [
hqf_pdf.Knot((0.2, 0.95), (0.5, 1.0), (0.8, 0.95)),
hqf_pdf.Knot((0.95, 0.8), (1.0, 0.5), (0.95, 0.2)),
hqf_pdf.Knot((0.8, 0.05), (0.5, 0.0), (0.2, 0.05)),
hqf_pdf.Knot((0.05, 0.2), (0.0, 0.5), (0.05, 0.8)),
]
return hqf_pdf.ClippingPath([hqf_pdf.Contour(knots)])
def made(words: Words) -> list[tuple[hqf_pdf.Image, str]]:
"""The sixteen pictures of the first page, each with the one line it says of
itself."""
image = hqf_pdf.Image
rgb = image.from_rgb(TILE, TILE, rgb_samples())
cmyk = image.from_cmyk(TILE, TILE, cmyk_samples())
palette, places = indexed()
table = image.from_raw(TILE, TILE, 4, hqf_pdf.ImageSpace.indexed(palette), places)
rgba_samples = bytearray()
ramp = gray_ramp()
colours = rgb_samples()
for place, alpha in enumerate(ramp):
rgba_samples += colours[place * 3 : place * 3 + 3]
rgba_samples.append(alpha)
rgba = image.from_rgba(TILE, TILE, bytes(rgba_samples))
keyed = rgb.with_color_key([(0, 90), (0, 90), (0, 255)])
soft = rgb.with_soft_mask(image.from_gray(TILE, TILE, ramp))
checker = image.from_raw(TILE, TILE, 1, hqf_pdf.ImageSpace.gray(), checker_bits())
masked = rgb.with_stencil_mask(checker.as_stencil())
stencil = checker.as_stencil()
decoded = rgb.with_decode([(1.0, 0.0), (1.0, 0.0), (1.0, 0.0)])
small = image.from_rgb(4, 4, colours[:48])
profiled = rgb.with_icc_profile(hqf_pdf.srgb_icc_profile()).with_rendering_intent(
hqf_pdf.RenderingIntent.perceptual()
)
dropped = rgba.without_transparency()
ink = hqf_pdf.Separation.ink("Harbour Blue", hqf_pdf.Cmyk(0.9, 0.5, 0.0, 0.1))
one_ink = image.from_gray(TILE, TILE, ramp).in_named_inks(
hqf_pdf.ImageSpace.separation(ink)
)
paired = bytes(value for pair in zip(ramp, reversed(ramp)) for value in pair)
two = image.from_raw(
TILE, TILE, 8, hqf_pdf.ImageSpace.device_n(two_inks()), paired
)
clipped = rgb.with_clipping_path(diamond())
smoothed = small.with_interpolation(True)
def size(picture) -> str:
return (
words.size.replace("{width}", str(picture.width))
.replace("{height}", str(picture.height))
.replace("{count}", str(picture.color_space.components))
)
path = clipped.clipping_path
knots = sum(len(contour.knots) for contour in path.contours)
intent = profiled.rendering_intent
said = [
size(rgb),
size(cmyk),
words.bits.replace("{bits}", str(table.bits_per_component)),
words.soft.replace("{answer}", yes_no(rgba.soft_mask is not None, words)),
words.keyed.replace("{ranges}", ranges(keyed.color_key or [])),
words.soft.replace("{answer}", yes_no(soft.soft_mask is not None, words)),
words.stencil_mask.replace(
"{answer}", yes_no(masked.stencil_mask is not None, words)
),
words.stencil.replace("{answer}", yes_no(stencil.is_stencil, words)),
words.decoded.replace("{ranges}", ranges(decoded.decode or [])),
words.smoothed.replace("{answer}", yes_no(smoothed.is_interpolated, words)),
words.smoothed.replace("{answer}", yes_no(small.is_interpolated, words)),
words.profile.replace("{bytes}", str(len(profiled.icc_profile or b""))).replace(
"{intent}", "" if intent is None else words.intents[INTENTS.index(intent)]
),
words.soft.replace("{answer}", yes_no(dropped.soft_mask is not None, words)),
words.components.replace("{count}", str(one_ink.color_space.components)),
words.components.replace("{count}", str(two.color_space.components)),
words.path.replace("{contours}", str(len(path.contours))).replace(
"{knots}", str(knots)
),
]
pictures = [
rgb,
cmyk,
table,
rgba,
keyed,
soft,
masked,
stencil,
decoded,
smoothed,
small,
profiled,
dropped,
one_ink,
two,
clipped,
]
return list(zip(pictures, said))
def caption(content, font, at, line: str) -> None:
"""Set `line` at `at` in `font` at the captions' size."""
content.draw_text(font, CAPTION, at[0], at[1], line)
# How wide the line tracing a clipping path over its picture is, in points.
TRACE = 0.6
def cell(index: int) -> tuple[float, float]:
"""Where cell `index` of a grid four across starts: its left edge and the top of its
picture."""
return LEFT + ACROSS * (index % 4), FIRST_ROW - DOWN * (index // 4)
def first_page(doc, font, words: Words) -> hqf_pdf.Page:
"""The first page: the sixteen pictures made in memory, each over its title and the
line it says of itself."""
content = hqf_pdf.Content()
content.draw_text(font, 16.0, LEFT, 790.0, words.title)
for index, (picture, said) in enumerate(made(words)):
x, top = cell(index)
bottom = top - SIDE
# A band behind the pictures that leave the page showing through.
if 3 <= index <= 7 or index == 15:
content.set_fill(hqf_pdf.Rgb(0.75, 0.75, 0.75))
content.rect(x, bottom + SIDE / 3.0, SIDE, SIDE / 3.0)
content.fill()
content.set_fill(hqf_pdf.Rgb(0.85, 0.35, 0.1))
clipped = picture.clipping_path is not None
handle = doc.add_image(picture)
if clipped:
content.draw_image_clipped(handle, x, bottom, SIDE, SIDE)
# The path itself, traced over the picture it holds: its points are
# fractions of the picture, so it is traced into the same square.
path = handle.clipping_path
if path is not None:
content.save_state()
content.transform((SIDE, 0.0, 0.0, SIDE, x, bottom))
content.set_line_width(TRACE / SIDE)
content.set_stroke(hqf_pdf.Rgb(0.1, 0.1, 0.1))
content.trace_clipping_path(path)
content.stroke()
content.restore_state()
else:
content.draw_image(handle, x, bottom, SIDE, SIDE)
content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
caption(content, font, (x, bottom - 12.0), words.made[index])
caption(content, font, (x, bottom - 22.0), said)
page = hqf_pdf.Page.a4()
page.set_content(content)
return page
def second_page(doc, font, words: Words) -> hqf_pdf.Page:
"""The second page: the letter turned by each of the eight orientations, and four
pictures read from files, the last on a layer, then the letter written inline and a
picture read as measured colour."""
content = hqf_pdf.Content()
content.draw_text(font, 16.0, LEFT, 790.0, words.files)
letter = hqf_pdf.Image.from_rgb(8, 12, letter_f())
for tag in range(1, 9):
index = tag - 1
x, top = cell(index)
orientation = hqf_pdf.Orientation.from_tag(tag)
if orientation is None:
continue
turned = letter.with_orientation(orientation)
# The box is the picture as it is seen: turned a quarter, it is as wide as it
# was tall.
if orientation.swaps_axes:
width, height = SIDE, SIDE * 8.0 / 12.0
else:
width, height = SIDE * 8.0 / 12.0, SIDE
handle = doc.add_image(turned)
content.draw_image(handle, x, top - height, width, height)
swap = words.swaps[0 if orientation.swaps_axes else 1]
said = words.tag.replace("{tag}", str(orientation.tag)).replace("{swap}", swap)
matrix = " ".join(number(entry) for entry in orientation.matrix[:4])
caption(content, font, (x, top - SIDE - 12.0), words.orientations[index])
caption(content, font, (x, top - SIDE - 22.0), said)
caption(
content,
font,
(x, top - SIDE - 32.0),
words.matrix.replace("{matrix}", matrix),
)
x, top = cell(12)
content.draw_inline_image(letter, x, top - SIDE, SIDE * 8.0 / 12.0, SIDE)
caption(content, font, (x, top - SIDE - 12.0), words.inline)
measured = hqf_pdf.Image.from_rgb(TILE, TILE, lab_samples()).in_measured_color(
lab_space()
)
components = words.components.replace(
"{count}", str(measured.color_space.components)
)
x, top = cell(15)
handle = doc.add_image(measured)
content.draw_image(handle, x, top - SIDE, SIDE, SIDE)
caption(content, font, (x, top - SIDE - 12.0), words.measured)
caption(content, font, (x, top - SIDE - 22.0), components)
images = TESTS / "images"
layer = doc.add_layer(hqf_pdf.Layer(words.layer))
image = hqf_pdf.Image
pictures = [
image.from_png((images / "logo.png").read_bytes()),
image.from_jpeg((images / "jfif_300dpi.jpg").read_bytes()),
image.from_bmp((images / "truecolour.bmp").read_bytes()),
image.from_tiff((images / "photograph.tif").read_bytes()).layer(layer),
]
channels = len(image.tiff_channel_names((images / "pages.tif").read_bytes(), 0))
for place, picture in enumerate(pictures):
x, top = cell(8 + place)
wide, tall = picture.size_at_dpi(300.0)
at_dpi = words.at_dpi.replace("{width}", f"{wide:.0f}").replace(
"{height}", f"{tall:.0f}"
)
dpi = picture.resolution
if dpi is None:
stated = words.unstated
else:
same = hqf_pdf.Resolution.square(dpi.x) == dpi
stated = (
words.stated.replace("{x}", f"{dpi.x:.0f}")
.replace("{y}", f"{dpi.y:.0f}")
.replace("{square}", words.square[0 if same else 1])
)
last = words.channels.replace("{count}", str(channels)) if place == 3 else ""
handle = doc.add_image(picture)
width, height = handle.fit_within(SIDE, SIDE)
content.draw_image(handle, x, top - height, width, height)
caption(content, font, (x, top - SIDE - 12.0), words.read[place])
caption(content, font, (x, top - SIDE - 22.0), at_dpi)
caption(content, font, (x, top - SIDE - 32.0), stated)
if last:
caption(content, font, (x, top - SIDE - 42.0), last)
caption(
content,
font,
(x, top - SIDE - 52.0),
words.on_layer.replace("{layer}", words.layer),
)
page = hqf_pdf.Page.a4()
page.set_content(content)
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("image_settings.pdf", language)).stem
)
doc = hqf_pdf.Document()
doc.set_license(_licence.licensed())
doc.set_info("Title", words.title)
font = doc.add_font(hqf_pdf.Font.from_path(TESTS / "fonts" / "DejaVuSans.ttf"))
doc.add_page(first_page(doc, font, words))
doc.add_page(second_page(doc, font, words))
written = doc.write(out)
print(f"wrote {out} ({written} bytes)")
if __name__ == "__main__":
main()
|