cink 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cink-0.1.4/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /target/
2
+ node_modules/
3
+
4
+ # Generated release outputs
5
+ **/dist/
6
+ **/LICENSES/
7
+ !LICENSES/
8
+ *.tgz
9
+ __pycache__/
10
+ *.egg-info/
@@ -0,0 +1,204 @@
1
+ Copyright 2026 Julian Y. Richard Corbet
2
+
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
cink-0.1.4/PKG-INFO ADDED
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: cink
3
+ Version: 0.1.4
4
+ Summary: Handwritten signature image rendering for correspondence. Pixels, not signatures
5
+ Project-URL: Homepage, https://github.com/corbet-labs/cink#readme
6
+ Project-URL: Repository, https://github.com/corbet-labs/cink
7
+ Project-URL: Issues, https://github.com/corbet-labs/cink/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSES/Apache-2.0.txt
10
+ Keywords: correspondence,i18n,locale
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+
16
+ # cink
17
+
18
+ **Prepare handwritten signature images for correspondence.**
19
+
20
+ [![crates.io](https://img.shields.io/crates/v/cink.svg)](https://crates.io/crates/cink) [![npm](https://img.shields.io/npm/v/@corbet-labs/cink.svg)](https://www.npmjs.com/package/@corbet-labs/cink) [![Rust API](https://docs.rs/cink/badge.svg)](https://docs.rs/cink)
21
+
22
+ Recognize PNG, JPEG, and SVG input, inspect raster dimensions, calculate an aspect-preserving size, and generate a Typst image call. Runs without an image-decoding library.
23
+
24
+ ```js
25
+ import { imageSnippet } from '@corbet-labs/cink';
26
+
27
+ imageSnippet('/signature.png', 31.5);
28
+ // #image("/signature.png", height: 31.5pt)
29
+ ```
30
+
31
+ ## Install
32
+
33
+ | Environment | Command |
34
+ | --- | --- |
35
+ | Rust / Cargo | `cargo add cink` |
36
+ | Node.js / npm | `npm install @corbet-labs/cink` |
37
+ | pnpm | `pnpm add @corbet-labs/cink` |
38
+ | Yarn | `yarn add @corbet-labs/cink` |
39
+ | Bun | `bun add @corbet-labs/cink` |
40
+ | Deno | `deno add npm:@corbet-labs/cink` |
41
+
42
+ The 0.1.4 JavaScript distribution includes compiled ESM, CommonJS,
43
+ TypeScript declarations, and a standalone browser module. Node.js 20+ is
44
+ supported; no TypeScript loader is required.
45
+
46
+ ```js
47
+ // CommonJS
48
+ const { imageSnippet } = require('@corbet-labs/cink');
49
+ ```
50
+
51
+ ```html
52
+ <script type="module">
53
+ import { imageSnippet } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cink@0.1.4/dist/browser.js';
54
+ console.log(imageSnippet('/signature.png', 31.5));
55
+ </script>
56
+ ```
57
+
58
+ Python wheels, source distributions, and CLI instructions are in the
59
+ [installation guide](https://github.com/corbet-labs/cink/blob/main/docs/installation.md).
60
+ JSR publication and Typst availability are listed there explicitly.
61
+
62
+ ## Rust
63
+
64
+ ```rust
65
+ use cink::image_snippet;
66
+
67
+ assert_eq!(image_snippet("/signature.png", 31.5, None), "#image(\"/signature.png\", height: 31.5pt)");
68
+ ```
69
+
70
+ ## Python
71
+
72
+ ```python
73
+ from cink import image_snippet
74
+
75
+ assert image_snippet("/signature.png", 31.5) == '#image("/signature.png", height: 31.5pt)'
76
+ ```
77
+
78
+ ## API
79
+
80
+ | JavaScript / Python or Rust | Purpose |
81
+ | --- | --- |
82
+ | `normalize` | Recognize a base64 image or data URL |
83
+ | `exceedsLimits` / `exceeds_limits` | Check a raster pixel budget |
84
+ | `scaleToFit` / `scale_to_fit` | Calculate a downscaling factor |
85
+ | `signatureSize` / `signature_size` | Fit dimensions to a point size |
86
+ | `imageSnippet` / `image_snippet` | Generate a Typst image call |
87
+
88
+ Base64 input uses the standard alphabet, required padding, and canonical trailing bits; embedded whitespace is rejected.
89
+
90
+ PNG and JPEG dimensions are read from headers; this is not a full raster integrity check. SVG passes through without sanitization or known dimensions. Unrecognized headers and unsupported formats return `null`/`None`. Nonpositive, nonfinite, and unrepresentable requested sizes return `null`/`None`. Resampling and placement belong to the caller. These are handwriting images, not cryptographic or electronic signatures.
91
+
92
+ ## Correspondence family
93
+
94
+ | Library | Responsibility |
95
+ | --- | --- |
96
+ | [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
97
+ | [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
98
+ | [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
99
+ | [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
100
+ | [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
101
+
102
+
103
+ ## Development
104
+
105
+ Behavior is defined by [the locale tables](https://github.com/corbet-labs/cink/tree/main/tables)
106
+ and [shared conformance vectors](https://github.com/corbet-labs/cink/tree/main/tests/vectors).
107
+ Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
108
+ installed JavaScript tarballs, Python wheels and command-line entrypoints, and
109
+ Typst packages. Release validation records the actual runtime and platform;
110
+ Linux results do not establish native Windows or macOS coverage.
111
+ All five Rust crates forbid unsafe code in their own source.
112
+
113
+ See [the release guide](https://github.com/corbet-labs/cink/blob/main/docs/releasing.md)
114
+ for generation, verification, and publication commands.
115
+
116
+ ## License
117
+
118
+ Copyright 2026 Julian Y. Richard Corbet. cink 0.1.4 is licensed under [Apache-2.0](https://github.com/corbet-labs/cink/blob/main/LICENSES/Apache-2.0.txt). Previously published versions retain their original license grants.
cink-0.1.4/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # cink
2
+
3
+ **Prepare handwritten signature images for correspondence.**
4
+
5
+ [![crates.io](https://img.shields.io/crates/v/cink.svg)](https://crates.io/crates/cink) [![npm](https://img.shields.io/npm/v/@corbet-labs/cink.svg)](https://www.npmjs.com/package/@corbet-labs/cink) [![Rust API](https://docs.rs/cink/badge.svg)](https://docs.rs/cink)
6
+
7
+ Recognize PNG, JPEG, and SVG input, inspect raster dimensions, calculate an aspect-preserving size, and generate a Typst image call. Runs without an image-decoding library.
8
+
9
+ ```js
10
+ import { imageSnippet } from '@corbet-labs/cink';
11
+
12
+ imageSnippet('/signature.png', 31.5);
13
+ // #image("/signature.png", height: 31.5pt)
14
+ ```
15
+
16
+ ## Install
17
+
18
+ | Environment | Command |
19
+ | --- | --- |
20
+ | Rust / Cargo | `cargo add cink` |
21
+ | Node.js / npm | `npm install @corbet-labs/cink` |
22
+ | pnpm | `pnpm add @corbet-labs/cink` |
23
+ | Yarn | `yarn add @corbet-labs/cink` |
24
+ | Bun | `bun add @corbet-labs/cink` |
25
+ | Deno | `deno add npm:@corbet-labs/cink` |
26
+
27
+ The 0.1.4 JavaScript distribution includes compiled ESM, CommonJS,
28
+ TypeScript declarations, and a standalone browser module. Node.js 20+ is
29
+ supported; no TypeScript loader is required.
30
+
31
+ ```js
32
+ // CommonJS
33
+ const { imageSnippet } = require('@corbet-labs/cink');
34
+ ```
35
+
36
+ ```html
37
+ <script type="module">
38
+ import { imageSnippet } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cink@0.1.4/dist/browser.js';
39
+ console.log(imageSnippet('/signature.png', 31.5));
40
+ </script>
41
+ ```
42
+
43
+ Python wheels, source distributions, and CLI instructions are in the
44
+ [installation guide](https://github.com/corbet-labs/cink/blob/main/docs/installation.md).
45
+ JSR publication and Typst availability are listed there explicitly.
46
+
47
+ ## Rust
48
+
49
+ ```rust
50
+ use cink::image_snippet;
51
+
52
+ assert_eq!(image_snippet("/signature.png", 31.5, None), "#image(\"/signature.png\", height: 31.5pt)");
53
+ ```
54
+
55
+ ## Python
56
+
57
+ ```python
58
+ from cink import image_snippet
59
+
60
+ assert image_snippet("/signature.png", 31.5) == '#image("/signature.png", height: 31.5pt)'
61
+ ```
62
+
63
+ ## API
64
+
65
+ | JavaScript / Python or Rust | Purpose |
66
+ | --- | --- |
67
+ | `normalize` | Recognize a base64 image or data URL |
68
+ | `exceedsLimits` / `exceeds_limits` | Check a raster pixel budget |
69
+ | `scaleToFit` / `scale_to_fit` | Calculate a downscaling factor |
70
+ | `signatureSize` / `signature_size` | Fit dimensions to a point size |
71
+ | `imageSnippet` / `image_snippet` | Generate a Typst image call |
72
+
73
+ Base64 input uses the standard alphabet, required padding, and canonical trailing bits; embedded whitespace is rejected.
74
+
75
+ PNG and JPEG dimensions are read from headers; this is not a full raster integrity check. SVG passes through without sanitization or known dimensions. Unrecognized headers and unsupported formats return `null`/`None`. Nonpositive, nonfinite, and unrepresentable requested sizes return `null`/`None`. Resampling and placement belong to the caller. These are handwriting images, not cryptographic or electronic signatures.
76
+
77
+ ## Correspondence family
78
+
79
+ | Library | Responsibility |
80
+ | --- | --- |
81
+ | [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
82
+ | [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
83
+ | [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
84
+ | [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
85
+ | [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
86
+
87
+
88
+ ## Development
89
+
90
+ Behavior is defined by [the locale tables](https://github.com/corbet-labs/cink/tree/main/tables)
91
+ and [shared conformance vectors](https://github.com/corbet-labs/cink/tree/main/tests/vectors).
92
+ Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
93
+ installed JavaScript tarballs, Python wheels and command-line entrypoints, and
94
+ Typst packages. Release validation records the actual runtime and platform;
95
+ Linux results do not establish native Windows or macOS coverage.
96
+ All five Rust crates forbid unsafe code in their own source.
97
+
98
+ See [the release guide](https://github.com/corbet-labs/cink/blob/main/docs/releasing.md)
99
+ for generation, verification, and publication commands.
100
+
101
+ ## License
102
+
103
+ Copyright 2026 Julian Y. Richard Corbet. cink 0.1.4 is licensed under [Apache-2.0](https://github.com/corbet-labs/cink/blob/main/LICENSES/Apache-2.0.txt). Previously published versions retain their original license grants.
@@ -0,0 +1,150 @@
1
+ """Validate and size handwritten signature images for correspondence."""
2
+
3
+ import base64
4
+ import binascii
5
+ import math
6
+ import struct
7
+ from dataclasses import dataclass
8
+ from typing import Literal
9
+
10
+ from ._tables import TABLES
11
+
12
+ _DEFAULTS = TABLES["defaults"]
13
+ _PNG = b"\x89PNG\r\n\x1a\n"
14
+ _SOF = {0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf}
15
+ __all__ = ["default_max_pixels", "supported_formats", "normalize", "exceeds_limits",
16
+ "scale_to_fit", "signature_size", "image_snippet"]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class DecodedImage:
21
+ """Image format, optional raster dimensions, and original encoded bytes."""
22
+
23
+ mime: Literal["png", "jpeg", "svg"]
24
+ width: int | None
25
+ height: int | None
26
+ bytes: bytes
27
+
28
+
29
+ def default_max_pixels() -> int:
30
+ """Default raster pixel budget."""
31
+ return _DEFAULTS["max_pixels"]
32
+
33
+
34
+ def supported_formats() -> list[str]:
35
+ """Accepted image formats."""
36
+ return sorted(_DEFAULTS["formats"])
37
+
38
+
39
+ def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
40
+ pos = 2
41
+ while pos < len(data):
42
+ if data[pos] != 0xff:
43
+ return None
44
+ while pos < len(data) and data[pos] == 0xff:
45
+ pos += 1
46
+ if pos >= len(data):
47
+ return None
48
+ marker = data[pos]
49
+ pos += 1
50
+ if marker == 1:
51
+ continue
52
+ if marker == 0 or 0xd0 <= marker <= 0xda:
53
+ return None
54
+ if pos + 2 > len(data):
55
+ return None
56
+ length = struct.unpack_from(">H", data, pos)[0]
57
+ if length < 2 or length > len(data) - pos:
58
+ return None
59
+ if marker in _SOF:
60
+ if length < 8:
61
+ return None
62
+ components = data[pos + 7]
63
+ if not components or length != 8 + 3 * components:
64
+ return None
65
+ height, width = struct.unpack_from(">HH", data, pos + 3)
66
+ return (width, height) if width and height else None
67
+ pos += length
68
+ return None
69
+
70
+
71
+ def normalize(value: str) -> DecodedImage | None:
72
+ """Read PNG/JPEG headers or pass SVG through from canonical base64/a data URL.
73
+
74
+ Required padding must be present; whitespace and nonzero unused bits are rejected.
75
+ Header recognition does not fully decode a raster or sanitize SVG markup.
76
+ """
77
+ payload = value
78
+ if value.startswith("data:") and "," in value:
79
+ meta, payload = value.split(",", 1)
80
+ if not meta.endswith(";base64"):
81
+ return None
82
+ if not payload:
83
+ return None
84
+ try:
85
+ data = base64.b64decode(payload, validate=True)
86
+ if base64.b64encode(data).decode("ascii") != payload:
87
+ return None
88
+ except (ValueError, binascii.Error):
89
+ return None
90
+ if data.startswith(_PNG):
91
+ if len(data) < 33 or data[8:16] != b"\x00\x00\x00\x0dIHDR":
92
+ return None
93
+ width, height = struct.unpack_from(">II", data, 16)
94
+ if not 0 < width <= 0x7fffffff or not 0 < height <= 0x7fffffff:
95
+ return None
96
+ depth, color, compression, filtering, interlace = data[24:29]
97
+ valid_depths = {0: (1, 2, 4, 8, 16), 2: (8, 16), 3: (1, 2, 4, 8), 4: (8, 16), 6: (8, 16)}
98
+ if depth not in valid_depths.get(color, ()) or compression != 0 or filtering != 0 or interlace > 1:
99
+ return None
100
+ return DecodedImage("png", width, height, data)
101
+ if data.startswith(b"\xff\xd8"):
102
+ dims = _jpeg_dimensions(data)
103
+ return DecodedImage("jpeg", *dims, data) if dims else None
104
+ if data.lstrip(b" \t\n\r\f").startswith(b"<svg"):
105
+ return DecodedImage("svg", None, None, data)
106
+ return None
107
+
108
+
109
+ def exceeds_limits(image: DecodedImage, max_pixels: int) -> bool:
110
+ """Whether raster dimensions exceed a pixel budget."""
111
+ return image.width is not None and image.height is not None and image.width * image.height > max_pixels
112
+
113
+
114
+ def scale_to_fit(image: DecodedImage, max_pixels: int) -> float:
115
+ """Scale factor at most one; callers perform any resampling."""
116
+ if image.width is None or image.height is None or not exceeds_limits(image, max_pixels):
117
+ return 1.0
118
+ return math.sqrt(max_pixels / (image.width * image.height))
119
+
120
+
121
+ def signature_size(image: DecodedImage, height_pt: float, max_width_pt: float | None = None) -> tuple[float, float] | None:
122
+ """Aspect-preserving point size, or None for invalid/nonrepresentable sizes."""
123
+ if (type(image.width) is not int or type(image.height) is not int
124
+ or not 0 < image.width <= 0xffffffff or not 0 < image.height <= 0xffffffff
125
+ or type(height_pt) not in (int, float)
126
+ or (max_width_pt is not None and type(max_width_pt) not in (int, float))):
127
+ return None
128
+ try:
129
+ height_pt = float(height_pt)
130
+ if max_width_pt is not None:
131
+ max_width_pt = float(max_width_pt)
132
+ except OverflowError:
133
+ return None
134
+ if (not math.isfinite(height_pt) or height_pt <= 0
135
+ or (max_width_pt is not None and (not math.isfinite(max_width_pt) or max_width_pt <= 0))):
136
+ return None
137
+ ratio = image.width / image.height
138
+ width = height_pt * ratio
139
+ if max_width_pt is not None and width > max_width_pt:
140
+ width, height_pt = max_width_pt, max_width_pt / ratio
141
+ return (width, height_pt) if math.isfinite(width) and math.isfinite(height_pt) and width > 0 and height_pt > 0 else None
142
+
143
+
144
+ def image_snippet(path: str, height_pt: float, width_pt: float | None = None) -> str:
145
+ """A Typst image call; placement remains the caller's responsibility."""
146
+ escapes = {'"': '\\"', "\\": "\\\\", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
147
+ safe = "".join(escapes.get(char, f"\\u{{{ord(char):x}}}" if ord(char) < 32 or 127 <= ord(char) <= 159 else char) for char in path)
148
+ height = format(height_pt, ".15g")
149
+ width = "" if width_pt is None else f", width: {format(width_pt, '.15g')}pt"
150
+ return f'#image("{safe}", height: {height}pt{width})'
@@ -0,0 +1,50 @@
1
+ """JSON command-line bridge for callers in any programming language."""
2
+ import argparse
3
+ import base64
4
+ import dataclasses
5
+ import json
6
+ import sys
7
+ import cink as api
8
+
9
+
10
+ def _json_default(value):
11
+ if dataclasses.is_dataclass(value):
12
+ return dataclasses.asdict(value)
13
+ if isinstance(value, bytes):
14
+ return base64.b64encode(value).decode("ascii")
15
+ raise TypeError(f"Cannot serialize {type(value).__name__}")
16
+
17
+
18
+ def _reject_constant(value):
19
+ raise ValueError(f"{value} is not a JSON number")
20
+
21
+
22
+ def main():
23
+ parser = argparse.ArgumentParser(description="Call cink functions with JSON arguments.")
24
+ parser.add_argument("function", choices=api.__all__)
25
+ parser.add_argument("arguments", nargs="?", default="[]", help="JSON array of positional arguments or object of keyword arguments; '-' reads UTF-8 stdin")
26
+ args = parser.parse_args()
27
+ try:
28
+ values = json.loads(sys.stdin.buffer.read().decode("utf-8") if args.arguments == "-" else args.arguments, parse_constant=_reject_constant)
29
+ if not isinstance(values, (list, dict)):
30
+ raise ValueError("arguments must be a JSON array or object")
31
+ # Image operations accept the JSON object returned by normalize.
32
+ if args.function in ("exceeds_limits", "scale_to_fit", "signature_size"):
33
+ raw = values[0] if isinstance(values, list) else values["image"]
34
+ if isinstance(raw, dict):
35
+ raw = dict(raw)
36
+ raw["bytes"] = base64.b64decode(raw["bytes"], validate=True)
37
+ image = api.DecodedImage(**raw)
38
+ if isinstance(values, list):
39
+ values[0] = image
40
+ else:
41
+ values["image"] = image
42
+ fn = getattr(api, args.function)
43
+ result = fn(*values) if isinstance(values, list) else fn(**values)
44
+ print(json.dumps(result, default=_json_default, ensure_ascii=True, allow_nan=False))
45
+ except (ValueError, TypeError, KeyError, IndexError, AttributeError, OverflowError) as error:
46
+ parser.error(str(error))
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
@@ -0,0 +1,2 @@
1
+ # Generated by scripts/sync-python.py; edit tables/*.json instead.
2
+ TABLES = {'defaults': {'max_pixels': 1600, 'formats': ['png', 'jpeg', 'svg']}}
File without changes
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cink"
7
+ version = "0.1.4"
8
+ description = "Handwritten signature image rendering for correspondence. Pixels, not signatures"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSES/*"]
12
+ requires-python = ">=3.10"
13
+ keywords = ["i18n", "correspondence", "locale"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent"]
15
+
16
+
17
+ [project.urls]
18
+ Homepage = "https://github.com/corbet-labs/cink#readme"
19
+ Repository = "https://github.com/corbet-labs/cink"
20
+ Issues = "https://github.com/corbet-labs/cink/issues"
21
+
22
+ [project.scripts]
23
+ cink = "cink.__main__:main"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["cink"]
@@ -0,0 +1,64 @@
1
+ """Run canonical vectors against either the source port or an installed wheel."""
2
+ import base64
3
+ import importlib
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ ROOT = Path(__file__).resolve().parents[2]
9
+ if "--installed" not in sys.argv:
10
+ sys.path.insert(0, str(ROOT / "py"))
11
+ api = importlib.import_module("cink")
12
+
13
+ ARGUMENTS = {
14
+ "region_parse": ["input"], "region_uses_comma": ["input"],
15
+ "salutation_last_name": ["input"], "salutation_honorific": ["input"],
16
+ "salutation_titles": ["input"], "salutation_surname": ["input"],
17
+ "de_salutation": ["input", "region"],
18
+ "recipient_salutation_warning": ["location", "input"],
19
+ "de_honorific_warning": ["location", "input"],
20
+ "closing": ["locale", "override"], "available_locales": [],
21
+ "long_date": ["locale", "year", "month", "day"],
22
+ "medium_date": ["locale", "year", "month", "day"],
23
+ "short_date": ["locale", "year", "month", "day"],
24
+ "month_year": ["locale", "year", "month"], "is_supported": ["locale"],
25
+ "supported_formats": [], "normalize": ["input"],
26
+ "exceeds_limits": ["image", "max_pixels"], "scale_to_fit": ["image", "max_pixels"],
27
+ "signature_size": ["image", "height_pt", "max_width_pt"],
28
+ "image_snippet": ["path", "height_pt", "width_pt"],
29
+ "resolve_locale": ["language", "location"],
30
+ "opening": ["locale", "person", "override"],
31
+ "subject": ["locale", "title", "prefix_override"],
32
+ "salutation": ["locale", "person"], "apply_ortho": ["locale", "text"],
33
+ "warnings": ["location", "locale", "person"],
34
+ }
35
+
36
+ files = sorted((ROOT / "tests/vectors").glob("*.json"))
37
+ assert files, "No conformance vectors"
38
+ count = 0
39
+ for file in files:
40
+ for vector in json.loads(file.read_text(encoding="utf-8")):
41
+ name = vector["fn"]
42
+ values = dict(vector)
43
+ if "fixture" in vector:
44
+ values["input"] = base64.b64encode((ROOT / "tests/fixtures" / vector["fixture"]).read_bytes()).decode("ascii")
45
+ if name != "normalize":
46
+ values["image"] = api.normalize(values["input"])
47
+ fn = getattr(api, "parse_region" if name == "region_parse" else name)
48
+ actual = fn(*(values.get(key) for key in ARGUMENTS[name]))
49
+ if name == "normalize" and actual is not None:
50
+ actual = {key: getattr(actual, key) for key in ("mime", "width", "height")}
51
+ if isinstance(actual, tuple):
52
+ actual = list(actual)
53
+ if actual != vector["expected"]:
54
+ raise AssertionError(f"{file.name} :: {vector['name']}: {actual!r} != {vector['expected']!r}")
55
+ count += 1
56
+ image = api.DecodedImage("png", 1, 1, b"")
57
+ for invalid in (float("nan"), float("inf"), -float("inf"), 0, -1, True, 10**400):
58
+ assert api.signature_size(image, invalid) is None
59
+ assert api.signature_size(image, 20, invalid) is None
60
+ for invalid_dimension in (0, -1, 1.5, True, 0x100000000):
61
+ assert api.signature_size(api.DecodedImage("png", invalid_dimension, 1, b""), 20) is None
62
+ assert api.signature_size(api.DecodedImage("png", 2, 1, b""), sys.float_info.max, 30) == (30, 15)
63
+ assert api.signature_size(api.DecodedImage("png", 1, 2, b""), float.fromhex("0x0.0000000000001p-1022")) is None
64
+ print(f"Python cink: {count} vectors across {len(files)} files and numeric boundary checks passed")
@@ -0,0 +1,106 @@
1
+ """Verify wheel/sdist contents and installed Python/console entrypoints.
2
+
3
+ Run with the interpreter in a fresh environment containing the wheel and its
4
+ declared dependencies. This script never adds the source package to sys.path.
5
+ """
6
+ import argparse
7
+ import base64
8
+ from email.parser import BytesParser
9
+ import importlib
10
+ import importlib.metadata
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import subprocess
15
+ import sys
16
+ import tarfile
17
+ import tempfile
18
+ import zipfile
19
+
20
+ ROOT = Path(__file__).resolve().parents[2]
21
+ PACKAGES = [path.name for path in (ROOT / "py").iterdir() if (path / "__init__.py").is_file()]
22
+ if len(PACKAGES) != 1:
23
+ raise RuntimeError("Expected exactly one source package")
24
+ NAME = PACKAGES[0]
25
+ CASES = {
26
+ "cgreet": ("de_salutation", ["Frau Dr. Müller", "ch"],
27
+ {"name": "Frau Dr. Müller", "region": "ch"}, "Sehr geehrte Frau Dr. Müller"),
28
+ "cfarewell": ("closing", ["DE-LI"], {"locale": "DE-LI"}, "Freundliche Grüsse"),
29
+ "cdate": ("long_date", ["EN-GB", 2026, 9, 7],
30
+ {"locale": "EN-GB", "year": 2026, "month": 9, "day": 7}, "7 September 2026"),
31
+ "cink": ("image_snippet", ["signature.png", 20],
32
+ {"path": "signature.png", "height_pt": 20}, '#image("signature.png", height: 20pt)'),
33
+ "cletter": ("salutation", ["DE-LI", "Frau Dr. Müller"],
34
+ {"locale": "DE-LI", "name": "Frau Dr. Müller"}, "Sehr geehrte Frau Dr. Müller"),
35
+ }
36
+
37
+
38
+ def check(condition, message):
39
+ if not condition:
40
+ raise AssertionError(message)
41
+
42
+
43
+ parser = argparse.ArgumentParser(description=__doc__)
44
+ parser.add_argument("--wheel", type=Path, required=True)
45
+ parser.add_argument("--sdist", type=Path, required=True)
46
+ args = parser.parse_args()
47
+ licenses = {path.name: path.read_bytes() for path in (ROOT / "LICENSES").iterdir() if path.is_file()}
48
+ check(bool(licenses), "Source licenses are missing")
49
+ with zipfile.ZipFile(args.wheel) as wheel:
50
+ files = wheel.namelist()
51
+ check(f"{NAME}/py.typed" in files, "Wheel is missing py.typed")
52
+ metadata_paths = [path for path in files if path.endswith(".dist-info/METADATA")]
53
+ check(len(metadata_paths) == 1, "Expected one wheel distribution")
54
+ metadata = BytesParser().parsebytes(wheel.read(metadata_paths[0]))
55
+ check(metadata["Name"] == NAME, "Wheel package name differs from repository")
56
+ expected_license = json.loads((ROOT / "js" / "@corbet-labs" / NAME / "package.json").read_text())["license"]
57
+ check(metadata["License-Expression"] == expected_license, "Wheel license differs from repository")
58
+ for name, expected in licenses.items():
59
+ check(any(path.endswith("/LICENSES/" + name) and wheel.read(path) == expected for path in files),
60
+ f"Wheel is missing the original {name}")
61
+ with tarfile.open(args.sdist, "r:gz") as sdist:
62
+ files = {member.name: member for member in sdist.getmembers() if member.isfile()}
63
+ for name, expected in licenses.items():
64
+ check(any(path.endswith("/LICENSES/" + name) and sdist.extractfile(member).read() == expected
65
+ for path, member in files.items()), f"Source distribution is missing {name}")
66
+
67
+ distribution = importlib.metadata.distribution(NAME)
68
+ check(distribution.version == metadata["Version"], "Installed version differs from wheel")
69
+ check(any(entry.group == "console_scripts" and entry.name == NAME and entry.value == f"{NAME}.__main__:main"
70
+ for entry in distribution.entry_points), "Missing console entrypoint metadata")
71
+ api = importlib.import_module(NAME)
72
+ check(not Path(api.__file__).resolve().is_relative_to(ROOT / "py"), "Imported source tree instead of installed wheel")
73
+ entrypoint = Path(sys.executable).parent / (NAME + (".exe" if os.name == "nt" else ""))
74
+ check(entrypoint.is_file(), "Installer did not create the console entrypoint")
75
+ function, positional, keywords, expected = CASES[NAME]
76
+
77
+ with tempfile.TemporaryDirectory(prefix=f"{NAME}-python-consumer-") as cwd:
78
+ def call(command, function, values, *, stdin=False, valid=True):
79
+ payload = values if isinstance(values, str) else json.dumps(values, ensure_ascii=False)
80
+ result = subprocess.run(command + [function, "-" if stdin else payload],
81
+ input=payload if stdin else None, cwd=cwd, text=True,
82
+ encoding="utf-8", capture_output=True, timeout=30)
83
+ if valid:
84
+ check(result.returncode == 0, result.stderr)
85
+ return json.loads(result.stdout)
86
+ check(result.returncode == 2 and not result.stdout and "Traceback" not in result.stderr,
87
+ f"Invalid arguments did not produce a clean CLI error: {result}")
88
+
89
+ for command in ([sys.executable, "-m", NAME], [str(entrypoint)]):
90
+ check(call(command, function, positional) == expected, "Positional JSON invocation failed")
91
+ check(call(command, function, keywords, stdin=True) == expected, "Keyword/stdin invocation failed")
92
+ call(command, function, "null", valid=False)
93
+ call(command, function, "[NaN]", valid=False)
94
+ call(command, function, [], valid=False)
95
+ if NAME in ("cink", "cletter"):
96
+ encoded = base64.b64encode(b'<svg xmlns="http://www.w3.org/2000/svg"/>').decode("ascii")
97
+ decoded = call([str(entrypoint)], "normalize", [encoded])
98
+ check(decoded["bytes"] == encoded and decoded["mime"] == "svg", "Image JSON output lost encoded bytes")
99
+ check(call([str(entrypoint)], "signature_size", {"image": decoded, "height_pt": 20}) is None,
100
+ "Image JSON output cannot be used as a subsequent input")
101
+ raster = {"mime": "png", "width": 1, "height": 1, "bytes": ""}
102
+ check(call([str(entrypoint)], "signature_size", {"image": raster, "height_pt": 10**400}) is None,
103
+ "An unrepresentable height escaped the JSON bridge")
104
+ check(call([str(entrypoint)], "signature_size", {"image": raster, "height_pt": 20, "max_width_pt": 10**400}) is None,
105
+ "An unrepresentable maximum width escaped the JSON bridge")
106
+ print(f"Python {NAME}: installed module, console JSON calls, wheel/sdist licenses and metadata passed")