odforge 0.3.0__py3-none-any.whl
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.
- odforge/__init__.py +1 -0
- odforge/benchmark.py +287 -0
- odforge/check.py +416 -0
- odforge/cli.py +1027 -0
- odforge/components.py +270 -0
- odforge/critic.py +1260 -0
- odforge/docfonts.py +104 -0
- odforge/editor_api.py +33 -0
- odforge/editor_launch.py +134 -0
- odforge/editor_routes.py +131 -0
- odforge/extract.py +478 -0
- odforge/feedback.py +86 -0
- odforge/fontembed.py +166 -0
- odforge/ir.py +1181 -0
- odforge/layoutcheck.py +602 -0
- odforge/llm.py +1865 -0
- odforge/localguard.py +42 -0
- odforge/mcp_server.py +552 -0
- odforge/media.py +352 -0
- odforge/odpedit.py +1219 -0
- odforge/package.py +114 -0
- odforge/pagefacts.py +388 -0
- odforge/preview.py +104 -0
- odforge/references.py +153 -0
- odforge/render/__init__.py +40 -0
- odforge/render/odp.py +5687 -0
- odforge/render/ods.py +155 -0
- odforge/render/odt.py +223 -0
- odforge/scene.py +657 -0
- odforge/setup_agents.py +274 -0
- odforge/skills/odforge-design/SKILL.md +298 -0
- odforge/skills/odforge-design/themes/academic.md +52 -0
- odforge/skills/odforge-design/themes/clay.md +53 -0
- odforge/skills/odforge-design/themes/color-system.md +59 -0
- odforge/skills/odforge-design/themes/crimson.md +53 -0
- odforge/skills/odforge-design/themes/dark.md +53 -0
- odforge/skills/odforge-design/themes/forest.md +54 -0
- odforge/skills/odforge-design/themes/gold.md +53 -0
- odforge/skills/odforge-design/themes/minimal.md +53 -0
- odforge/skills/odforge-design/themes/navy.md +56 -0
- odforge/skills/odforge-design/themes/plum.md +53 -0
- odforge/skills/odforge-design/themes/sky.md +53 -0
- odforge/skills/odforge-design/themes/slate.md +53 -0
- odforge/skills/odforge-design/themes/teal.md +53 -0
- odforge/skills/odforge-design/themes/violet.md +56 -0
- odforge/templates.py +250 -0
- odforge/textmetrics.py +616 -0
- odforge/textutil.py +24 -0
- odforge/themes.py +886 -0
- odforge/validate.py +403 -0
- odforge/watch.py +266 -0
- odforge/webapi.py +2617 -0
- odforge/webui/assets/editor-CjpYXM1a.css +1 -0
- odforge/webui/assets/editor-DPToJGio.js +3 -0
- odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
- odforge/webui/assets/main-BLOs7Hnk.js +7 -0
- odforge/webui/assets/main-D21yFVE6.css +1 -0
- odforge/webui/editor.html +14 -0
- odforge/webui/index.html +25 -0
- odforge/xmlsafe.py +46 -0
- odforge/zipguard.py +91 -0
- odforge-0.3.0.dist-info/METADATA +95 -0
- odforge-0.3.0.dist-info/RECORD +66 -0
- odforge-0.3.0.dist-info/WHEEL +4 -0
- odforge-0.3.0.dist-info/entry_points.txt +3 -0
- odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/media.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""Safe raster-image ingestion and pluggable image generation.
|
|
2
|
+
|
|
3
|
+
The presentation model refers to user files through opaque ``asset://`` IDs.
|
|
4
|
+
Only this module may turn those IDs into bytes. Arbitrary local paths are never
|
|
5
|
+
accepted from model output.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import binascii
|
|
12
|
+
import ipaddress
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import socket
|
|
16
|
+
import struct
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import TYPE_CHECKING, Mapping, Protocol
|
|
20
|
+
from urllib.parse import urlparse
|
|
21
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from odforge.ir import ImageSpec
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
MAX_IMAGE_BYTES = 8 * 1024 * 1024
|
|
28
|
+
_ALLOWED_MIME = {
|
|
29
|
+
"image/png": ".png",
|
|
30
|
+
"image/jpeg": ".jpg",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class MediaError(ValueError):
|
|
35
|
+
"""Raised when an image source is unsafe or invalid."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class AssetBlob:
|
|
40
|
+
"""Validated raster bytes ready to embed into an ODF package."""
|
|
41
|
+
|
|
42
|
+
data: bytes
|
|
43
|
+
mime_type: str
|
|
44
|
+
extension: str
|
|
45
|
+
width: int
|
|
46
|
+
height: int
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ImageProvider(Protocol):
|
|
50
|
+
"""Minimal adapter interface for an external image generator."""
|
|
51
|
+
|
|
52
|
+
def generate(self, prompt: str) -> AssetBlob:
|
|
53
|
+
"""Generate one image for ``prompt`` or raise :class:`MediaError`."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
57
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _png_dimensions(data: bytes) -> tuple[int, int] | None:
|
|
62
|
+
if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n":
|
|
63
|
+
return None
|
|
64
|
+
width, height = struct.unpack(">II", data[16:24])
|
|
65
|
+
return (width, height) if width and height else None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
|
|
69
|
+
if len(data) < 4 or data[:2] != b"\xff\xd8":
|
|
70
|
+
return None
|
|
71
|
+
offset = 2
|
|
72
|
+
while offset + 4 <= len(data):
|
|
73
|
+
if data[offset] != 0xFF:
|
|
74
|
+
offset += 1
|
|
75
|
+
continue
|
|
76
|
+
marker = data[offset + 1]
|
|
77
|
+
offset += 2
|
|
78
|
+
if marker in {0xD8, 0xD9} or 0xD0 <= marker <= 0xD7:
|
|
79
|
+
continue
|
|
80
|
+
if offset + 2 > len(data):
|
|
81
|
+
break
|
|
82
|
+
segment_length = struct.unpack(">H", data[offset : offset + 2])[0]
|
|
83
|
+
if segment_length < 2 or offset + segment_length > len(data):
|
|
84
|
+
break
|
|
85
|
+
if marker in {
|
|
86
|
+
0xC0,
|
|
87
|
+
0xC1,
|
|
88
|
+
0xC2,
|
|
89
|
+
0xC3,
|
|
90
|
+
0xC5,
|
|
91
|
+
0xC6,
|
|
92
|
+
0xC7,
|
|
93
|
+
0xC9,
|
|
94
|
+
0xCA,
|
|
95
|
+
0xCB,
|
|
96
|
+
0xCD,
|
|
97
|
+
0xCE,
|
|
98
|
+
0xCF,
|
|
99
|
+
}:
|
|
100
|
+
if segment_length < 7:
|
|
101
|
+
break
|
|
102
|
+
height, width = struct.unpack(
|
|
103
|
+
">HH", data[offset + 3 : offset + 7]
|
|
104
|
+
)
|
|
105
|
+
return (width, height) if width and height else None
|
|
106
|
+
offset += segment_length
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def validate_image_bytes(
|
|
111
|
+
data: bytes, declared_mime: str | None = None
|
|
112
|
+
) -> AssetBlob:
|
|
113
|
+
"""Validate size, signature and dimensions of PNG/JPEG bytes."""
|
|
114
|
+
|
|
115
|
+
if not data:
|
|
116
|
+
raise MediaError("image is empty")
|
|
117
|
+
if len(data) > MAX_IMAGE_BYTES:
|
|
118
|
+
raise MediaError(
|
|
119
|
+
f"image exceeds {MAX_IMAGE_BYTES // (1024 * 1024)} MiB limit"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
dimensions = _png_dimensions(data)
|
|
123
|
+
mime_type = "image/png" if dimensions else ""
|
|
124
|
+
if dimensions is None:
|
|
125
|
+
dimensions = _jpeg_dimensions(data)
|
|
126
|
+
mime_type = "image/jpeg" if dimensions else ""
|
|
127
|
+
if dimensions is None:
|
|
128
|
+
raise MediaError("only valid PNG and JPEG images are supported")
|
|
129
|
+
|
|
130
|
+
normalized_declared = (
|
|
131
|
+
declared_mime.split(";", 1)[0].strip().lower() if declared_mime else ""
|
|
132
|
+
)
|
|
133
|
+
if normalized_declared and normalized_declared not in _ALLOWED_MIME:
|
|
134
|
+
raise MediaError(f"unsupported image content type: {normalized_declared}")
|
|
135
|
+
if normalized_declared and normalized_declared != mime_type:
|
|
136
|
+
raise MediaError(
|
|
137
|
+
f"image signature is {mime_type}, not {normalized_declared}"
|
|
138
|
+
)
|
|
139
|
+
width, height = dimensions
|
|
140
|
+
return AssetBlob(
|
|
141
|
+
data=data,
|
|
142
|
+
mime_type=mime_type,
|
|
143
|
+
extension=_ALLOWED_MIME[mime_type],
|
|
144
|
+
width=width,
|
|
145
|
+
height=height,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def decode_data_uri(value: str) -> AssetBlob:
|
|
150
|
+
"""Decode a PNG/JPEG base64 data URI with strict validation."""
|
|
151
|
+
|
|
152
|
+
try:
|
|
153
|
+
header, encoded = value.split(",", 1)
|
|
154
|
+
except ValueError as exc:
|
|
155
|
+
raise MediaError("invalid image data URI") from exc
|
|
156
|
+
if not header.lower().startswith("data:image/") or ";base64" not in header.lower():
|
|
157
|
+
raise MediaError("image data URI must be base64 encoded")
|
|
158
|
+
mime_type = header[5:].split(";", 1)[0].lower()
|
|
159
|
+
if mime_type not in _ALLOWED_MIME:
|
|
160
|
+
raise MediaError("only PNG and JPEG data URIs are supported")
|
|
161
|
+
try:
|
|
162
|
+
data = base64.b64decode(encoded, validate=True)
|
|
163
|
+
except (binascii.Error, ValueError) as exc:
|
|
164
|
+
raise MediaError("invalid base64 image data") from exc
|
|
165
|
+
return validate_image_bytes(data, mime_type)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def load_local_image(path: Path) -> AssetBlob:
|
|
169
|
+
"""Load an application-selected local PNG/JPEG file."""
|
|
170
|
+
|
|
171
|
+
file_path = Path(path)
|
|
172
|
+
if not file_path.is_file():
|
|
173
|
+
raise MediaError(f"image file does not exist: {file_path}")
|
|
174
|
+
if file_path.stat().st_size > MAX_IMAGE_BYTES:
|
|
175
|
+
raise MediaError(
|
|
176
|
+
f"image exceeds {MAX_IMAGE_BYTES // (1024 * 1024)} MiB limit"
|
|
177
|
+
)
|
|
178
|
+
return validate_image_bytes(file_path.read_bytes())
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _remote_host_allowed(hostname: str) -> bool:
|
|
182
|
+
allowed = {
|
|
183
|
+
item.strip().lower()
|
|
184
|
+
for item in os.getenv("ODFORGE_REMOTE_IMAGE_HOSTS", "").split(",")
|
|
185
|
+
if item.strip()
|
|
186
|
+
}
|
|
187
|
+
return hostname.lower() in allowed
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _assert_public_host(hostname: str) -> None:
|
|
191
|
+
try:
|
|
192
|
+
addresses = socket.getaddrinfo(hostname, 443, type=socket.SOCK_STREAM)
|
|
193
|
+
except socket.gaierror as exc:
|
|
194
|
+
raise MediaError(f"unable to resolve remote image host: {hostname}") from exc
|
|
195
|
+
if not addresses:
|
|
196
|
+
raise MediaError(f"remote image host has no addresses: {hostname}")
|
|
197
|
+
for address in addresses:
|
|
198
|
+
ip = ipaddress.ip_address(address[4][0])
|
|
199
|
+
if not ip.is_global:
|
|
200
|
+
raise MediaError("remote image host resolves to a non-public address")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def fetch_remote_image(url: str) -> AssetBlob:
|
|
204
|
+
"""Fetch an allowlisted public HTTPS image without following redirects."""
|
|
205
|
+
|
|
206
|
+
parsed = urlparse(url)
|
|
207
|
+
if parsed.scheme.lower() != "https" or not parsed.hostname:
|
|
208
|
+
raise MediaError("remote images require an HTTPS URL")
|
|
209
|
+
if not _remote_host_allowed(parsed.hostname):
|
|
210
|
+
raise MediaError(
|
|
211
|
+
"remote image host is not in ODFORGE_REMOTE_IMAGE_HOSTS"
|
|
212
|
+
)
|
|
213
|
+
_assert_public_host(parsed.hostname)
|
|
214
|
+
request = Request(
|
|
215
|
+
url,
|
|
216
|
+
headers={
|
|
217
|
+
"Accept": "image/png,image/jpeg",
|
|
218
|
+
"User-Agent": "ODForge/1.0",
|
|
219
|
+
},
|
|
220
|
+
)
|
|
221
|
+
try:
|
|
222
|
+
with build_opener(_NoRedirect).open(request, timeout=12) as response:
|
|
223
|
+
length = response.headers.get("Content-Length")
|
|
224
|
+
if length and int(length) > MAX_IMAGE_BYTES:
|
|
225
|
+
raise MediaError("remote image exceeds size limit")
|
|
226
|
+
data = response.read(MAX_IMAGE_BYTES + 1)
|
|
227
|
+
content_type = response.headers.get("Content-Type", "")
|
|
228
|
+
except MediaError:
|
|
229
|
+
raise
|
|
230
|
+
except Exception as exc:
|
|
231
|
+
raise MediaError(f"remote image request failed: {exc}") from exc
|
|
232
|
+
return validate_image_bytes(data, content_type)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class HttpImageProvider:
|
|
236
|
+
"""POST prompts to an app-owned endpoint that returns raw PNG/JPEG bytes."""
|
|
237
|
+
|
|
238
|
+
def __init__(self, endpoint: str, api_key: str = "") -> None:
|
|
239
|
+
parsed = urlparse(endpoint)
|
|
240
|
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
241
|
+
raise MediaError("image provider endpoint must be an HTTP(S) URL")
|
|
242
|
+
self.endpoint = endpoint
|
|
243
|
+
self.api_key = api_key
|
|
244
|
+
|
|
245
|
+
def generate(self, prompt: str) -> AssetBlob:
|
|
246
|
+
payload = json.dumps({"prompt": prompt}, ensure_ascii=False).encode("utf-8")
|
|
247
|
+
headers = {
|
|
248
|
+
"Accept": "image/png,image/jpeg",
|
|
249
|
+
"Content-Type": "application/json",
|
|
250
|
+
"User-Agent": "ODForge/1.0",
|
|
251
|
+
}
|
|
252
|
+
if self.api_key:
|
|
253
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
254
|
+
request = Request(
|
|
255
|
+
self.endpoint, data=payload, headers=headers, method="POST"
|
|
256
|
+
)
|
|
257
|
+
try:
|
|
258
|
+
with build_opener(_NoRedirect).open(request, timeout=60) as response:
|
|
259
|
+
length = response.headers.get("Content-Length")
|
|
260
|
+
if length and int(length) > MAX_IMAGE_BYTES:
|
|
261
|
+
raise MediaError("generated image exceeds size limit")
|
|
262
|
+
data = response.read(MAX_IMAGE_BYTES + 1)
|
|
263
|
+
content_type = response.headers.get("Content-Type", "")
|
|
264
|
+
except MediaError:
|
|
265
|
+
raise
|
|
266
|
+
except Exception as exc:
|
|
267
|
+
raise MediaError(f"image provider request failed: {exc}") from exc
|
|
268
|
+
return validate_image_bytes(data, content_type)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def configured_image_provider() -> ImageProvider | None:
|
|
272
|
+
"""Return the configured provider, or ``None`` when generation is off."""
|
|
273
|
+
|
|
274
|
+
backend = os.getenv("ODFORGE_IMAGE_BACKEND", "off").strip().lower()
|
|
275
|
+
if backend in {"", "off", "none"}:
|
|
276
|
+
return None
|
|
277
|
+
if backend != "http":
|
|
278
|
+
raise MediaError(
|
|
279
|
+
"ODFORGE_IMAGE_BACKEND must be 'off' or 'http'"
|
|
280
|
+
)
|
|
281
|
+
endpoint = os.getenv("ODFORGE_IMAGE_ENDPOINT", "").strip()
|
|
282
|
+
if not endpoint:
|
|
283
|
+
raise MediaError(
|
|
284
|
+
"ODFORGE_IMAGE_ENDPOINT is required for the http image backend"
|
|
285
|
+
)
|
|
286
|
+
return HttpImageProvider(
|
|
287
|
+
endpoint=endpoint,
|
|
288
|
+
api_key=os.getenv("ODFORGE_IMAGE_API_KEY", ""),
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
AssetInput = AssetBlob | bytes | Path
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def normalize_assets(
|
|
296
|
+
assets: Mapping[str, AssetInput] | None,
|
|
297
|
+
) -> dict[str, AssetBlob]:
|
|
298
|
+
"""Validate an app-owned ``id -> image`` mapping."""
|
|
299
|
+
|
|
300
|
+
normalized: dict[str, AssetBlob] = {}
|
|
301
|
+
for asset_id, value in (assets or {}).items():
|
|
302
|
+
if not asset_id or not all(
|
|
303
|
+
char.isalnum() or char in "_-" for char in asset_id
|
|
304
|
+
):
|
|
305
|
+
raise MediaError(f"unsafe asset id: {asset_id!r}")
|
|
306
|
+
if isinstance(value, AssetBlob):
|
|
307
|
+
blob = value
|
|
308
|
+
elif isinstance(value, bytes):
|
|
309
|
+
blob = validate_image_bytes(value)
|
|
310
|
+
else:
|
|
311
|
+
blob = load_local_image(Path(value))
|
|
312
|
+
normalized[asset_id] = blob
|
|
313
|
+
return normalized
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def resolve_image(
|
|
317
|
+
image: ImageSpec,
|
|
318
|
+
assets: Mapping[str, AssetBlob],
|
|
319
|
+
provider: ImageProvider | None = None,
|
|
320
|
+
) -> AssetBlob | None:
|
|
321
|
+
"""Resolve an image spec. Missing/unavailable sources return ``None``.
|
|
322
|
+
|
|
323
|
+
Invalid bytes still raise ``MediaError``; a missing asset or disabled
|
|
324
|
+
provider becomes a visible placeholder in the renderer instead of a crash.
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
if image.src.startswith("asset://"):
|
|
328
|
+
return assets.get(image.src.removeprefix("asset://"))
|
|
329
|
+
if image.src.startswith("data:"):
|
|
330
|
+
return decode_data_uri(image.src)
|
|
331
|
+
if image.src.startswith("https://"):
|
|
332
|
+
return fetch_remote_image(image.src)
|
|
333
|
+
if image.prompt and provider is not None:
|
|
334
|
+
return provider.generate(image.prompt)
|
|
335
|
+
return None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
__all__ = [
|
|
339
|
+
"MAX_IMAGE_BYTES",
|
|
340
|
+
"AssetBlob",
|
|
341
|
+
"AssetInput",
|
|
342
|
+
"HttpImageProvider",
|
|
343
|
+
"ImageProvider",
|
|
344
|
+
"MediaError",
|
|
345
|
+
"configured_image_provider",
|
|
346
|
+
"decode_data_uri",
|
|
347
|
+
"fetch_remote_image",
|
|
348
|
+
"load_local_image",
|
|
349
|
+
"normalize_assets",
|
|
350
|
+
"resolve_image",
|
|
351
|
+
"validate_image_bytes",
|
|
352
|
+
]
|