@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.8
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.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
- package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
- package/bundled-assets/skill/LICENSE +21 -0
- package/bundled-assets/skill/README.md +61 -0
- package/bundled-assets/skill/SKILL.md +185 -0
- package/bundled-assets/skill/references/art-directions.md +99 -0
- package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
- package/bundled-assets/skill/references/design-baseline.txt +1 -0
- package/bundled-assets/skill/references/prompt-compiler.md +99 -0
- package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
- package/bundled-assets/skill/references/staged-pptx.md +71 -0
- package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
- package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
- package/bundled-assets/skill/scripts/brand_ref.py +776 -0
- package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
- package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
- package/bundled-assets/skill/scripts/export_images.py +280 -0
- package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
- package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
- package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
- package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
- package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
- package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
- package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
- package/bundled-assets/skill/scripts/render_gradient.py +258 -0
- package/bundled-assets/skill/scripts/slide_brand.py +111 -0
- package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
- package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
- package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
- package/bundled-assets/skill/vendor/README.md +4 -0
- package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
- package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
- package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +11423 -0
- package/lib/index.js +2638 -0
- package/package.json +140 -4
|
@@ -0,0 +1,1029 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
import argparse
|
|
3
|
+
import html
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
import zipfile
|
|
11
|
+
from copy import deepcopy
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from native_tables import normalize_table, table_xml, cell_text_box
|
|
15
|
+
|
|
16
|
+
from path_geometry import custom_path_geometry_xml, draw_styled_path, preview_path_points, validate_shape
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
EMU_PER_INCH = 914400
|
|
20
|
+
REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
|
|
21
|
+
ASPECT_16_9 = 16 / 9
|
|
22
|
+
ASPECT_TOLERANCE = 0.03
|
|
23
|
+
DEFAULT_TEXT_FIT_SAFETY = 0.9
|
|
24
|
+
DEFAULT_TEXT_LINE_HEIGHT = 1.22
|
|
25
|
+
DEFAULT_MIN_FONT_SIZE = 4.0
|
|
26
|
+
TEXT_ALIGNMENTS = {
|
|
27
|
+
"left": ("l", "left"),
|
|
28
|
+
"center": ("ctr", "center"),
|
|
29
|
+
"right": ("r", "right"),
|
|
30
|
+
"l": ("l", "left"),
|
|
31
|
+
"ctr": ("ctr", "center"),
|
|
32
|
+
"r": ("r", "right"),
|
|
33
|
+
}
|
|
34
|
+
TEXT_VERTICAL_ALIGNMENTS = {
|
|
35
|
+
"top": ("t", "top"),
|
|
36
|
+
"middle": ("ctr", "middle"),
|
|
37
|
+
"center": ("ctr", "middle"),
|
|
38
|
+
"bottom": ("b", "bottom"),
|
|
39
|
+
"t": ("t", "top"),
|
|
40
|
+
"ctr": ("ctr", "middle"),
|
|
41
|
+
"b": ("b", "bottom"),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def emu(value):
|
|
46
|
+
return int(round(float(value) * EMU_PER_INCH))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def hex_color(value, default="000000"):
|
|
50
|
+
if not value:
|
|
51
|
+
return default
|
|
52
|
+
return str(value).strip().lstrip("#").upper()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def content_type_for(path):
|
|
56
|
+
suffix = Path(path).suffix.lower()
|
|
57
|
+
if suffix == ".png":
|
|
58
|
+
return "image/png"
|
|
59
|
+
if suffix in (".jpg", ".jpeg"):
|
|
60
|
+
return "image/jpeg"
|
|
61
|
+
if suffix == ".gif":
|
|
62
|
+
return "image/gif"
|
|
63
|
+
if suffix == ".svg":
|
|
64
|
+
return "image/svg+xml"
|
|
65
|
+
raise ValueError(f"Unsupported image type: {path}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def image_ext(path):
|
|
69
|
+
suffix = Path(path).suffix.lower()
|
|
70
|
+
return ".jpg" if suffix == ".jpeg" else suffix
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def xml_text(value):
|
|
74
|
+
return html.escape(str(value), quote=True)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def text_alignment(value="left"):
|
|
78
|
+
key = str(value or "left").strip().lower()
|
|
79
|
+
if key not in TEXT_ALIGNMENTS:
|
|
80
|
+
raise ValueError(f"Unsupported text align value: {value}")
|
|
81
|
+
return TEXT_ALIGNMENTS[key]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def text_vertical_alignment(value="top"):
|
|
85
|
+
key = str(value or "top").strip().lower()
|
|
86
|
+
if key not in TEXT_VERTICAL_ALIGNMENTS:
|
|
87
|
+
raise ValueError(f"Unsupported text valign value: {value}")
|
|
88
|
+
return TEXT_VERTICAL_ALIGNMENTS[key]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def source_size_px(manifest):
|
|
92
|
+
source = manifest.get("source", {})
|
|
93
|
+
width = source.get("width_px")
|
|
94
|
+
height = source.get("height_px")
|
|
95
|
+
if width and height:
|
|
96
|
+
return float(width), float(height)
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def slide_size(manifest):
|
|
101
|
+
slide = manifest.get("slide", {})
|
|
102
|
+
return float(slide.get("width", 13.333)), float(slide.get("height", 7.5))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def fit_content_box(source_width, source_height, slide_width, slide_height):
|
|
106
|
+
source_aspect = source_width / source_height
|
|
107
|
+
slide_aspect = slide_width / slide_height
|
|
108
|
+
if source_aspect >= slide_aspect:
|
|
109
|
+
width = slide_width
|
|
110
|
+
height = width / source_aspect
|
|
111
|
+
left = 0
|
|
112
|
+
top = (slide_height - height) / 2
|
|
113
|
+
else:
|
|
114
|
+
height = slide_height
|
|
115
|
+
width = height * source_aspect
|
|
116
|
+
left = (slide_width - width) / 2
|
|
117
|
+
top = 0
|
|
118
|
+
return {"left": left, "top": top, "width": width, "height": height}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def content_box_for_manifest(manifest):
|
|
122
|
+
content_box = manifest.get("content_box")
|
|
123
|
+
if content_box:
|
|
124
|
+
return {
|
|
125
|
+
"left": float(content_box.get("left", 0)),
|
|
126
|
+
"top": float(content_box.get("top", 0)),
|
|
127
|
+
"width": float(content_box.get("width", 1)),
|
|
128
|
+
"height": float(content_box.get("height", 1)),
|
|
129
|
+
}
|
|
130
|
+
source_size = source_size_px(manifest)
|
|
131
|
+
slide_width, slide_height = slide_size(manifest)
|
|
132
|
+
if not source_size:
|
|
133
|
+
return {"left": 0, "top": 0, "width": slide_width, "height": slide_height}
|
|
134
|
+
source_width, source_height = source_size
|
|
135
|
+
return fit_content_box(source_width, source_height, slide_width, slide_height)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def px_to_inches(manifest, x, y, width, height):
|
|
139
|
+
source_size = source_size_px(manifest)
|
|
140
|
+
if not source_size:
|
|
141
|
+
raise ValueError("Manifest uses pixel coordinates but lacks source.width_px/source.height_px")
|
|
142
|
+
source_width, source_height = source_size
|
|
143
|
+
content_box = content_box_for_manifest(manifest)
|
|
144
|
+
return {
|
|
145
|
+
"left": content_box["left"] + float(x) / source_width * content_box["width"],
|
|
146
|
+
"top": content_box["top"] + float(y) / source_height * content_box["height"],
|
|
147
|
+
"width": float(width) / source_width * content_box["width"],
|
|
148
|
+
"height": float(height) / source_height * content_box["height"],
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def normalize_position_item(manifest, item):
|
|
153
|
+
item = dict(item)
|
|
154
|
+
if "polygon_px" in item:
|
|
155
|
+
points = [(float(point[0]), float(point[1])) for point in item["polygon_px"]]
|
|
156
|
+
if points and "box_px" not in item:
|
|
157
|
+
xs = [point[0] for point in points]
|
|
158
|
+
ys = [point[1] for point in points]
|
|
159
|
+
item["box_px"] = [min(xs), min(ys), max(xs) - min(xs), max(ys) - min(ys)]
|
|
160
|
+
item["polygon"] = [
|
|
161
|
+
[px_to_inches(manifest, point[0], point[1], 0, 0)["left"], px_to_inches(manifest, point[0], point[1], 0, 0)["top"]]
|
|
162
|
+
for point in points
|
|
163
|
+
]
|
|
164
|
+
if "box_px" in item:
|
|
165
|
+
x, y, width, height = item["box_px"]
|
|
166
|
+
item.update(px_to_inches(manifest, x, y, width, height))
|
|
167
|
+
if "points_px" in item:
|
|
168
|
+
x1, y1, x2, y2 = item["points_px"]
|
|
169
|
+
left = min(float(x1), float(x2))
|
|
170
|
+
top = min(float(y1), float(y2))
|
|
171
|
+
width = abs(float(x2) - float(x1))
|
|
172
|
+
height = abs(float(y2) - float(y1))
|
|
173
|
+
item.update(px_to_inches(manifest, left, top, width, height))
|
|
174
|
+
start = px_to_inches(manifest, x1, y1, 0, 0)
|
|
175
|
+
end = px_to_inches(manifest, x2, y2, 0, 0)
|
|
176
|
+
item["points"] = [start["left"], start["top"], end["left"], end["top"]]
|
|
177
|
+
if float(x2) < float(x1):
|
|
178
|
+
item["flip_h"] = True
|
|
179
|
+
if float(y2) < float(y1):
|
|
180
|
+
item["flip_v"] = True
|
|
181
|
+
if item.get("source_corner_radius_px") is not None and "radius" not in item:
|
|
182
|
+
radius = float(item.get("source_corner_radius_px") or 0)
|
|
183
|
+
item["radius"] = px_to_inches(manifest, 0, 0, radius, radius)["width"]
|
|
184
|
+
return item
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def iter_text_lines(item):
|
|
188
|
+
if item.get("paragraphs"):
|
|
189
|
+
lines = []
|
|
190
|
+
for paragraph in item["paragraphs"]:
|
|
191
|
+
if isinstance(paragraph, str):
|
|
192
|
+
lines.append(paragraph)
|
|
193
|
+
else:
|
|
194
|
+
runs = paragraph.get("runs")
|
|
195
|
+
if runs:
|
|
196
|
+
lines.append("".join(str(run.get("text", "")) for run in runs))
|
|
197
|
+
else:
|
|
198
|
+
lines.append(str(paragraph.get("text", "")))
|
|
199
|
+
return lines or [""]
|
|
200
|
+
if item.get("runs"):
|
|
201
|
+
return ["".join(str(run.get("text", "")) for run in item["runs"])]
|
|
202
|
+
return str(item.get("text", "")).splitlines() or [""]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def text_width_units(text):
|
|
206
|
+
units = 0.0
|
|
207
|
+
for char in str(text):
|
|
208
|
+
codepoint = ord(char)
|
|
209
|
+
if char.isspace():
|
|
210
|
+
units += 0.32
|
|
211
|
+
elif codepoint <= 0x7F:
|
|
212
|
+
units += 0.55
|
|
213
|
+
elif 0xFF00 <= codepoint <= 0xFFEF:
|
|
214
|
+
units += 1.0
|
|
215
|
+
elif 0x4E00 <= codepoint <= 0x9FFF:
|
|
216
|
+
units += 1.0
|
|
217
|
+
else:
|
|
218
|
+
units += 0.85
|
|
219
|
+
return max(units, 1.0)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def longest_unbreakable_units(text):
|
|
223
|
+
tokens = [token for token in re.split(r"\s+", str(text)) if token]
|
|
224
|
+
if not tokens:
|
|
225
|
+
return text_width_units(text)
|
|
226
|
+
return max(text_width_units(token) for token in tokens)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def is_measured_text(item):
|
|
230
|
+
"""True when the author marked this box as sized from `page hints` measurement."""
|
|
231
|
+
return str(item.get("font_size_source", "")).strip().lower() in {"measured", "hints"}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def fitted_font_size(item, manifest):
|
|
235
|
+
if item.get("fit_text") is False or manifest.get("fit_text") is False:
|
|
236
|
+
return None
|
|
237
|
+
if "width" not in item or "height" not in item:
|
|
238
|
+
return None
|
|
239
|
+
lines = iter_text_lines(item)
|
|
240
|
+
requested = float(item.get("font_size", 18))
|
|
241
|
+
width_pt = max(1.0, float(item.get("width", 1)) * 72)
|
|
242
|
+
height_pt = max(1.0, float(item.get("height", 0.4)) * 72)
|
|
243
|
+
if is_measured_text(item):
|
|
244
|
+
# Box and font size were both measured from source ink; the safety
|
|
245
|
+
# discount exists to absorb estimation error in hand-written boxes
|
|
246
|
+
# and would systematically shrink correct text here. Clamp only at
|
|
247
|
+
# the geometric limit.
|
|
248
|
+
safety = 1.0
|
|
249
|
+
else:
|
|
250
|
+
safety = float(item.get("text_fit_safety", manifest.get("text_fit_safety", DEFAULT_TEXT_FIT_SAFETY)))
|
|
251
|
+
line_height = float(item.get("line_height", manifest.get("text_line_height", DEFAULT_TEXT_LINE_HEIGHT)))
|
|
252
|
+
wrap_enabled = item.get("wrap") not in (None, "", "none")
|
|
253
|
+
if wrap_enabled:
|
|
254
|
+
line_count = sum(max(1, math.ceil(text_width_units(line) * requested / width_pt)) for line in lines)
|
|
255
|
+
width_limit = width_pt / max(longest_unbreakable_units(line) for line in lines)
|
|
256
|
+
else:
|
|
257
|
+
line_count = max(1, len(lines))
|
|
258
|
+
width_limit = width_pt / max(text_width_units(line) for line in lines)
|
|
259
|
+
height_limit = height_pt / (line_count * max(line_height, 1.0))
|
|
260
|
+
max_font_size = min(width_limit, height_limit) * safety
|
|
261
|
+
explicit_max = item.get("max_font_size")
|
|
262
|
+
if explicit_max not in (None, ""):
|
|
263
|
+
max_font_size = min(max_font_size, float(explicit_max))
|
|
264
|
+
min_font_size = float(item.get("min_font_size", manifest.get("min_font_size", DEFAULT_MIN_FONT_SIZE)))
|
|
265
|
+
return max(min_font_size, max_font_size)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def scale_run_font_sizes(item, ratio):
|
|
269
|
+
def scale_run(run):
|
|
270
|
+
if run.get("font_size") not in (None, ""):
|
|
271
|
+
run["font_size"] = round(float(run["font_size"]) * ratio, 1)
|
|
272
|
+
|
|
273
|
+
for run in item.get("runs", []):
|
|
274
|
+
scale_run(run)
|
|
275
|
+
for paragraph in item.get("paragraphs", []):
|
|
276
|
+
if isinstance(paragraph, dict):
|
|
277
|
+
for run in paragraph.get("runs", []):
|
|
278
|
+
scale_run(run)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def fit_text_item(item, manifest):
|
|
282
|
+
fitted = fitted_font_size(item, manifest)
|
|
283
|
+
if fitted is None:
|
|
284
|
+
return item
|
|
285
|
+
requested = float(item.get("font_size", fitted))
|
|
286
|
+
effective = min(requested, fitted)
|
|
287
|
+
if effective < requested:
|
|
288
|
+
item["_requested_font_size"] = requested
|
|
289
|
+
item["font_size"] = round(effective, 1)
|
|
290
|
+
scale_run_font_sizes(item, effective / requested)
|
|
291
|
+
elif "font_size" not in item:
|
|
292
|
+
item["font_size"] = round(effective, 1)
|
|
293
|
+
return item
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def normalize_manifest(manifest):
|
|
297
|
+
"""Return a manifest copy with pixel authoring fields resolved to inches."""
|
|
298
|
+
normalized = deepcopy(manifest)
|
|
299
|
+
line_ids = set()
|
|
300
|
+
for item in normalized.get("shapes", []):
|
|
301
|
+
validate_shape(item)
|
|
302
|
+
line_id = item.get("semantic_line_id")
|
|
303
|
+
if line_id is not None:
|
|
304
|
+
if not isinstance(line_id, str) or not line_id.strip():
|
|
305
|
+
raise ValueError("semantic_line_id must be a non-empty string")
|
|
306
|
+
if line_id in line_ids:
|
|
307
|
+
raise ValueError(f"Logical line {line_id!r} is split across multiple shapes")
|
|
308
|
+
line_ids.add(line_id)
|
|
309
|
+
normalized["text_boxes"] = [
|
|
310
|
+
fit_text_item(normalize_position_item(normalized, item), normalized) for item in normalized.get("text_boxes", [])
|
|
311
|
+
]
|
|
312
|
+
for key in ("images", "shapes"):
|
|
313
|
+
normalized[key] = [normalize_position_item(normalized, item) for item in normalized.get(key, [])]
|
|
314
|
+
normalized["tables"] = [normalize_table(item, normalized, normalize_position_item, fit_text_item, text_alignment, text_vertical_alignment) for item in normalized.get("tables", [])]
|
|
315
|
+
return normalized
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def preview_color(value):
|
|
319
|
+
if not value or value == "none":
|
|
320
|
+
return value
|
|
321
|
+
value = str(value).strip()
|
|
322
|
+
if value.startswith("#"):
|
|
323
|
+
return value
|
|
324
|
+
if len(value) == 6 and all(ch in "0123456789abcdefABCDEF" for ch in value):
|
|
325
|
+
return f"#{value}"
|
|
326
|
+
return value
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def shape_fill(fill):
|
|
330
|
+
if not fill or fill == "none":
|
|
331
|
+
return '<a:noFill/>'
|
|
332
|
+
return f'<a:solidFill><a:srgbClr val="{hex_color(fill)}"/></a:solidFill>'
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def shape_line_xml(stroke, width, dash=None, start_arrow=None, end_arrow=None):
|
|
336
|
+
if not stroke or stroke == "none":
|
|
337
|
+
return '<a:ln><a:noFill/></a:ln>'
|
|
338
|
+
dash_xml = f'<a:prstDash val="{xml_text(dash)}"/>' if dash else ""
|
|
339
|
+
return (
|
|
340
|
+
f'<a:ln w="{int(float(width or 1) * 12700)}">'
|
|
341
|
+
f'<a:solidFill><a:srgbClr val="{hex_color(stroke)}"/></a:solidFill>'
|
|
342
|
+
f"{dash_xml}"
|
|
343
|
+
+ (f'<a:headEnd type="{xml_text(start_arrow)}"/>' if start_arrow else "")
|
|
344
|
+
+ (f'<a:tailEnd type="{xml_text(end_arrow)}"/>' if end_arrow else "")
|
|
345
|
+
+ "</a:ln>"
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def slide_background_xml(slide):
|
|
350
|
+
background = slide.get("background")
|
|
351
|
+
if not background:
|
|
352
|
+
return ""
|
|
353
|
+
return (
|
|
354
|
+
"<p:bg><p:bgPr>"
|
|
355
|
+
f'<a:solidFill><a:srgbClr val="{hex_color(background, "FFFFFF")}"/></a:solidFill>'
|
|
356
|
+
"<a:effectLst/></p:bgPr></p:bg>"
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def text_box_xml(idx, item):
|
|
361
|
+
left = emu(item.get("left", 0))
|
|
362
|
+
top = emu(item.get("top", 0))
|
|
363
|
+
width = emu(item.get("width", 1))
|
|
364
|
+
height = emu(item.get("height", 0.4))
|
|
365
|
+
rotation = item.get("rotation")
|
|
366
|
+
rotation_attr = f' rot="{int(float(rotation) * 60000)}"' if rotation not in (None, "") else ""
|
|
367
|
+
font_size = int(float(item.get("font_size", 18)) * 100)
|
|
368
|
+
font = xml_text(item.get("font", "PingFang SC"))
|
|
369
|
+
align = text_alignment(item.get("align", "left"))[0]
|
|
370
|
+
anchor = text_vertical_alignment(item.get("valign", "top"))[0]
|
|
371
|
+
wrap = item.get("wrap", "none")
|
|
372
|
+
autofit = item.get("autofit", "none")
|
|
373
|
+
autofit_xml = "<a:spAutoFit/>" if autofit == "shape" else "<a:noAutofit/>"
|
|
374
|
+
paragraphs = item.get("paragraphs")
|
|
375
|
+
runs = item.get("runs")
|
|
376
|
+
|
|
377
|
+
def run_xml(run):
|
|
378
|
+
run_font_size = int(float(run.get("font_size", item.get("font_size", 18))) * 100)
|
|
379
|
+
run_font = xml_text(run.get("font", item.get("font", "PingFang SC")))
|
|
380
|
+
run_color = hex_color(run.get("color", item.get("color", "#111111")))
|
|
381
|
+
run_bold = ' b="1"' if run.get("bold", item.get("bold")) else ""
|
|
382
|
+
run_italic = ' i="1"' if run.get("italic", item.get("italic")) else ""
|
|
383
|
+
run_baseline = run.get("baseline")
|
|
384
|
+
run_baseline_attr = f' baseline="{int(float(run_baseline))}"' if run_baseline not in (None, "") else ""
|
|
385
|
+
run_text = xml_text(run.get("text", ""))
|
|
386
|
+
return (
|
|
387
|
+
f'<a:r><a:rPr lang="zh-CN" sz="{run_font_size}"{run_bold}{run_italic}{run_baseline_attr}>'
|
|
388
|
+
f'<a:solidFill><a:srgbClr val="{run_color}"/></a:solidFill>'
|
|
389
|
+
f'<a:latin typeface="{run_font}"/><a:ea typeface="{run_font}"/><a:cs typeface="{run_font}"/>'
|
|
390
|
+
f'</a:rPr><a:t>{run_text}</a:t></a:r>'
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
def paragraph_xml(paragraph):
|
|
394
|
+
if isinstance(paragraph, str):
|
|
395
|
+
paragraph_runs = [{"text": paragraph}]
|
|
396
|
+
else:
|
|
397
|
+
paragraph_runs = paragraph.get("runs", [{"text": paragraph.get("text", "")}])
|
|
398
|
+
return (
|
|
399
|
+
f'<a:p><a:pPr algn="{align}"/>'
|
|
400
|
+
+ "".join(run_xml(run) for run in paragraph_runs)
|
|
401
|
+
+ f'<a:endParaRPr lang="zh-CN" sz="{font_size}"/></a:p>'
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
if paragraphs:
|
|
405
|
+
text_body = "".join(paragraph_xml(paragraph) for paragraph in paragraphs)
|
|
406
|
+
elif runs:
|
|
407
|
+
text_body = paragraph_xml({"runs": runs})
|
|
408
|
+
else:
|
|
409
|
+
text_body = "".join(paragraph_xml(part) for part in str(item.get("text", "")).split("\n"))
|
|
410
|
+
return f"""
|
|
411
|
+
<p:sp>
|
|
412
|
+
<p:nvSpPr><p:cNvPr id="{idx}" name="TextBox {idx}"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>
|
|
413
|
+
<p:spPr><a:xfrm{rotation_attr}><a:off x="{left}" y="{top}"/><a:ext cx="{width}" cy="{height}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr>
|
|
414
|
+
<p:txBody>
|
|
415
|
+
<a:bodyPr wrap="{xml_text(wrap)}" anchor="{anchor}" lIns="0" tIns="0" rIns="0" bIns="0">{autofit_xml}</a:bodyPr><a:lstStyle/>
|
|
416
|
+
{text_body}
|
|
417
|
+
</p:txBody>
|
|
418
|
+
</p:sp>"""
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def image_xml(idx, rel_id, item):
|
|
422
|
+
left = emu(item.get("left", 0))
|
|
423
|
+
top = emu(item.get("top", 0))
|
|
424
|
+
width = emu(item.get("width", 1))
|
|
425
|
+
height = emu(item.get("height", 1))
|
|
426
|
+
name = xml_text(item.get("alt") or Path(item.get("path", "")).stem or f"Image {idx}")
|
|
427
|
+
return f"""
|
|
428
|
+
<p:pic>
|
|
429
|
+
<p:nvPicPr><p:cNvPr id="{idx}" name="{name}"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>
|
|
430
|
+
<p:blipFill><a:blip r:embed="{rel_id}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>
|
|
431
|
+
<p:spPr><a:xfrm><a:off x="{left}" y="{top}"/><a:ext cx="{width}" cy="{height}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>
|
|
432
|
+
</p:pic>"""
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def shape_xml(idx, item):
|
|
436
|
+
validate_shape(item)
|
|
437
|
+
kind = item.get("type", "rect")
|
|
438
|
+
left = emu(item.get("left", 0))
|
|
439
|
+
top = emu(item.get("top", 0))
|
|
440
|
+
width = emu(item.get("width", 1))
|
|
441
|
+
height = emu(item.get("height", 1))
|
|
442
|
+
stroke_width = item.get("stroke_width", 1)
|
|
443
|
+
flip_h = ' flipH="1"' if item.get("flip_h") else ""
|
|
444
|
+
flip_v = ' flipV="1"' if item.get("flip_v") else ""
|
|
445
|
+
fill = shape_fill(item.get("fill"))
|
|
446
|
+
line = shape_line_xml(item.get("stroke", "#000000"), stroke_width, item.get("dash"), item.get("start_arrow"), item.get("end_arrow"))
|
|
447
|
+
preset = item.get("preset")
|
|
448
|
+
if kind == "path":
|
|
449
|
+
geometry = custom_path_geometry_xml(item)
|
|
450
|
+
elif item.get("polygon_px"):
|
|
451
|
+
geometry = custom_polygon_geometry_xml(item)
|
|
452
|
+
else:
|
|
453
|
+
if not preset:
|
|
454
|
+
preset = "line" if kind == "line" else "ellipse" if kind == "ellipse" else "roundRect" if kind == "roundRect" else "rect"
|
|
455
|
+
geometry = preset_geometry_xml(preset, item)
|
|
456
|
+
return f"""
|
|
457
|
+
<p:sp>
|
|
458
|
+
<p:nvSpPr><p:cNvPr id="{idx}" name="{xml_text(kind.title())} {idx}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
|
|
459
|
+
<p:spPr><a:xfrm{flip_h}{flip_v}><a:off x="{left}" y="{top}"/><a:ext cx="{width}" cy="{height}"/></a:xfrm>{geometry}{fill}{line}</p:spPr>
|
|
460
|
+
<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>
|
|
461
|
+
</p:sp>"""
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def custom_polygon_geometry_xml(item):
|
|
465
|
+
points = [(float(point[0]), float(point[1])) for point in item.get("polygon_px", [])]
|
|
466
|
+
if len(points) < 3:
|
|
467
|
+
return '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
|
|
468
|
+
box = item.get("box_px")
|
|
469
|
+
if box and len(box) == 4:
|
|
470
|
+
left, top, width, height = [float(value) for value in box]
|
|
471
|
+
else:
|
|
472
|
+
xs = [point[0] for point in points]
|
|
473
|
+
ys = [point[1] for point in points]
|
|
474
|
+
left, top = min(xs), min(ys)
|
|
475
|
+
width, height = max(xs) - left, max(ys) - top
|
|
476
|
+
width = max(width, 1.0)
|
|
477
|
+
height = max(height, 1.0)
|
|
478
|
+
|
|
479
|
+
def rel_coord(point):
|
|
480
|
+
x, y = point
|
|
481
|
+
return int(round((x - left) / width * 21600)), int(round((y - top) / height * 21600))
|
|
482
|
+
|
|
483
|
+
first_x, first_y = rel_coord(points[0])
|
|
484
|
+
segments = [f'<a:moveTo><a:pt x="{first_x}" y="{first_y}"/></a:moveTo>']
|
|
485
|
+
for point in points[1:]:
|
|
486
|
+
x, y = rel_coord(point)
|
|
487
|
+
segments.append(f'<a:lnTo><a:pt x="{x}" y="{y}"/></a:lnTo>')
|
|
488
|
+
segments.append("<a:close/>")
|
|
489
|
+
return (
|
|
490
|
+
'<a:custGeom><a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>'
|
|
491
|
+
'<a:rect l="l" t="t" r="r" b="b"/>'
|
|
492
|
+
'<a:pathLst><a:path w="21600" h="21600">'
|
|
493
|
+
+ "".join(segments)
|
|
494
|
+
+ "</a:path></a:pathLst></a:custGeom>"
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def round_rect_adjustment(item):
|
|
499
|
+
box_px = item.get("box_px")
|
|
500
|
+
if item.get("source_corner_radius_px") is not None and box_px and len(box_px) == 4:
|
|
501
|
+
radius = float(item.get("source_corner_radius_px") or 0)
|
|
502
|
+
min_dim = max(1.0, min(float(box_px[2]), float(box_px[3])))
|
|
503
|
+
elif item.get("radius") is not None:
|
|
504
|
+
radius = float(item.get("radius") or 0)
|
|
505
|
+
min_dim = max(0.01, min(float(item.get("width", 1)), float(item.get("height", 1))))
|
|
506
|
+
else:
|
|
507
|
+
return None
|
|
508
|
+
return max(0, min(50000, int(round(radius / min_dim * 100000))))
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def preset_geometry_xml(preset, item):
|
|
512
|
+
if preset != "roundRect":
|
|
513
|
+
return f'<a:prstGeom prst="{preset}"><a:avLst/></a:prstGeom>'
|
|
514
|
+
adjustment = round_rect_adjustment(item)
|
|
515
|
+
if adjustment is None:
|
|
516
|
+
return '<a:prstGeom prst="roundRect"><a:avLst/></a:prstGeom>'
|
|
517
|
+
return (
|
|
518
|
+
'<a:prstGeom prst="roundRect"><a:avLst>'
|
|
519
|
+
f'<a:gd name="adj" fmla="val {adjustment}"/>'
|
|
520
|
+
'</a:avLst></a:prstGeom>'
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def slide_xml(manifest):
|
|
525
|
+
slide = manifest.get("slide", {})
|
|
526
|
+
next_id = 2
|
|
527
|
+
parts = []
|
|
528
|
+
layered = []
|
|
529
|
+
for index, item in enumerate(manifest.get("shapes", [])):
|
|
530
|
+
layered.append((float(item.get("z_index", 100)), index, "shape", item, None))
|
|
531
|
+
for rel_index, item in enumerate(manifest.get("images", []), start=1):
|
|
532
|
+
layered.append((float(item.get("z_index", 200)), rel_index, "image", item, f"rId{rel_index + 1}"))
|
|
533
|
+
for index, item in enumerate(manifest.get("tables", [])):
|
|
534
|
+
layered.append((float(item.get("z_index", 250)), index, "table", item, None))
|
|
535
|
+
for index, item in enumerate(manifest.get("text_boxes", [])):
|
|
536
|
+
layered.append((float(item.get("z_index", 300)), index, "text", item, None))
|
|
537
|
+
|
|
538
|
+
for _z_index, _order, kind, item, rel_id in sorted(layered, key=lambda entry: (entry[0], entry[1])):
|
|
539
|
+
if kind == "shape":
|
|
540
|
+
parts.append(shape_xml(next_id, item))
|
|
541
|
+
elif kind == "image":
|
|
542
|
+
parts.append(image_xml(next_id, rel_id, item))
|
|
543
|
+
elif kind == "table":
|
|
544
|
+
parts.append(table_xml(next_id, item, emu, text_box_xml, shape_fill, shape_line_xml, text_vertical_alignment))
|
|
545
|
+
else:
|
|
546
|
+
parts.append(text_box_xml(next_id, item))
|
|
547
|
+
next_id += 1
|
|
548
|
+
return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
549
|
+
<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
|
|
550
|
+
<p:cSld>
|
|
551
|
+
{slide_background_xml(slide)}
|
|
552
|
+
<p:spTree>
|
|
553
|
+
<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>
|
|
554
|
+
<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>
|
|
555
|
+
{''.join(parts)}
|
|
556
|
+
</p:spTree>
|
|
557
|
+
</p:cSld>
|
|
558
|
+
<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>
|
|
559
|
+
</p:sld>"""
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def rels_xml(manifest, media_start=1, notes_index=None):
|
|
563
|
+
rels = ['<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>']
|
|
564
|
+
for i, item in enumerate(manifest.get("images", []), start=1):
|
|
565
|
+
target = f"../media/image{media_start + i - 1}{image_ext(item['path'])}"
|
|
566
|
+
rels.append(f'<Relationship Id="rId{i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="{target}"/>')
|
|
567
|
+
if notes_index is not None:
|
|
568
|
+
rels.append(
|
|
569
|
+
f'<Relationship Id="rId{len(rels) + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notesSlide{notes_index}.xml"/>'
|
|
570
|
+
)
|
|
571
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' + "".join(rels) + "</Relationships>"
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def notes_slide_xml(text):
|
|
575
|
+
paras = "".join(
|
|
576
|
+
f'<a:p><a:r><a:rPr lang="zh-CN" sz="1200"/><a:t>{xml_text(line)}</a:t></a:r><a:endParaRPr lang="zh-CN" sz="1200"/></a:p>'
|
|
577
|
+
for line in str(text).splitlines()
|
|
578
|
+
) or '<a:p><a:endParaRPr lang="zh-CN" sz="1200"/></a:p>'
|
|
579
|
+
return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
580
|
+
<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
|
|
581
|
+
<p:cSld>
|
|
582
|
+
<p:spTree>
|
|
583
|
+
<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>
|
|
584
|
+
<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>
|
|
585
|
+
<p:sp>
|
|
586
|
+
<p:nvSpPr><p:cNvPr id="2" name="Notes Placeholder"/><p:cNvSpPr txBox="1"/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>
|
|
587
|
+
<p:spPr><a:xfrm><a:off x="685800" y="914400"/><a:ext cx="5486400" cy="6858000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr>
|
|
588
|
+
<p:txBody><a:bodyPr/><a:lstStyle/>{paras}</p:txBody>
|
|
589
|
+
</p:sp>
|
|
590
|
+
</p:spTree>
|
|
591
|
+
</p:cSld>
|
|
592
|
+
<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>
|
|
593
|
+
</p:notes>"""
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def notes_rels_xml(slide_index):
|
|
597
|
+
return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
598
|
+
<Relationships xmlns="{REL_NS}">
|
|
599
|
+
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="../notesMasters/notesMaster1.xml"/>
|
|
600
|
+
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="../slides/slide{slide_index}.xml"/>
|
|
601
|
+
</Relationships>"""
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def notes_master_xml():
|
|
605
|
+
return """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
606
|
+
<p:notesMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
|
|
607
|
+
<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/></p:spTree></p:cSld>
|
|
608
|
+
<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>
|
|
609
|
+
</p:notesMaster>"""
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def notes_master_rels_xml():
|
|
613
|
+
return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
614
|
+
<Relationships xmlns="{REL_NS}">
|
|
615
|
+
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>
|
|
616
|
+
</Relationships>"""
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def content_types_xml(manifests, notes_indices=None):
|
|
620
|
+
notes_indices = notes_indices or []
|
|
621
|
+
defaults = {
|
|
622
|
+
"rels": "application/vnd.openxmlformats-package.relationships+xml",
|
|
623
|
+
"xml": "application/xml",
|
|
624
|
+
}
|
|
625
|
+
for manifest in manifests:
|
|
626
|
+
for item in manifest.get("images", []):
|
|
627
|
+
ext = image_ext(item["path"]).lstrip(".")
|
|
628
|
+
defaults[ext] = content_type_for(item["path"])
|
|
629
|
+
default_xml = "".join(f'<Default Extension="{ext}" ContentType="{ctype}"/>' for ext, ctype in defaults.items())
|
|
630
|
+
overrides = [
|
|
631
|
+
'<Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>',
|
|
632
|
+
'<Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>',
|
|
633
|
+
'<Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>',
|
|
634
|
+
'<Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>',
|
|
635
|
+
'<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>',
|
|
636
|
+
'<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>',
|
|
637
|
+
]
|
|
638
|
+
for i in range(1, len(manifests) + 1):
|
|
639
|
+
overrides.append(f'<Override PartName="/ppt/slides/slide{i}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>')
|
|
640
|
+
if notes_indices:
|
|
641
|
+
overrides.append('<Override PartName="/ppt/notesMasters/notesMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>')
|
|
642
|
+
for i in notes_indices:
|
|
643
|
+
overrides.append(f'<Override PartName="/ppt/notesSlides/notesSlide{i}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>')
|
|
644
|
+
return f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">{default_xml}{"".join(overrides)}</Types>'
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def is_wide_slide(width, height):
|
|
648
|
+
return abs((float(width) / float(height)) / ASPECT_16_9 - 1) <= ASPECT_TOLERANCE
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def slide_size_type(width, height):
|
|
652
|
+
return "screen16x9" if is_wide_slide(width, height) else "custom"
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def presentation_xml(slide_count, width, height):
|
|
656
|
+
slide_ids = "".join(f'<p:sldId id="{255 + i}" r:id="rId{i + 1}"/>' for i in range(1, slide_count + 1))
|
|
657
|
+
size_type = slide_size_type(width, height)
|
|
658
|
+
return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
659
|
+
<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
|
|
660
|
+
<p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>
|
|
661
|
+
<p:sldIdLst>{slide_ids}</p:sldIdLst>
|
|
662
|
+
<p:sldSz cx="{width}" cy="{height}" type="{size_type}"/>
|
|
663
|
+
<p:notesSz cx="6858000" cy="9144000"/>
|
|
664
|
+
</p:presentation>"""
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def presentation_rels_xml(slide_count):
|
|
668
|
+
rels = ['<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>']
|
|
669
|
+
for i in range(1, slide_count + 1):
|
|
670
|
+
rels.append(f'<Relationship Id="rId{i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide{i}.xml"/>')
|
|
671
|
+
return f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="{REL_NS}">{"".join(rels)}</Relationships>'
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def write_common_parts(z, slide_count, width, height, notes_count):
|
|
675
|
+
presentation_format = "Widescreen" if is_wide_slide(width, height) else "Custom"
|
|
676
|
+
z.writestr("_rels/.rels", """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/></Relationships>""")
|
|
677
|
+
z.writestr("docProps/core.xml", """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Image to editable PPT</dc:title></cp:coreProperties>""")
|
|
678
|
+
z.writestr("docProps/app.xml", f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"><Application>Codex</Application><PresentationFormat>{presentation_format}</PresentationFormat><Slides>{slide_count}</Slides></Properties>""")
|
|
679
|
+
z.writestr("ppt/presentation.xml", presentation_xml(slide_count, width, height))
|
|
680
|
+
z.writestr("ppt/_rels/presentation.xml.rels", presentation_rels_xml(slide_count))
|
|
681
|
+
z.writestr("ppt/slideMasters/slideMaster1.xml", """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/></p:spTree></p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst></p:sldMaster>""")
|
|
682
|
+
z.writestr("ppt/slideMasters/_rels/slideMaster1.xml.rels", """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/></Relationships>""")
|
|
683
|
+
z.writestr("ppt/slideLayouts/slideLayout1.xml", """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1"><p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/></p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>""")
|
|
684
|
+
z.writestr("ppt/slideLayouts/_rels/slideLayout1.xml.rels", """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/></Relationships>""")
|
|
685
|
+
# DrawingML requires at least three entries in each theme style list.
|
|
686
|
+
theme_fills = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' * 3
|
|
687
|
+
theme_lines = '<a:ln w="9525"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' * 3
|
|
688
|
+
theme_effects = '<a:effectStyle><a:effectLst/></a:effectStyle>' * 3
|
|
689
|
+
z.writestr("ppt/theme/theme1.xml", f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="ImageToEditablePPT"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="1F1F1F"/></a:dk2><a:lt2><a:srgbClr val="F8F8F8"/></a:lt2><a:accent1><a:srgbClr val="0F766E"/></a:accent1><a:accent2><a:srgbClr val="E66B00"/></a:accent2><a:accent3><a:srgbClr val="F6D365"/></a:accent3><a:accent4><a:srgbClr val="57C4B8"/></a:accent4><a:accent5><a:srgbClr val="666666"/></a:accent5><a:accent6><a:srgbClr val="111111"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="PingFang"><a:majorFont><a:latin typeface="PingFang SC"/><a:ea typeface="PingFang SC"/><a:cs typeface="PingFang SC"/></a:majorFont><a:minorFont><a:latin typeface="PingFang SC"/><a:ea typeface="PingFang SC"/><a:cs typeface="PingFang SC"/></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst>{theme_fills}</a:fillStyleLst><a:lnStyleLst>{theme_lines}</a:lnStyleLst><a:effectStyleLst>{theme_effects}</a:effectStyleLst><a:bgFillStyleLst>{theme_fills}</a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>""")
|
|
690
|
+
if notes_count:
|
|
691
|
+
z.writestr("ppt/notesMasters/notesMaster1.xml", notes_master_xml())
|
|
692
|
+
z.writestr("ppt/notesMasters/_rels/notesMaster1.xml.rels", notes_master_rels_xml())
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def write_pptx(manifest, out_path, manifest_path):
|
|
696
|
+
width = emu(manifest.get("slide", {}).get("width", 13.333))
|
|
697
|
+
height = emu(manifest.get("slide", {}).get("height", 7.5))
|
|
698
|
+
out = Path(out_path)
|
|
699
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
700
|
+
normalized = normalize_manifest(manifest)
|
|
701
|
+
media_index = 1
|
|
702
|
+
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
|
|
703
|
+
z.writestr("[Content_Types].xml", content_types_xml([normalized], []))
|
|
704
|
+
write_common_parts(z, 1, width, height, 0)
|
|
705
|
+
z.writestr("ppt/slides/slide1.xml", slide_xml(normalized))
|
|
706
|
+
z.writestr("ppt/slides/_rels/slide1.xml.rels", rels_xml(normalized, media_index, None))
|
|
707
|
+
base = Path(manifest_path).resolve().parent
|
|
708
|
+
for item in normalized.get("images", []):
|
|
709
|
+
src = Path(item["path"])
|
|
710
|
+
if not src.is_absolute():
|
|
711
|
+
src = base / src
|
|
712
|
+
z.write(src, f"ppt/media/image{media_index}{image_ext(src)}")
|
|
713
|
+
media_index += 1
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def deck_slide_size(deck, page_entries):
|
|
717
|
+
slide = deck.get("slide") or {}
|
|
718
|
+
if not slide and page_entries:
|
|
719
|
+
slide = page_entries[0]["manifest"].get("slide", {})
|
|
720
|
+
return emu(slide.get("width", 13.333)), emu(slide.get("height", 7.5))
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def write_deck(deck, page_entries, out_path, notes_entries):
|
|
724
|
+
if not page_entries:
|
|
725
|
+
raise ValueError("Deck has no pages")
|
|
726
|
+
width, height = deck_slide_size(deck, page_entries)
|
|
727
|
+
out = Path(out_path)
|
|
728
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
729
|
+
notes_by_page = {int(entry.get("page_index", 0)): entry for entry in notes_entries if entry.get("text")}
|
|
730
|
+
notes_indices = sorted(notes_by_page)
|
|
731
|
+
normalized_entries = [{**entry, "manifest": normalize_manifest(entry["manifest"])} for entry in page_entries]
|
|
732
|
+
manifests = [entry["manifest"] for entry in normalized_entries]
|
|
733
|
+
media_index = 1
|
|
734
|
+
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
|
|
735
|
+
z.writestr("[Content_Types].xml", content_types_xml(manifests, notes_indices))
|
|
736
|
+
write_common_parts(z, len(page_entries), width, height, len(notes_by_page))
|
|
737
|
+
for slide_index, entry in enumerate(normalized_entries, start=1):
|
|
738
|
+
manifest = entry["manifest"]
|
|
739
|
+
notes_index = slide_index if slide_index in notes_by_page else None
|
|
740
|
+
z.writestr(f"ppt/slides/slide{slide_index}.xml", slide_xml(manifest))
|
|
741
|
+
z.writestr(f"ppt/slides/_rels/slide{slide_index}.xml.rels", rels_xml(manifest, media_index, notes_index))
|
|
742
|
+
base = Path(entry["manifest_path"]).resolve().parent
|
|
743
|
+
for item in manifest.get("images", []):
|
|
744
|
+
src = Path(item["path"])
|
|
745
|
+
if not src.is_absolute():
|
|
746
|
+
src = base / src
|
|
747
|
+
z.write(src, f"ppt/media/image{media_index}{image_ext(src)}")
|
|
748
|
+
media_index += 1
|
|
749
|
+
if notes_index is not None:
|
|
750
|
+
note = notes_by_page[slide_index]
|
|
751
|
+
notes_xml = note.get("notes_xml")
|
|
752
|
+
if notes_xml and Path(notes_xml).exists():
|
|
753
|
+
z.writestr(f"ppt/notesSlides/notesSlide{notes_index}.xml", Path(notes_xml).read_bytes())
|
|
754
|
+
else:
|
|
755
|
+
z.writestr(f"ppt/notesSlides/notesSlide{notes_index}.xml", notes_slide_xml(note.get("text", "")))
|
|
756
|
+
z.writestr(f"ppt/notesSlides/_rels/notesSlide{notes_index}.xml.rels", notes_rels_xml(slide_index))
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def page_entries_from_deck_manifest(deck_manifest_path):
|
|
760
|
+
deck_path = Path(deck_manifest_path).resolve()
|
|
761
|
+
deck = json.loads(deck_path.read_text(encoding="utf-8"))
|
|
762
|
+
root = Path(deck.get("job_dir", deck_path.parent)).resolve()
|
|
763
|
+
entries = []
|
|
764
|
+
for page in deck.get("pages", []):
|
|
765
|
+
manifest_path = Path(page.get("manifest", ""))
|
|
766
|
+
if not manifest_path.is_absolute():
|
|
767
|
+
manifest_path = root / manifest_path
|
|
768
|
+
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
769
|
+
entries.append({"manifest": manifest, "manifest_path": manifest_path})
|
|
770
|
+
notes_path = deck.get("notes_manifest")
|
|
771
|
+
notes_entries = []
|
|
772
|
+
if notes_path:
|
|
773
|
+
notes_file = Path(notes_path)
|
|
774
|
+
if not notes_file.is_absolute():
|
|
775
|
+
notes_file = root / notes_file
|
|
776
|
+
if notes_file.exists():
|
|
777
|
+
notes_entries = json.loads(notes_file.read_text(encoding="utf-8")).get("notes", [])
|
|
778
|
+
for note in notes_entries:
|
|
779
|
+
notes_xml = note.get("notes_xml")
|
|
780
|
+
if notes_xml:
|
|
781
|
+
notes_xml_path = Path(notes_xml)
|
|
782
|
+
if not notes_xml_path.is_absolute():
|
|
783
|
+
notes_xml_path = root / notes_xml_path
|
|
784
|
+
note["notes_xml"] = str(notes_xml_path)
|
|
785
|
+
return deck, entries, notes_entries
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def output_path_from_deck_manifest(deck_manifest_path):
|
|
789
|
+
deck_path = Path(deck_manifest_path).resolve()
|
|
790
|
+
deck = json.loads(deck_path.read_text(encoding="utf-8"))
|
|
791
|
+
root = Path(deck.get("job_dir", deck_path.parent)).resolve()
|
|
792
|
+
output = Path(deck.get("output", "final/deck_edited.pptx"))
|
|
793
|
+
if not output.is_absolute():
|
|
794
|
+
output = root / output
|
|
795
|
+
return output
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def render_preview(manifest, manifest_path, out_path):
|
|
799
|
+
from PIL import Image, ImageColor, ImageDraw, ImageFont
|
|
800
|
+
|
|
801
|
+
manifest = normalize_manifest(manifest)
|
|
802
|
+
slide = manifest.get("slide", {})
|
|
803
|
+
width_in = float(slide.get("width", 13.333))
|
|
804
|
+
height_in = float(slide.get("height", 7.5))
|
|
805
|
+
scale = int(manifest.get("preview_scale", 120))
|
|
806
|
+
canvas = Image.new("RGB", (int(width_in * scale), int(height_in * scale)), ImageColor.getrgb(slide.get("background", "#ffffff")))
|
|
807
|
+
base = Path(manifest_path).resolve().parent
|
|
808
|
+
draw = ImageDraw.Draw(canvas)
|
|
809
|
+
|
|
810
|
+
def open_preview_image(src):
|
|
811
|
+
if src.suffix.lower() != ".svg":
|
|
812
|
+
return Image.open(src).convert("RGBA")
|
|
813
|
+
convert = "/opt/homebrew/bin/magick"
|
|
814
|
+
if not Path(convert).exists():
|
|
815
|
+
convert = "/opt/homebrew/bin/convert"
|
|
816
|
+
if not Path(convert).exists():
|
|
817
|
+
print(f"Warning: cannot preview SVG without ImageMagick: {src}", file=sys.stderr)
|
|
818
|
+
return None
|
|
819
|
+
with tempfile.NamedTemporaryFile(suffix=".png") as handle:
|
|
820
|
+
subprocess.run([convert, str(src), handle.name], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
821
|
+
return Image.open(handle.name).convert("RGBA")
|
|
822
|
+
|
|
823
|
+
def render_shape(item):
|
|
824
|
+
box = [item.get("left", 0) * scale, item.get("top", 0) * scale, (item.get("left", 0) + item.get("width", 1)) * scale, (item.get("top", 0) + item.get("height", 1)) * scale]
|
|
825
|
+
fill = preview_color(item.get("fill"))
|
|
826
|
+
outline = preview_color(item.get("stroke", "#000000"))
|
|
827
|
+
width = max(1, int(float(item.get("stroke_width", 1))))
|
|
828
|
+
if item.get("polygon"):
|
|
829
|
+
points = [(point[0] * scale, point[1] * scale) for point in item["polygon"]]
|
|
830
|
+
draw.polygon(points, fill=None if fill in (None, "none") else fill, outline=None if outline == "none" else outline)
|
|
831
|
+
elif item.get("type") in ("line", "path"):
|
|
832
|
+
width = max(1, round(float(item.get("stroke_width", 1)) * scale / 72))
|
|
833
|
+
if item.get("type") == "path":
|
|
834
|
+
points = preview_path_points(item, scale)
|
|
835
|
+
if item["path_px"][-1]["op"] == "close" and fill not in (None, "none"):
|
|
836
|
+
draw.polygon(points, fill=fill)
|
|
837
|
+
else:
|
|
838
|
+
coords = [value * scale for value in item["points"]] if "points" in item else box
|
|
839
|
+
points = [tuple(coords[:2]), tuple(coords[2:])]
|
|
840
|
+
if outline not in (None, "none"):
|
|
841
|
+
draw_styled_path(draw, points, outline, width, item.get("dash"), item.get("start_arrow"), item.get("end_arrow"))
|
|
842
|
+
elif item.get("type") == "ellipse":
|
|
843
|
+
draw.ellipse(box, fill=None if fill in (None, "none") else fill, outline=None if outline == "none" else outline, width=width)
|
|
844
|
+
elif item.get("type") == "roundRect" or item.get("preset") == "roundRect":
|
|
845
|
+
radius = int(float(item.get("radius", 0.12)) * scale)
|
|
846
|
+
draw.rounded_rectangle(box, radius=radius, fill=None if fill in (None, "none") else fill, outline=None if outline == "none" else outline, width=width)
|
|
847
|
+
elif item.get("preset") == "diamond":
|
|
848
|
+
left, top, right, bottom = box
|
|
849
|
+
center_x = (left + right) / 2
|
|
850
|
+
center_y = (top + bottom) / 2
|
|
851
|
+
points = [(center_x, top), (right, center_y), (center_x, bottom), (left, center_y)]
|
|
852
|
+
draw.polygon(points, fill=None if fill in (None, "none") else fill, outline=None if outline == "none" else outline)
|
|
853
|
+
else:
|
|
854
|
+
draw.rectangle(box, fill=None if fill in (None, "none") else fill, outline=None if outline == "none" else outline, width=width)
|
|
855
|
+
|
|
856
|
+
def render_image(item):
|
|
857
|
+
src = Path(item["path"])
|
|
858
|
+
if not src.is_absolute():
|
|
859
|
+
src = base / src
|
|
860
|
+
img = open_preview_image(src)
|
|
861
|
+
if img is None:
|
|
862
|
+
return
|
|
863
|
+
img = img.resize((max(1, int(item.get("width", 1) * scale)), max(1, int(item.get("height", 1) * scale))))
|
|
864
|
+
canvas.paste(img, (int(item.get("left", 0) * scale), int(item.get("top", 0) * scale)), img)
|
|
865
|
+
|
|
866
|
+
def render_text(item):
|
|
867
|
+
preview_font_scale = float(item.get("preview_font_scale", manifest.get("preview_font_scale", 1.0)))
|
|
868
|
+
size = max(1, int(float(item.get("font_size", 18)) * scale / 72 * preview_font_scale))
|
|
869
|
+
font_path = choose_preview_font(item.get("preview_font"))
|
|
870
|
+
try:
|
|
871
|
+
font = ImageFont.truetype(font_path, size=size) if font_path else ImageFont.load_default()
|
|
872
|
+
except Exception:
|
|
873
|
+
font = ImageFont.load_default()
|
|
874
|
+
if item.get("paragraphs"):
|
|
875
|
+
lines = []
|
|
876
|
+
for paragraph in item["paragraphs"]:
|
|
877
|
+
if isinstance(paragraph, str):
|
|
878
|
+
lines.append(paragraph)
|
|
879
|
+
else:
|
|
880
|
+
lines.append("".join(str(run.get("text", "")) for run in paragraph.get("runs", [])))
|
|
881
|
+
preview_text = "\n".join(lines)
|
|
882
|
+
elif item.get("runs"):
|
|
883
|
+
preview_text = "".join(str(run.get("text", "")) for run in item["runs"])
|
|
884
|
+
else:
|
|
885
|
+
preview_text = item.get("text", "")
|
|
886
|
+
fill = preview_color(item.get("color", "#111111"))
|
|
887
|
+
align = text_alignment(item.get("align", "left"))[1]
|
|
888
|
+
valign = text_vertical_alignment(item.get("valign", "top"))[1]
|
|
889
|
+
box_x = int(item.get("left", 0) * scale)
|
|
890
|
+
box_y = int(item.get("top", 0) * scale)
|
|
891
|
+
box_width = max(1, int(item.get("width", 1) * scale))
|
|
892
|
+
box_height = max(1, int(item.get("height", 0.4) * scale))
|
|
893
|
+
rotation = float(item.get("rotation", 0) or 0)
|
|
894
|
+
|
|
895
|
+
def aligned_origin(bounds, origin_x, origin_y):
|
|
896
|
+
text_width = bounds[2] - bounds[0]
|
|
897
|
+
text_height = bounds[3] - bounds[1]
|
|
898
|
+
if align == "center":
|
|
899
|
+
text_x = origin_x + (box_width - text_width) // 2 - bounds[0]
|
|
900
|
+
elif align == "right":
|
|
901
|
+
text_x = origin_x + box_width - text_width - bounds[0]
|
|
902
|
+
else:
|
|
903
|
+
text_x = origin_x
|
|
904
|
+
if valign == "middle":
|
|
905
|
+
text_y = origin_y + (box_height - text_height) // 2 - bounds[1]
|
|
906
|
+
elif valign == "bottom":
|
|
907
|
+
text_y = origin_y + box_height - text_height - bounds[1]
|
|
908
|
+
else:
|
|
909
|
+
text_y = origin_y
|
|
910
|
+
return text_x, text_y
|
|
911
|
+
|
|
912
|
+
run_specs = []
|
|
913
|
+
if item.get("runs"):
|
|
914
|
+
cursor_x = 0
|
|
915
|
+
base_size = size
|
|
916
|
+
for run in item["runs"]:
|
|
917
|
+
run_size = max(1, int(float(run.get("font_size", item.get("font_size", 18))) * scale / 72 * preview_font_scale))
|
|
918
|
+
run_font_path = choose_preview_font(run.get("preview_font") or item.get("preview_font"))
|
|
919
|
+
try:
|
|
920
|
+
run_font = ImageFont.truetype(run_font_path, size=run_size) if run_font_path else ImageFont.load_default()
|
|
921
|
+
except Exception:
|
|
922
|
+
run_font = font
|
|
923
|
+
run_fill = preview_color(run.get("color", item.get("color", "#111111")))
|
|
924
|
+
baseline = float(run.get("baseline", 0) or 0)
|
|
925
|
+
run_y = int(-baseline / 100000 * base_size)
|
|
926
|
+
run_text = str(run.get("text", ""))
|
|
927
|
+
run_specs.append((cursor_x, run_y, run_text, run_fill, run_font, run_font.getbbox(run_text)))
|
|
928
|
+
cursor_x += int(round(draw.textlength(run_text, font=run_font)))
|
|
929
|
+
|
|
930
|
+
def draw_content(target_draw, origin_x, origin_y):
|
|
931
|
+
if run_specs:
|
|
932
|
+
bounds = (
|
|
933
|
+
min(spec[0] + spec[5][0] for spec in run_specs),
|
|
934
|
+
min(spec[1] + spec[5][1] for spec in run_specs),
|
|
935
|
+
max(spec[0] + spec[5][2] for spec in run_specs),
|
|
936
|
+
max(spec[1] + spec[5][3] for spec in run_specs),
|
|
937
|
+
)
|
|
938
|
+
text_x, text_y = aligned_origin(bounds, origin_x, origin_y)
|
|
939
|
+
for run_x, run_y, run_text, run_fill, run_font, _run_bounds in run_specs:
|
|
940
|
+
target_draw.text((text_x + run_x, text_y + run_y), run_text, fill=run_fill, font=run_font)
|
|
941
|
+
return
|
|
942
|
+
bounds = target_draw.multiline_textbbox((0, 0), preview_text, font=font, spacing=4, align=align)
|
|
943
|
+
text_x, text_y = aligned_origin(bounds, origin_x, origin_y)
|
|
944
|
+
target_draw.multiline_text((text_x, text_y), preview_text, fill=fill, font=font, spacing=4, align=align)
|
|
945
|
+
|
|
946
|
+
if rotation:
|
|
947
|
+
layer = Image.new("RGBA", (box_width, box_height), (0, 0, 0, 0))
|
|
948
|
+
draw_content(ImageDraw.Draw(layer), 0, 0)
|
|
949
|
+
rotated = layer.rotate(-rotation, expand=True)
|
|
950
|
+
paste_x = box_x + (box_width - rotated.width) // 2
|
|
951
|
+
paste_y = box_y + (box_height - rotated.height) // 2
|
|
952
|
+
canvas.paste(rotated, (paste_x, paste_y), rotated)
|
|
953
|
+
return
|
|
954
|
+
draw_content(draw, box_x, box_y)
|
|
955
|
+
|
|
956
|
+
def render_table(table):
|
|
957
|
+
visible = [cell for row in table["cells"] for cell in row if "_owner" not in cell]
|
|
958
|
+
for cell in visible:
|
|
959
|
+
fill = preview_color(cell["fill"])
|
|
960
|
+
if fill not in (None, "none"):
|
|
961
|
+
draw.rectangle([cell["left"] * scale, cell["top"] * scale,
|
|
962
|
+
(cell["left"] + cell["width"]) * scale,
|
|
963
|
+
(cell["top"] + cell["height"]) * scale], fill=fill)
|
|
964
|
+
for cell in visible:
|
|
965
|
+
stroke = preview_color(cell["stroke"])
|
|
966
|
+
if stroke not in (None, "none") and cell["stroke_width"] > 0:
|
|
967
|
+
draw.rectangle([cell["left"] * scale, cell["top"] * scale,
|
|
968
|
+
(cell["left"] + cell["width"]) * scale,
|
|
969
|
+
(cell["top"] + cell["height"]) * scale], outline=stroke,
|
|
970
|
+
width=max(1, round(cell["stroke_width"] * scale / 72)))
|
|
971
|
+
render_text(cell_text_box(cell))
|
|
972
|
+
|
|
973
|
+
layered = []
|
|
974
|
+
for index, item in enumerate(manifest.get("tables", [])):
|
|
975
|
+
layered.append((float(item.get("z_index", 250)), index, render_table, item))
|
|
976
|
+
for index, item in enumerate(manifest.get("shapes", [])):
|
|
977
|
+
layered.append((float(item.get("z_index", 100)), index, render_shape, item))
|
|
978
|
+
for index, item in enumerate(manifest.get("images", [])):
|
|
979
|
+
layered.append((float(item.get("z_index", 200)), index, render_image, item))
|
|
980
|
+
for index, item in enumerate(manifest.get("text_boxes", [])):
|
|
981
|
+
layered.append((float(item.get("z_index", 300)), index, render_text, item))
|
|
982
|
+
for _z_index, _order, renderer, item in sorted(layered, key=lambda entry: (entry[0], entry[1])):
|
|
983
|
+
renderer(item)
|
|
984
|
+
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
|
|
985
|
+
canvas.save(out_path)
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def choose_preview_font(preferred):
|
|
989
|
+
candidates = [
|
|
990
|
+
preferred,
|
|
991
|
+
"/System/Library/Fonts/STHeiti Medium.ttc",
|
|
992
|
+
"/System/Library/Fonts/STHeiti Light.ttc",
|
|
993
|
+
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
|
|
994
|
+
"/Library/Fonts/Arial Unicode.ttf",
|
|
995
|
+
]
|
|
996
|
+
for candidate in candidates:
|
|
997
|
+
if candidate and Path(candidate).exists():
|
|
998
|
+
return candidate
|
|
999
|
+
return None
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def main():
|
|
1003
|
+
parser = argparse.ArgumentParser()
|
|
1004
|
+
parser.add_argument("manifest", nargs="?")
|
|
1005
|
+
parser.add_argument("--deck-manifest")
|
|
1006
|
+
parser.add_argument("--out")
|
|
1007
|
+
parser.add_argument("--preview")
|
|
1008
|
+
args = parser.parse_args()
|
|
1009
|
+
if args.deck_manifest:
|
|
1010
|
+
deck, entries, notes_entries = page_entries_from_deck_manifest(args.deck_manifest)
|
|
1011
|
+
out = Path(args.out) if args.out else output_path_from_deck_manifest(args.deck_manifest)
|
|
1012
|
+
write_deck(deck, entries, out, notes_entries)
|
|
1013
|
+
print(f"Wrote {out}")
|
|
1014
|
+
return
|
|
1015
|
+
if not args.manifest:
|
|
1016
|
+
parser.error("manifest is required unless --deck-manifest is used")
|
|
1017
|
+
if not args.out:
|
|
1018
|
+
parser.error("--out is required unless --deck-manifest provides an output")
|
|
1019
|
+
manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8"))
|
|
1020
|
+
write_pptx(manifest, args.out, args.manifest)
|
|
1021
|
+
if args.preview:
|
|
1022
|
+
render_preview(manifest, args.manifest, args.preview)
|
|
1023
|
+
print(f"Wrote {args.out}")
|
|
1024
|
+
if args.preview:
|
|
1025
|
+
print(f"Wrote {args.preview}")
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
if __name__ == "__main__":
|
|
1029
|
+
main()
|