oicana 0.1.0__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.
@@ -0,0 +1,10 @@
1
+ target/
2
+ .idea/
3
+ output/
4
+ .env
5
+ .dependencies/
6
+ e2e-tests/template/oicana-e2e-test-*.zip
7
+ ort/
8
+ AGENTS.md
9
+ __pycache__/
10
+ release.sh
@@ -0,0 +1,131 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncommercial Purposes
53
+
54
+ Any noncommercial purpose is a permitted purpose.
55
+
56
+ ## Personal Uses
57
+
58
+ Personal use for research, experiment, and testing for
59
+ the benefit of public knowledge, personal study, private
60
+ entertainment, hobby projects, amateur pursuits, or religious
61
+ observance, without any anticipated commercial application,
62
+ is use for a permitted purpose.
63
+
64
+ ## Noncommercial Organizations
65
+
66
+ Use by any charitable organization, educational institution,
67
+ public research organization, public safety or health
68
+ organization, environmental protection organization,
69
+ or government institution is use for a permitted purpose
70
+ regardless of the source of funding or obligations resulting
71
+ from the funding.
72
+
73
+ ## Fair Use
74
+
75
+ You may have "fair use" rights for the software under the
76
+ law. These terms do not limit them.
77
+
78
+ ## No Other Rights
79
+
80
+ These terms do not allow you to sublicense or transfer any of
81
+ your licenses to anyone else, or prevent the licensor from
82
+ granting licenses to anyone else. These terms do not imply
83
+ any other licenses.
84
+
85
+ ## Patent Defense
86
+
87
+ If you make any written claim that the software infringes or
88
+ contributes to infringement of any patent, your patent license
89
+ for the software granted under these terms ends immediately. If
90
+ your company makes such a claim, your patent license ends
91
+ immediately for work on behalf of your company.
92
+
93
+ ## Violations
94
+
95
+ The first time you are notified in writing that you have
96
+ violated any of these terms, or done anything with the software
97
+ not covered by your licenses, your licenses can nonetheless
98
+ continue if you come into full compliance with these terms,
99
+ and take practical steps to correct past violations, within
100
+ 32 days of receiving notice. Otherwise, all your licenses
101
+ end immediately.
102
+
103
+ ## No Liability
104
+
105
+ ***As far as the law allows, the software comes as is, without
106
+ any warranty or condition, and the licensor will not be liable
107
+ to you for any damages arising out of these terms or the use
108
+ or nature of the software, under any kind of legal claim.***
109
+
110
+ ## Definitions
111
+
112
+ The **licensor** is the individual or entity offering these
113
+ terms, and the **software** is the software the licensor makes
114
+ available under these terms.
115
+
116
+ **You** refers to the individual or entity agreeing to these
117
+ terms.
118
+
119
+ **Your company** is any legal entity, sole proprietorship,
120
+ or other kind of organization that you work for, plus all
121
+ organizations that have control over, are under the control of,
122
+ or are under common control with that organization. **Control**
123
+ means ownership of substantially all the assets of an entity,
124
+ or the power to direct its management and policies by vote,
125
+ contract, or otherwise. Control can be direct or indirect.
126
+
127
+ **Your licenses** are all the licenses granted to you for the
128
+ software under these terms.
129
+
130
+ **Use** means anything you do with the software requiring one
131
+ of your licenses.
oicana-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: oicana
3
+ Version: 0.1.0
4
+ Summary: PDF templating with Typst
5
+ Project-URL: Homepage, https://oicana.com
6
+ Project-URL: Repository, https://github.com/oicana/oicana
7
+ Project-URL: Documentation, https://oicana.com/docs
8
+ Author-email: Oicana <hello@oicana.com>
9
+ License: # PolyForm Noncommercial License 1.0.0
10
+
11
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
12
+
13
+ ## Acceptance
14
+
15
+ In order to get any license under these terms, you must agree
16
+ to them as both strict obligations and conditions to all
17
+ your licenses.
18
+
19
+ ## Copyright License
20
+
21
+ The licensor grants you a copyright license for the
22
+ software to do everything you might do with the software
23
+ that would otherwise infringe the licensor's copyright
24
+ in it for any permitted purpose. However, you may
25
+ only distribute the software according to [Distribution
26
+ License](#distribution-license) and make changes or new works
27
+ based on the software according to [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Distribution License
31
+
32
+ The licensor grants you an additional copyright license
33
+ to distribute copies of the software. Your license
34
+ to distribute covers distributing the software with
35
+ changes and new works permitted by [Changes and New Works
36
+ License](#changes-and-new-works-license).
37
+
38
+ ## Notices
39
+
40
+ You must ensure that anyone who gets a copy of any part of
41
+ the software from you also gets a copy of these terms or the
42
+ URL for them above, as well as copies of any plain-text lines
43
+ beginning with `Required Notice:` that the licensor provided
44
+ with the software. For example:
45
+
46
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
47
+
48
+ ## Changes and New Works License
49
+
50
+ The licensor grants you an additional copyright license to
51
+ make changes and new works based on the software for any
52
+ permitted purpose.
53
+
54
+ ## Patent License
55
+
56
+ The licensor grants you a patent license for the software that
57
+ covers patent claims the licensor can license, or becomes able
58
+ to license, that you would infringe by using the software.
59
+
60
+ ## Noncommercial Purposes
61
+
62
+ Any noncommercial purpose is a permitted purpose.
63
+
64
+ ## Personal Uses
65
+
66
+ Personal use for research, experiment, and testing for
67
+ the benefit of public knowledge, personal study, private
68
+ entertainment, hobby projects, amateur pursuits, or religious
69
+ observance, without any anticipated commercial application,
70
+ is use for a permitted purpose.
71
+
72
+ ## Noncommercial Organizations
73
+
74
+ Use by any charitable organization, educational institution,
75
+ public research organization, public safety or health
76
+ organization, environmental protection organization,
77
+ or government institution is use for a permitted purpose
78
+ regardless of the source of funding or obligations resulting
79
+ from the funding.
80
+
81
+ ## Fair Use
82
+
83
+ You may have "fair use" rights for the software under the
84
+ law. These terms do not limit them.
85
+
86
+ ## No Other Rights
87
+
88
+ These terms do not allow you to sublicense or transfer any of
89
+ your licenses to anyone else, or prevent the licensor from
90
+ granting licenses to anyone else. These terms do not imply
91
+ any other licenses.
92
+
93
+ ## Patent Defense
94
+
95
+ If you make any written claim that the software infringes or
96
+ contributes to infringement of any patent, your patent license
97
+ for the software granted under these terms ends immediately. If
98
+ your company makes such a claim, your patent license ends
99
+ immediately for work on behalf of your company.
100
+
101
+ ## Violations
102
+
103
+ The first time you are notified in writing that you have
104
+ violated any of these terms, or done anything with the software
105
+ not covered by your licenses, your licenses can nonetheless
106
+ continue if you come into full compliance with these terms,
107
+ and take practical steps to correct past violations, within
108
+ 32 days of receiving notice. Otherwise, all your licenses
109
+ end immediately.
110
+
111
+ ## No Liability
112
+
113
+ ***As far as the law allows, the software comes as is, without
114
+ any warranty or condition, and the licensor will not be liable
115
+ to you for any damages arising out of these terms or the use
116
+ or nature of the software, under any kind of legal claim.***
117
+
118
+ ## Definitions
119
+
120
+ The **licensor** is the individual or entity offering these
121
+ terms, and the **software** is the software the licensor makes
122
+ available under these terms.
123
+
124
+ **You** refers to the individual or entity agreeing to these
125
+ terms.
126
+
127
+ **Your company** is any legal entity, sole proprietorship,
128
+ or other kind of organization that you work for, plus all
129
+ organizations that have control over, are under the control of,
130
+ or are under common control with that organization. **Control**
131
+ means ownership of substantially all the assets of an entity,
132
+ or the power to direct its management and policies by vote,
133
+ contract, or otherwise. Control can be direct or indirect.
134
+
135
+ **Your licenses** are all the licenses granted to you for the
136
+ software under these terms.
137
+
138
+ **Use** means anything you do with the software requiring one
139
+ of your licenses.
140
+ License-File: LICENSE.md
141
+ Keywords: oicana,pdf,typesetting,typst
142
+ Classifier: Development Status :: 4 - Beta
143
+ Classifier: Intended Audience :: Developers
144
+ Classifier: Programming Language :: Python :: 3
145
+ Classifier: Programming Language :: Python :: 3.11
146
+ Classifier: Programming Language :: Python :: 3.12
147
+ Classifier: Programming Language :: Python :: 3.13
148
+ Classifier: Programming Language :: Python :: 3.14
149
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
150
+ Requires-Python: >=3.11
151
+ Requires-Dist: oicana-native>=0.1.0
152
+ Provides-Extra: dev
153
+ Requires-Dist: mypy>=1.0; extra == 'dev'
154
+ Requires-Dist: pytest>=7.0; extra == 'dev'
155
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
156
+ Provides-Extra: test
157
+ Requires-Dist: pytest>=7.0; extra == 'test'
158
+ Description-Content-Type: text/markdown
159
+
160
+ # Oicana
161
+
162
+ Dynamic PDF Generation based on Typst.
163
+
164
+ Oicana offers seamless PDF templating. Define your templates in Typst, specify dynamic inputs, and generate high quality PDFs from your application code.
165
+
166
+ ## Installation
167
+
168
+ ```bash
169
+ uv add oicana
170
+ ```
171
+
172
+ ## Quick Start
173
+
174
+ ```python
175
+ import json
176
+ from oicana import Template, CompilationMode
177
+
178
+ # Load your template
179
+ with open("template.zip", "rb") as f:
180
+ template_bytes = f.read()
181
+
182
+ # Create template and compile
183
+ with Template(template_bytes) as template:
184
+ pdf = template.compile(
185
+ json_inputs={
186
+ "invoice": json.dumps({
187
+ "number": "INV-001",
188
+ "items": [{"name": "Service", "price": 100}]
189
+ })
190
+ },
191
+ export={"format": "pdf"},
192
+ mode=CompilationMode.PRODUCTION,
193
+ )
194
+
195
+ # Save the PDF
196
+ with open("output.pdf", "wb") as f:
197
+ f.write(pdf)
198
+ ```
199
+
200
+ ## Features
201
+
202
+ - **Multi-platform**: Works on Linux, macOS, and Windows
203
+ - **Powerful Layouting**: Full access to Typst's functionality
204
+ - **Performant**: Native Rust performance via PyO3
205
+ - **Type Safe**: Full type hints for IDE support
206
+ - **Pythonic**: Context managers, dataclasses, and enums
207
+
208
+ ## Documentation
209
+
210
+ For more information, visit [https://oicana.com/docs](https://oicana.com/docs)
211
+
212
+
213
+ ## Licensing
214
+
215
+ Oicana is source-available under [PolyForm Noncommercial License 1.0.0](./LICENSE.md). You can use it for free in any noncommercial context.
216
+ For commercial use, please visit [the Oicana website][oicana-website] for pricing options.
217
+
218
+
219
+ [oicana-website]: https://oicana.com
oicana-0.1.0/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # Oicana
2
+
3
+ Dynamic PDF Generation based on Typst.
4
+
5
+ Oicana offers seamless PDF templating. Define your templates in Typst, specify dynamic inputs, and generate high quality PDFs from your application code.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ uv add oicana
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```python
16
+ import json
17
+ from oicana import Template, CompilationMode
18
+
19
+ # Load your template
20
+ with open("template.zip", "rb") as f:
21
+ template_bytes = f.read()
22
+
23
+ # Create template and compile
24
+ with Template(template_bytes) as template:
25
+ pdf = template.compile(
26
+ json_inputs={
27
+ "invoice": json.dumps({
28
+ "number": "INV-001",
29
+ "items": [{"name": "Service", "price": 100}]
30
+ })
31
+ },
32
+ export={"format": "pdf"},
33
+ mode=CompilationMode.PRODUCTION,
34
+ )
35
+
36
+ # Save the PDF
37
+ with open("output.pdf", "wb") as f:
38
+ f.write(pdf)
39
+ ```
40
+
41
+ ## Features
42
+
43
+ - **Multi-platform**: Works on Linux, macOS, and Windows
44
+ - **Powerful Layouting**: Full access to Typst's functionality
45
+ - **Performant**: Native Rust performance via PyO3
46
+ - **Type Safe**: Full type hints for IDE support
47
+ - **Pythonic**: Context managers, dataclasses, and enums
48
+
49
+ ## Documentation
50
+
51
+ For more information, visit [https://oicana.com/docs](https://oicana.com/docs)
52
+
53
+
54
+ ## Licensing
55
+
56
+ Oicana is source-available under [PolyForm Noncommercial License 1.0.0](./LICENSE.md). You can use it for free in any noncommercial context.
57
+ For commercial use, please visit [the Oicana website][oicana-website] for pricing options.
58
+
59
+
60
+ [oicana-website]: https://oicana.com
@@ -0,0 +1,69 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "oicana"
7
+ version = "0.1.0"
8
+ description = "PDF templating with Typst"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { file = "LICENSE.md" }
12
+ authors = [
13
+ { name = "Oicana", email = "hello@oicana.com" }
14
+ ]
15
+ dependencies = [
16
+ "oicana-native>=0.1.0",
17
+ ]
18
+ keywords = ["oicana", "typst", "typesetting", "pdf"]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Developers",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://oicana.com"
32
+ Repository = "https://github.com/oicana/oicana"
33
+ Documentation = "https://oicana.com/docs"
34
+
35
+ [project.optional-dependencies]
36
+ dev = [
37
+ "pytest>=7.0",
38
+ "mypy>=1.0",
39
+ "ruff>=0.1.0",
40
+ ]
41
+ test = [
42
+ "pytest>=7.0",
43
+ ]
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/oicana"]
47
+
48
+ [tool.ruff]
49
+ line-length = 100
50
+ target-version = "py38"
51
+
52
+ [tool.ruff.lint]
53
+ select = ["E", "F", "I", "UP"]
54
+
55
+ [tool.uv.sources]
56
+ oicana-native = { workspace = true }
57
+
58
+ [dependency-groups]
59
+ dev = [
60
+ "pytest>=7.0",
61
+ "mypy>=1.0",
62
+ "ruff>=0.1.0",
63
+ ]
64
+
65
+ [tool.mypy]
66
+ python_version = "3.9"
67
+ warn_return_any = true
68
+ warn_unused_configs = true
69
+ disallow_untyped_defs = true
@@ -0,0 +1,28 @@
1
+ """Oicana - PDF templating with Typst."""
2
+ from .template import Template, configure_automatic_cache_eviction, evict_cache
3
+ from .types import (
4
+ BlobInput,
5
+ BlobInputDefinition,
6
+ CompilationMode,
7
+ ExportFormat,
8
+ ExportFormatPdf,
9
+ ExportFormatPng,
10
+ ExportFormatSvg,
11
+ JsonInputDefinition,
12
+ )
13
+
14
+ __version__ = "0.1.0a1"
15
+
16
+ __all__ = [
17
+ "Template",
18
+ "configure_automatic_cache_eviction",
19
+ "evict_cache",
20
+ "CompilationMode",
21
+ "BlobInput",
22
+ "ExportFormat",
23
+ "ExportFormatPdf",
24
+ "ExportFormatPng",
25
+ "ExportFormatSvg",
26
+ "JsonInputDefinition",
27
+ "BlobInputDefinition",
28
+ ]
File without changes
@@ -0,0 +1,229 @@
1
+ """Oicana Python integration."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import uuid
6
+ from typing import TYPE_CHECKING
7
+
8
+ from oicana_native import (
9
+ BlobWithMetadata,
10
+ compile_template,
11
+ export_document,
12
+ get_file,
13
+ get_source,
14
+ inputs,
15
+ register_template,
16
+ remove_document,
17
+ remove_world,
18
+ )
19
+ from oicana_native import (
20
+ CompilationMode as NativeCompilationMode,
21
+ )
22
+ from oicana_native import (
23
+ configure_automatic_cache_eviction as _configure_automatic_cache_eviction,
24
+ )
25
+ from oicana_native import (
26
+ evict_cache as _evict_cache,
27
+ )
28
+ from oicana_native import (
29
+ set_validate_inputs as _set_validate_inputs,
30
+ )
31
+
32
+ from .types import BlobInput, CompilationMode, ExportFormat
33
+
34
+ if TYPE_CHECKING:
35
+ from typing import Any
36
+
37
+
38
+ class Template:
39
+ """Oicana template for PDF generation.
40
+
41
+ Example:
42
+ >>> with Template(template_bytes) as template:
43
+ ... pdf = template.compile(
44
+ ... json_inputs={"name": '{"value": "Alice"}'},
45
+ ... export={"format": "pdf"}
46
+ ... )
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ template: bytes,
52
+ *,
53
+ json_inputs: dict[str, str] | None = None,
54
+ blob_inputs: dict[str, BlobInput] | None = None,
55
+ mode: CompilationMode = CompilationMode.DEVELOPMENT,
56
+ ) -> None:
57
+ """Initialize template.
58
+
59
+ Args:
60
+ template: Template zip file bytes
61
+ json_inputs: Initial JSON inputs (key -> JSON string)
62
+ blob_inputs: Initial blob inputs
63
+ mode: Compilation mode (development/production)
64
+ """
65
+ self._template_id = str(uuid.uuid4())
66
+ self._document_ids: list[str] = []
67
+
68
+ native_mode = (
69
+ NativeCompilationMode.Production
70
+ if mode == CompilationMode.PRODUCTION
71
+ else NativeCompilationMode.Development
72
+ )
73
+
74
+ native_json = json_inputs if json_inputs is not None else {}
75
+
76
+ native_blobs = {}
77
+ if blob_inputs:
78
+ for key, blob in blob_inputs.items():
79
+ meta_str = json.dumps(blob.metadata) if blob.metadata else "{}"
80
+ native_blobs[key] = BlobWithMetadata(blob.data, meta_str)
81
+
82
+ doc_id = register_template(
83
+ self._template_id,
84
+ template,
85
+ native_json,
86
+ native_blobs,
87
+ native_mode,
88
+ )
89
+ remove_document(doc_id)
90
+
91
+ def compile(
92
+ self,
93
+ *,
94
+ json_inputs: dict[str, str] | None = None,
95
+ blob_inputs: dict[str, BlobInput] | None = None,
96
+ export: ExportFormat = {"format": "pdf"}, # type: ignore[typeddict-item]
97
+ mode: CompilationMode = CompilationMode.PRODUCTION,
98
+ ) -> bytes:
99
+ """Compile template and export to the given format.
100
+
101
+ Args:
102
+ json_inputs: JSON inputs
103
+ blob_inputs: Blob inputs
104
+ export: Export format and configuration (pdf/png/svg)
105
+ mode: Compilation mode
106
+
107
+ Returns:
108
+ Compiled document bytes
109
+ """
110
+ native_mode = (
111
+ NativeCompilationMode.Production
112
+ if mode == CompilationMode.PRODUCTION
113
+ else NativeCompilationMode.Development
114
+ )
115
+
116
+ native_json = json_inputs if json_inputs is not None else {}
117
+
118
+ native_blobs = {}
119
+ if blob_inputs:
120
+ for key, blob in blob_inputs.items():
121
+ meta_str = json.dumps(blob.metadata) if blob.metadata else "{}"
122
+ native_blobs[key] = BlobWithMetadata(blob.data, meta_str)
123
+
124
+ doc_id = compile_template(
125
+ self._template_id,
126
+ native_json,
127
+ native_blobs,
128
+ native_mode,
129
+ )
130
+ self._document_ids.append(doc_id)
131
+
132
+ result = export_document(doc_id, json.dumps(export))
133
+
134
+ remove_document(doc_id)
135
+ self._document_ids.remove(doc_id)
136
+
137
+ return bytes(result)
138
+
139
+ def inputs(self) -> dict[str, Any]:
140
+ """Get input definitions from manifest.
141
+
142
+ Returns:
143
+ Dictionary with input definitions
144
+ """
145
+ inputs_json = inputs(self._template_id)
146
+ return json.loads(inputs_json) # type: ignore[no-any-return]
147
+
148
+ def source(self, path: str) -> str:
149
+ """Get source file content.
150
+
151
+ Args:
152
+ path: File path in template
153
+
154
+ Returns:
155
+ File content as string
156
+ """
157
+ return get_source(self._template_id, path) # type: ignore[no-any-return]
158
+
159
+ def file(self, path: str) -> bytes:
160
+ """Get binary file content.
161
+
162
+ Args:
163
+ path: File path in template
164
+
165
+ Returns:
166
+ File content as bytes
167
+ """
168
+ return bytes(get_file(self._template_id, path))
169
+
170
+ def set_validate_inputs(self, validate: bool) -> None:
171
+ """Enable or disable JSON schema validation for this template.
172
+
173
+ When enabled (the default), JSON inputs are validated against their schemas
174
+ before compilation.
175
+
176
+ Args:
177
+ validate: Whether to validate inputs against their JSON schemas.
178
+ """
179
+ _set_validate_inputs(self._template_id, validate)
180
+
181
+ def cleanup(self) -> None:
182
+ """Clean up cached resources."""
183
+ for doc_id in list(self._document_ids):
184
+ remove_document(doc_id)
185
+ self._document_ids.clear()
186
+
187
+ remove_world(self._template_id)
188
+
189
+ def __enter__(self) -> Template:
190
+ """Context manager entry."""
191
+ return self
192
+
193
+ def __exit__(self, *args: object) -> None:
194
+ """Context manager exit with cleanup."""
195
+ self.cleanup()
196
+
197
+ def __del__(self) -> None:
198
+ """Destructor cleanup."""
199
+ try:
200
+ self.cleanup()
201
+ except Exception:
202
+ pass # Best effort cleanup
203
+
204
+
205
+ def configure_automatic_cache_eviction(max_age: int | None) -> None:
206
+ """Configure automatic cache eviction after each compilation.
207
+
208
+ Args:
209
+ max_age: Maximum age threshold, or None to disable:
210
+ - None - Disables cache eviction (cache never cleared)
211
+ - 0 - Clears all cache entries with every eviction
212
+ - 1 - Keeps only entries used since the last eviction
213
+ - n - Keeps entries used within the last n evictions
214
+ Default is 10.
215
+ """
216
+ _configure_automatic_cache_eviction(max_age)
217
+
218
+
219
+ def evict_cache(max_age: int) -> None:
220
+ """Manually evict the cache with the given age threshold.
221
+
222
+ This directly calls the underlying eviction with the specified age,
223
+ regardless of the configured default age.
224
+
225
+ Args:
226
+ max_age: Maximum age threshold for eviction.
227
+ Entries with age >= this value will be removed.
228
+ """
229
+ _evict_cache(max_age)
@@ -0,0 +1,61 @@
1
+ """Type definitions for Oicana."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from enum import Enum
6
+ from typing import Any, Literal, TypedDict, Union
7
+
8
+
9
+ class CompilationMode(Enum):
10
+ """Template compilation mode."""
11
+
12
+ PRODUCTION = "production"
13
+ DEVELOPMENT = "development"
14
+
15
+
16
+ class ExportFormatPdf(TypedDict):
17
+ """PDF export format."""
18
+
19
+ format: Literal["pdf"]
20
+
21
+
22
+ class ExportFormatSvg(TypedDict):
23
+ """SVG export format."""
24
+
25
+ format: Literal["svg"]
26
+
27
+
28
+ class ExportFormatPng(TypedDict):
29
+ """PNG export format."""
30
+
31
+ format: Literal["png"]
32
+ pixelsPerPt: float
33
+
34
+
35
+ ExportFormat = Union[ExportFormatPdf, ExportFormatSvg, ExportFormatPng]
36
+
37
+
38
+ @dataclass
39
+ class BlobInput:
40
+ """Binary blob input with optional metadata."""
41
+
42
+ data: bytes
43
+ metadata: dict[str, Any] | None = None
44
+
45
+
46
+ @dataclass
47
+ class JsonInputDefinition:
48
+ """JSON input definition from manifest."""
49
+
50
+ key: str
51
+ schema: dict[str, Any]
52
+ development_value: dict[str, Any] | None = None
53
+
54
+
55
+ @dataclass
56
+ class BlobInputDefinition:
57
+ """Blob input definition from manifest."""
58
+
59
+ key: str
60
+ development_file: str | None = None
61
+ default_file: str | None = None
@@ -0,0 +1,3 @@
1
+ *.png
2
+ *.pdf
3
+ *.svg
@@ -0,0 +1,159 @@
1
+ """E2E tests for Oicana Python integration."""
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from oicana import BlobInput, CompilationMode, Template
7
+
8
+
9
+ def asset(file: str) -> bytes:
10
+ """Load asset file."""
11
+ path = Path(__file__).parent.parent.parent.parent.parent / "assets" / file
12
+ return path.read_bytes()
13
+
14
+
15
+ def template_file() -> bytes:
16
+ """Load E2E test template."""
17
+ path = (
18
+ Path(__file__).parent.parent.parent.parent.parent
19
+ / "e2e-tests"
20
+ / "template"
21
+ / "oicana-e2e-test-x.y.z.zip"
22
+ )
23
+ return path.read_bytes()
24
+
25
+
26
+ def test_development() -> None:
27
+ """Test compilation in development mode with no inputs."""
28
+ template_bytes = template_file()
29
+ template = Template(template_bytes)
30
+
31
+ try:
32
+ image = template.compile(
33
+ export={"format": "png", "pixelsPerPt": 1.0},
34
+ mode=CompilationMode.DEVELOPMENT,
35
+ )
36
+
37
+ output_dir = Path(__file__).parent / "testOutput"
38
+ output_dir.mkdir(exist_ok=True)
39
+ (output_dir / "development.png").write_bytes(image)
40
+ finally:
41
+ template.cleanup()
42
+
43
+
44
+ def test_production() -> None:
45
+ """Test compilation in production mode with required inputs."""
46
+ template_bytes = template_file()
47
+ template = Template(template_bytes)
48
+
49
+ try:
50
+ blob = asset("inputs/input.txt")
51
+ json_data = asset("inputs/input.json")
52
+
53
+ blob_inputs = {
54
+ "development-blob": BlobInput(
55
+ data=blob,
56
+ metadata={"image_format": "jpeg", "foo": 43, "bar": ["input", "two"]},
57
+ )
58
+ }
59
+ json_inputs = {"development-json": json_data.decode()}
60
+
61
+ image = template.compile(
62
+ json_inputs=json_inputs,
63
+ blob_inputs=blob_inputs,
64
+ export={"format": "png", "pixelsPerPt": 1.0},
65
+ )
66
+
67
+ output_dir = Path(__file__).parent / "testOutput"
68
+ output_dir.mkdir(exist_ok=True)
69
+ (output_dir / "production.png").write_bytes(image)
70
+ finally:
71
+ template.cleanup()
72
+
73
+
74
+ def test_all_inputs() -> None:
75
+ """Test compilation with all possible inputs."""
76
+ template_bytes = template_file()
77
+ template = Template(template_bytes)
78
+
79
+ try:
80
+ blob = asset("inputs/input.txt")
81
+ json_data = asset("inputs/input.json")
82
+
83
+ blob_inputs = {
84
+ "default-blob": BlobInput(
85
+ data=blob,
86
+ metadata={"image_format": "jpeg", "foo": 42, "bar": ["input", "two"]},
87
+ ),
88
+ "development-blob": BlobInput(
89
+ data=blob,
90
+ metadata={"image_format": "jpeg", "foo": 43, "bar": ["input", "two"]},
91
+ ),
92
+ "both-blob": BlobInput(
93
+ data=blob,
94
+ metadata={"image_format": "jpeg", "foo": 44, "bar": ["input", "two"]},
95
+ ),
96
+ }
97
+ json_inputs = {
98
+ "default-json": json_data.decode(),
99
+ "development-json": json_data.decode(),
100
+ "both-json": json_data.decode(),
101
+ }
102
+
103
+ image = template.compile(
104
+ json_inputs=json_inputs,
105
+ blob_inputs=blob_inputs,
106
+ export={"format": "png", "pixelsPerPt": 1.0},
107
+ )
108
+
109
+ output_dir = Path(__file__).parent / "testOutput"
110
+ output_dir.mkdir(exist_ok=True)
111
+ (output_dir / "all-inputs.png").write_bytes(image)
112
+ finally:
113
+ template.cleanup()
114
+
115
+
116
+ def test_explicit_development_mode_allows_compile_with_empty_inputs() -> None:
117
+ """Test that development mode allows compilation with empty inputs."""
118
+ template_bytes = template_file()
119
+ template = Template(template_bytes)
120
+
121
+ try:
122
+ template.compile(
123
+ export={"format": "png", "pixelsPerPt": 1.0},
124
+ mode=CompilationMode.DEVELOPMENT,
125
+ )
126
+ finally:
127
+ template.cleanup()
128
+
129
+
130
+ def test_compile_defaults_to_production_mode() -> None:
131
+ """Test that compile defaults to production mode and fails without inputs."""
132
+ template_bytes = template_file()
133
+ template = Template(template_bytes)
134
+
135
+ try:
136
+ with pytest.raises(Exception, match="No value for the required input"):
137
+ template.compile(export={"format": "png", "pixelsPerPt": 1.0})
138
+ finally:
139
+ template.cleanup()
140
+
141
+
142
+ def test_can_control_compilation_mode_when_registering() -> None:
143
+ """Test that compilation mode can be set during template registration."""
144
+ template_bytes = template_file()
145
+
146
+ with pytest.raises(Exception, match="No value for the required input"):
147
+ Template(template_bytes, mode=CompilationMode.PRODUCTION)
148
+
149
+
150
+ def test_context_manager() -> None:
151
+ """Test that template works as context manager."""
152
+ template_bytes = template_file()
153
+
154
+ with Template(template_bytes) as template:
155
+ image = template.compile(
156
+ export={"format": "png", "pixelsPerPt": 1.0},
157
+ mode=CompilationMode.DEVELOPMENT,
158
+ )
159
+ assert len(image) > 0
@@ -0,0 +1,20 @@
1
+ """Tests for the Template class."""
2
+ import pytest
3
+
4
+ from oicana import CompilationMode, Template
5
+
6
+
7
+ def test_import() -> None:
8
+ """Test that the module can be imported."""
9
+ from oicana import BlobInput, ExportFormat
10
+
11
+ assert Template is not None
12
+ assert CompilationMode is not None
13
+ assert BlobInput is not None
14
+ assert ExportFormat is not None
15
+
16
+
17
+ def test_compilation_mode() -> None:
18
+ """Test CompilationMode enum."""
19
+ assert CompilationMode.PRODUCTION.value == "production"
20
+ assert CompilationMode.DEVELOPMENT.value == "development"