@hfyjq/crannia 1.0.0 → 1.1.1
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 +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/updater.py +229 -40
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +24 -10
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +178 -20
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
|
@@ -1,1267 +1,1267 @@
|
|
|
1
|
-
"""Core PPTX assembly: create_pptx_with_native_svg."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import hashlib
|
|
6
|
-
import json
|
|
7
|
-
import mimetypes
|
|
8
|
-
import os
|
|
9
|
-
import re
|
|
10
|
-
import posixpath
|
|
11
|
-
import shutil
|
|
12
|
-
import stat
|
|
13
|
-
import subprocess
|
|
14
|
-
import tempfile
|
|
15
|
-
import uuid
|
|
16
|
-
import zipfile
|
|
17
|
-
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
18
|
-
from datetime import datetime, timezone
|
|
19
|
-
from pathlib import Path
|
|
20
|
-
from typing import Any
|
|
21
|
-
from xml.sax.saxutils import escape
|
|
22
|
-
|
|
23
|
-
from pptx import Presentation
|
|
24
|
-
from pptx.util import Emu
|
|
25
|
-
|
|
26
|
-
from ..drawingml.converter import convert_svg_to_slide_shapes
|
|
27
|
-
from .dimensions import (
|
|
28
|
-
CANVAS_FORMATS,
|
|
29
|
-
get_slide_dimensions, get_pixel_dimensions,
|
|
30
|
-
get_viewbox_dimensions, detect_format_from_svg,
|
|
31
|
-
)
|
|
32
|
-
from .media import (
|
|
33
|
-
PNG_RENDERER,
|
|
34
|
-
get_png_renderer_info, convert_svg_to_png, convert_svg_to_png_cached,
|
|
35
|
-
)
|
|
36
|
-
from .notes import (
|
|
37
|
-
markdown_to_plain_text,
|
|
38
|
-
create_notes_master_rels_xml,
|
|
39
|
-
create_notes_master_xml,
|
|
40
|
-
create_notes_slide_xml,
|
|
41
|
-
create_notes_slide_rels_xml,
|
|
42
|
-
)
|
|
43
|
-
from .narration import (
|
|
44
|
-
AUDIO_CONTENT_TYPES,
|
|
45
|
-
AUDIO_REL_TYPE,
|
|
46
|
-
AUDIO_MARKER_PNG_BYTES,
|
|
47
|
-
IMAGE_REL_TYPE,
|
|
48
|
-
MEDIA_REL_TYPE,
|
|
49
|
-
apply_recorded_timing,
|
|
50
|
-
inject_narration,
|
|
51
|
-
next_shape_id,
|
|
52
|
-
probe_audio_duration,
|
|
53
|
-
)
|
|
54
|
-
from .slide_xml import (
|
|
55
|
-
ANIMATIONS_AVAILABLE, TRANSITIONS,
|
|
56
|
-
create_slide_xml_with_svg, create_slide_rels_xml,
|
|
57
|
-
)
|
|
58
|
-
|
|
59
|
-
# Re-import create_transition_xml only if available
|
|
60
|
-
try:
|
|
61
|
-
from pptx_animations import (
|
|
62
|
-
create_transition_xml,
|
|
63
|
-
create_sequence_timing_xml,
|
|
64
|
-
pick_animation_effect,
|
|
65
|
-
)
|
|
66
|
-
except ImportError:
|
|
67
|
-
create_transition_xml = None
|
|
68
|
-
create_sequence_timing_xml = None
|
|
69
|
-
pick_animation_effect = None
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _append_relationship(
|
|
73
|
-
rels_path: Path,
|
|
74
|
-
rel_type: str,
|
|
75
|
-
target: str,
|
|
76
|
-
) -> str:
|
|
77
|
-
"""Append a relationship entry with the next available rId."""
|
|
78
|
-
with open(rels_path, 'r', encoding='utf-8') as f:
|
|
79
|
-
rels_content = f.read()
|
|
80
|
-
|
|
81
|
-
rid_numbers = [int(match) for match in re.findall(r'Id="rId(\d+)"', rels_content)]
|
|
82
|
-
next_rid = f'rId{max(rid_numbers, default=0) + 1}'
|
|
83
|
-
rel_xml = (
|
|
84
|
-
f' <Relationship Id="{next_rid}" '
|
|
85
|
-
f'Type="{rel_type}" Target="{target}"/>'
|
|
86
|
-
)
|
|
87
|
-
rels_content = rels_content.replace(
|
|
88
|
-
'</Relationships>', rel_xml + '\n</Relationships>',
|
|
89
|
-
)
|
|
90
|
-
|
|
91
|
-
with open(rels_path, 'w', encoding='utf-8') as f:
|
|
92
|
-
f.write(rels_content)
|
|
93
|
-
|
|
94
|
-
return next_rid
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
def _find_relationship_id(
|
|
98
|
-
rels_path: Path,
|
|
99
|
-
rel_type: str,
|
|
100
|
-
target: str,
|
|
101
|
-
) -> str | None:
|
|
102
|
-
"""Find an existing relationship id by type and target."""
|
|
103
|
-
if not rels_path.exists():
|
|
104
|
-
return None
|
|
105
|
-
rels_content = rels_path.read_text(encoding='utf-8')
|
|
106
|
-
pattern = (
|
|
107
|
-
r'<Relationship\b[^>]*\bId="([^"]+)"[^>]*'
|
|
108
|
-
rf'\bType="{re.escape(rel_type)}"[^>]*'
|
|
109
|
-
rf'\bTarget="{re.escape(target)}"[^>]*/>'
|
|
110
|
-
)
|
|
111
|
-
match = re.search(pattern, rels_content)
|
|
112
|
-
return match.group(1) if match else None
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def _add_default_content_type(content_types: str, extension: str, content_type: str) -> str:
|
|
116
|
-
"""Add a Default content type if it is not already present."""
|
|
117
|
-
ext = extension.lstrip(".")
|
|
118
|
-
if f'Extension="{ext}"' in content_types:
|
|
119
|
-
return content_types
|
|
120
|
-
entry = f' <Default Extension="{ext}" ContentType="{content_type}"/>'
|
|
121
|
-
override_pos = content_types.find('<Override ')
|
|
122
|
-
if override_pos >= 0:
|
|
123
|
-
return content_types[:override_pos] + entry + '\n' + content_types[override_pos:]
|
|
124
|
-
return content_types.replace('</Types>', entry + '\n</Types>')
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def _add_content_type_override(content_types: str, part_name: str, content_type: str) -> str:
|
|
128
|
-
"""Add an Override content type if it is not already present."""
|
|
129
|
-
normalized = '/' + part_name.lstrip('/')
|
|
130
|
-
if f'PartName="{normalized}"' in content_types:
|
|
131
|
-
return content_types
|
|
132
|
-
entry = f' <Override PartName="{normalized}" ContentType="{content_type}"/>'
|
|
133
|
-
return content_types.replace('</Types>', entry + '\n</Types>')
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
_IMAGE_CONTENT_TYPES = {
|
|
137
|
-
'png': 'image/png',
|
|
138
|
-
'jpg': 'image/jpeg',
|
|
139
|
-
'jpeg': 'image/jpeg',
|
|
140
|
-
'gif': 'image/gif',
|
|
141
|
-
'webp': 'image/webp',
|
|
142
|
-
'svg': 'image/svg+xml',
|
|
143
|
-
'bmp': 'image/bmp',
|
|
144
|
-
'emf': 'image/x-emf',
|
|
145
|
-
'tif': 'image/tiff',
|
|
146
|
-
'tiff': 'image/tiff',
|
|
147
|
-
'wmf': 'image/x-wmf',
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
def _content_type_for_extension(ext: str) -> str:
|
|
152
|
-
clean = ext.lower().lstrip('.')
|
|
153
|
-
content_type = _IMAGE_CONTENT_TYPES.get(clean) or mimetypes.guess_type(f'x.{clean}')[0]
|
|
154
|
-
if not content_type:
|
|
155
|
-
raise ValueError(f"Unknown media content type for extension: {ext}")
|
|
156
|
-
return content_type
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
def _as_dict(value: Any) -> dict[str, Any]:
|
|
160
|
-
return value if isinstance(value, dict) else {}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
def _create_writable_work_dir(output_path: Path) -> Path:
|
|
164
|
-
"""Create a real writable work directory for PPTX assembly."""
|
|
165
|
-
parents = [output_path.parent, Path.cwd(), Path(tempfile.gettempdir())]
|
|
166
|
-
seen: set[str] = set()
|
|
167
|
-
errors: list[str] = []
|
|
168
|
-
|
|
169
|
-
for parent in parents:
|
|
170
|
-
parent = parent if str(parent) else Path(".")
|
|
171
|
-
try:
|
|
172
|
-
key = str(parent.resolve())
|
|
173
|
-
except OSError:
|
|
174
|
-
key = str(parent.absolute())
|
|
175
|
-
if key in seen:
|
|
176
|
-
continue
|
|
177
|
-
seen.add(key)
|
|
178
|
-
|
|
179
|
-
try:
|
|
180
|
-
parent.mkdir(parents=True, exist_ok=True)
|
|
181
|
-
except OSError as exc:
|
|
182
|
-
errors.append(f"{parent}: cannot create parent ({exc})")
|
|
183
|
-
continue
|
|
184
|
-
|
|
185
|
-
for _ in range(3):
|
|
186
|
-
work_dir = parent / f".pptx-build-{os.getpid()}-{uuid.uuid4().hex}"
|
|
187
|
-
try:
|
|
188
|
-
work_dir.mkdir(mode=0o700)
|
|
189
|
-
probe_path = work_dir / ".write-probe"
|
|
190
|
-
probe_path.write_text("ok", encoding="utf-8")
|
|
191
|
-
probe_path.unlink()
|
|
192
|
-
return work_dir
|
|
193
|
-
except OSError as exc:
|
|
194
|
-
errors.append(f"{work_dir}: {exc}")
|
|
195
|
-
shutil.rmtree(work_dir, ignore_errors=True)
|
|
196
|
-
|
|
197
|
-
details = "\n - ".join(errors) if errors else "no candidate directories available"
|
|
198
|
-
raise PermissionError(
|
|
199
|
-
"Unable to create a writable PPTX work directory. "
|
|
200
|
-
"Set the output path to a writable project directory or adjust sandbox permissions. "
|
|
201
|
-
f"Tried:\n - {details}"
|
|
202
|
-
)
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
def _relax_output_permissions(output_path: Path) -> list[str]:
|
|
206
|
-
"""Make exported files readable outside the sandbox owner where possible."""
|
|
207
|
-
warnings: list[str] = []
|
|
208
|
-
|
|
209
|
-
try:
|
|
210
|
-
current_mode = output_path.stat().st_mode
|
|
211
|
-
readable_mode = (
|
|
212
|
-
current_mode
|
|
213
|
-
| stat.S_IRUSR
|
|
214
|
-
| stat.S_IWUSR
|
|
215
|
-
| stat.S_IRGRP
|
|
216
|
-
| stat.S_IROTH
|
|
217
|
-
)
|
|
218
|
-
os.chmod(output_path, readable_mode)
|
|
219
|
-
except OSError as exc:
|
|
220
|
-
warnings.append(f"chmod skipped for {output_path}: {exc}")
|
|
221
|
-
|
|
222
|
-
if os.name != 'nt':
|
|
223
|
-
return warnings
|
|
224
|
-
|
|
225
|
-
# Windows ACLs can remain sandbox-only even when the file mode looks sane.
|
|
226
|
-
# Grant the built-in Users SID read access; the SID avoids localization
|
|
227
|
-
# issues on non-English Windows installations.
|
|
228
|
-
try:
|
|
229
|
-
result = subprocess.run(
|
|
230
|
-
['icacls', str(output_path), '/grant', '*S-1-5-32-545:R'],
|
|
231
|
-
capture_output=True,
|
|
232
|
-
text=True,
|
|
233
|
-
check=False,
|
|
234
|
-
)
|
|
235
|
-
except OSError as exc:
|
|
236
|
-
warnings.append(f"icacls skipped for {output_path}: {exc}")
|
|
237
|
-
else:
|
|
238
|
-
if result.returncode != 0:
|
|
239
|
-
message = (result.stderr or result.stdout or '').strip()
|
|
240
|
-
details = f": {message}" if message else ''
|
|
241
|
-
warnings.append(f"icacls failed for {output_path}{details}")
|
|
242
|
-
|
|
243
|
-
return warnings
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
_NOTES_MASTER_REL_TYPE = (
|
|
247
|
-
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster'
|
|
248
|
-
)
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
def _ensure_notes_master(extract_dir: Path) -> None:
|
|
252
|
-
"""Create notesMaster parts and wire them into the presentation package."""
|
|
253
|
-
ppt_dir = extract_dir / 'ppt'
|
|
254
|
-
notes_masters_dir = ppt_dir / 'notesMasters'
|
|
255
|
-
notes_masters_dir.mkdir(exist_ok=True)
|
|
256
|
-
|
|
257
|
-
notes_master_path = notes_masters_dir / 'notesMaster1.xml'
|
|
258
|
-
if not notes_master_path.exists():
|
|
259
|
-
notes_master_path.write_text(create_notes_master_xml(), encoding='utf-8')
|
|
260
|
-
|
|
261
|
-
theme_dir = ppt_dir / 'theme'
|
|
262
|
-
theme_dir.mkdir(exist_ok=True)
|
|
263
|
-
theme1_path = theme_dir / 'theme1.xml'
|
|
264
|
-
theme2_path = theme_dir / 'theme2.xml'
|
|
265
|
-
if not theme2_path.exists():
|
|
266
|
-
if theme1_path.exists():
|
|
267
|
-
shutil.copy2(theme1_path, theme2_path)
|
|
268
|
-
else:
|
|
269
|
-
raise RuntimeError('Cannot create notes theme: ppt/theme/theme1.xml is missing')
|
|
270
|
-
|
|
271
|
-
notes_master_rels_dir = notes_masters_dir / '_rels'
|
|
272
|
-
notes_master_rels_dir.mkdir(exist_ok=True)
|
|
273
|
-
notes_master_rels_path = notes_master_rels_dir / 'notesMaster1.xml.rels'
|
|
274
|
-
if not notes_master_rels_path.exists():
|
|
275
|
-
notes_master_rels_path.write_text(
|
|
276
|
-
create_notes_master_rels_xml(),
|
|
277
|
-
encoding='utf-8',
|
|
278
|
-
)
|
|
279
|
-
|
|
280
|
-
presentation_rels_path = ppt_dir / '_rels' / 'presentation.xml.rels'
|
|
281
|
-
notes_master_rid = _find_relationship_id(
|
|
282
|
-
presentation_rels_path,
|
|
283
|
-
_NOTES_MASTER_REL_TYPE,
|
|
284
|
-
'notesMasters/notesMaster1.xml',
|
|
285
|
-
)
|
|
286
|
-
if notes_master_rid is None:
|
|
287
|
-
notes_master_rid = _append_relationship(
|
|
288
|
-
presentation_rels_path,
|
|
289
|
-
_NOTES_MASTER_REL_TYPE,
|
|
290
|
-
'notesMasters/notesMaster1.xml',
|
|
291
|
-
)
|
|
292
|
-
|
|
293
|
-
presentation_path = ppt_dir / 'presentation.xml'
|
|
294
|
-
presentation_xml = presentation_path.read_text(encoding='utf-8')
|
|
295
|
-
if '<p:notesMasterIdLst>' in presentation_xml:
|
|
296
|
-
return
|
|
297
|
-
notes_master_lst = (
|
|
298
|
-
f'<p:notesMasterIdLst><p:notesMasterId r:id="{notes_master_rid}"/>'
|
|
299
|
-
'</p:notesMasterIdLst>'
|
|
300
|
-
)
|
|
301
|
-
if '</p:sldMasterIdLst>' not in presentation_xml:
|
|
302
|
-
raise RuntimeError('presentation.xml is missing p:sldMasterIdLst')
|
|
303
|
-
presentation_xml = presentation_xml.replace(
|
|
304
|
-
'</p:sldMasterIdLst>',
|
|
305
|
-
'</p:sldMasterIdLst>' + notes_master_lst,
|
|
306
|
-
1,
|
|
307
|
-
)
|
|
308
|
-
presentation_path.write_text(presentation_xml, encoding='utf-8')
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
def _to_float(value: Any, default: float) -> float:
|
|
312
|
-
if value is None:
|
|
313
|
-
return default
|
|
314
|
-
try:
|
|
315
|
-
number = float(value)
|
|
316
|
-
except (TypeError, ValueError):
|
|
317
|
-
return default
|
|
318
|
-
return number if number >= 0 else default
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
def _slide_config(animation_config: dict[str, Any] | None, svg_stem: str) -> dict[str, Any]:
|
|
322
|
-
if not animation_config:
|
|
323
|
-
return {}
|
|
324
|
-
slides = _as_dict(animation_config.get('slides'))
|
|
325
|
-
return _as_dict(slides.get(svg_stem))
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
def _slide_transition_settings(
|
|
329
|
-
slide_cfg: dict[str, Any],
|
|
330
|
-
transition: str | None,
|
|
331
|
-
duration: float,
|
|
332
|
-
auto_advance: float | None,
|
|
333
|
-
cli_overrides: dict[str, bool],
|
|
334
|
-
) -> tuple[str | None, float, float | None]:
|
|
335
|
-
trans_cfg = _as_dict(slide_cfg.get('transition'))
|
|
336
|
-
effect = transition
|
|
337
|
-
if not cli_overrides.get('transition') and 'effect' in trans_cfg:
|
|
338
|
-
cfg_effect = str(trans_cfg.get('effect'))
|
|
339
|
-
effect = None if cfg_effect == 'none' else cfg_effect
|
|
340
|
-
if not cli_overrides.get('transition_duration'):
|
|
341
|
-
duration = _to_float(trans_cfg.get('duration'), duration)
|
|
342
|
-
if not cli_overrides.get('auto_advance') and 'auto_advance' in trans_cfg:
|
|
343
|
-
auto_advance = _to_float(trans_cfg.get('auto_advance'), auto_advance or 0)
|
|
344
|
-
return effect, duration, auto_advance
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
def _slide_animation_settings(
|
|
348
|
-
slide_cfg: dict[str, Any],
|
|
349
|
-
animation: str | None,
|
|
350
|
-
duration: float,
|
|
351
|
-
stagger: float,
|
|
352
|
-
trigger: str,
|
|
353
|
-
cli_overrides: dict[str, bool],
|
|
354
|
-
) -> tuple[str | None, float, float, str]:
|
|
355
|
-
anim_cfg = _as_dict(slide_cfg.get('animation'))
|
|
356
|
-
effect = animation
|
|
357
|
-
if not cli_overrides.get('animation') and 'effect' in anim_cfg:
|
|
358
|
-
cfg_effect = str(anim_cfg.get('effect'))
|
|
359
|
-
effect = None if cfg_effect == 'none' else cfg_effect
|
|
360
|
-
if not cli_overrides.get('animation_duration'):
|
|
361
|
-
duration = _to_float(anim_cfg.get('duration'), duration)
|
|
362
|
-
if not cli_overrides.get('animation_stagger'):
|
|
363
|
-
stagger = _to_float(anim_cfg.get('stagger'), stagger)
|
|
364
|
-
if not cli_overrides.get('animation_trigger') and anim_cfg.get('trigger'):
|
|
365
|
-
trigger = str(anim_cfg.get('trigger'))
|
|
366
|
-
return effect, duration, stagger, trigger
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
def _build_sequence_targets(
|
|
370
|
-
anim_targets: list[tuple[int, str]],
|
|
371
|
-
slide_cfg: dict[str, Any],
|
|
372
|
-
animation: str,
|
|
373
|
-
duration: float,
|
|
374
|
-
stagger: float,
|
|
375
|
-
mixed_animation_offset: int,
|
|
376
|
-
) -> tuple[list[tuple[int, int, str, float]], int]:
|
|
377
|
-
groups_cfg = _as_dict(slide_cfg.get('groups'))
|
|
378
|
-
ordered: list[tuple[int, int, int, str, dict[str, Any]]] = []
|
|
379
|
-
for idx, (sid, svg_id) in enumerate(anim_targets):
|
|
380
|
-
group_cfg = _as_dict(groups_cfg.get(svg_id))
|
|
381
|
-
if str(group_cfg.get('effect', '')).lower() == 'none':
|
|
382
|
-
continue
|
|
383
|
-
order_value = group_cfg.get('order')
|
|
384
|
-
try:
|
|
385
|
-
order = int(order_value)
|
|
386
|
-
has_order = 0
|
|
387
|
-
except (TypeError, ValueError):
|
|
388
|
-
order = idx
|
|
389
|
-
has_order = 1
|
|
390
|
-
group_entry = dict(group_cfg)
|
|
391
|
-
group_entry['_shape_id'] = sid
|
|
392
|
-
ordered.append((has_order, order, idx, svg_id, group_entry))
|
|
393
|
-
|
|
394
|
-
ordered.sort(key=lambda item: (item[0], item[1], item[2]))
|
|
395
|
-
|
|
396
|
-
seq_targets: list[tuple[int, int, str, float]] = []
|
|
397
|
-
for seq_idx, (_has_order, _order, _original_idx, _svg_id, group_cfg) in enumerate(ordered):
|
|
398
|
-
shape_id = int(group_cfg['_shape_id'])
|
|
399
|
-
raw_effect = group_cfg.get('effect')
|
|
400
|
-
if raw_effect in ('auto', 'mixed', 'random'):
|
|
401
|
-
effect = pick_animation_effect(
|
|
402
|
-
str(raw_effect), seq_idx, mixed_animation_offset, group_id=_svg_id,
|
|
403
|
-
)
|
|
404
|
-
else:
|
|
405
|
-
effect = str(raw_effect or pick_animation_effect(
|
|
406
|
-
animation, seq_idx, mixed_animation_offset, group_id=_svg_id,
|
|
407
|
-
))
|
|
408
|
-
item_duration = _to_float(group_cfg.get('duration'), duration)
|
|
409
|
-
delay_seconds = _to_float(
|
|
410
|
-
group_cfg.get('delay'),
|
|
411
|
-
0 if seq_idx == 0 else stagger,
|
|
412
|
-
)
|
|
413
|
-
seq_targets.append((shape_id, int(delay_seconds * 1000), effect, item_duration))
|
|
414
|
-
|
|
415
|
-
mixed_count = 0
|
|
416
|
-
if animation == 'mixed':
|
|
417
|
-
mixed_count = sum(1 for _target in seq_targets[1:])
|
|
418
|
-
elif animation == 'auto':
|
|
419
|
-
# 'auto' accumulates a cross-slide offset so the image pool and the
|
|
420
|
-
# unmatched-id fallback rotate as the deck advances. Single-effect
|
|
421
|
-
# semantic matches (title→fade, chart→wipe etc.) are unaffected
|
|
422
|
-
# because they ignore the offset.
|
|
423
|
-
mixed_count = len(seq_targets)
|
|
424
|
-
return seq_targets, mixed_count
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
def _prerender_legacy_pngs(
|
|
428
|
-
svg_files: list[Path],
|
|
429
|
-
media_dir: Path,
|
|
430
|
-
pixel_width: int,
|
|
431
|
-
pixel_height: int,
|
|
432
|
-
cache_dir: Path | None,
|
|
433
|
-
workers: int,
|
|
434
|
-
verbose: bool,
|
|
435
|
-
) -> dict[int, bool]:
|
|
436
|
-
"""Render every SVG→PNG into media_dir in parallel.
|
|
437
|
-
|
|
438
|
-
Returns {1-based slide index: success}. Falls back to sequential when
|
|
439
|
-
workers<=1 or len(svg_files)<=2.
|
|
440
|
-
"""
|
|
441
|
-
results: dict[int, bool] = {}
|
|
442
|
-
targets: list[tuple[int, Path, Path]] = [
|
|
443
|
-
(i, svg, media_dir / f'image{i}.png')
|
|
444
|
-
for i, svg in enumerate(svg_files, 1)
|
|
445
|
-
]
|
|
446
|
-
|
|
447
|
-
if workers <= 1 or len(targets) <= 2:
|
|
448
|
-
for i, svg, png in targets:
|
|
449
|
-
ok = convert_svg_to_png_cached(svg, png, pixel_width, pixel_height, cache_dir)
|
|
450
|
-
results[i] = ok
|
|
451
|
-
if verbose:
|
|
452
|
-
tag = 'cached/ok' if ok else 'failed'
|
|
453
|
-
print(f" [PNG {i}/{len(targets)}] {svg.name} - {tag}")
|
|
454
|
-
return results
|
|
455
|
-
|
|
456
|
-
with ProcessPoolExecutor(max_workers=workers) as pool:
|
|
457
|
-
future_map = {
|
|
458
|
-
pool.submit(
|
|
459
|
-
convert_svg_to_png_cached,
|
|
460
|
-
svg, png, pixel_width, pixel_height, cache_dir,
|
|
461
|
-
): (i, svg)
|
|
462
|
-
for i, svg, png in targets
|
|
463
|
-
}
|
|
464
|
-
done = 0
|
|
465
|
-
for future in as_completed(future_map):
|
|
466
|
-
i, svg = future_map[future]
|
|
467
|
-
try:
|
|
468
|
-
ok = future.result()
|
|
469
|
-
except Exception as exc:
|
|
470
|
-
ok = False
|
|
471
|
-
if verbose:
|
|
472
|
-
print(f" [PNG] {svg.name} - worker error: {exc}")
|
|
473
|
-
results[i] = ok
|
|
474
|
-
done += 1
|
|
475
|
-
if verbose:
|
|
476
|
-
tag = 'cached/ok' if ok else 'failed'
|
|
477
|
-
print(f" [PNG {done}/{len(targets)}] {svg.name} - {tag}")
|
|
478
|
-
|
|
479
|
-
return results
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
_REL_TARGET_RE = re.compile(r'<Relationship\b[^/]*?/>', re.DOTALL)
|
|
483
|
-
_TARGET_ATTR_RE = re.compile(r'Target="([^"]+)"')
|
|
484
|
-
_TARGET_MODE_EXT_RE = re.compile(r'TargetMode="External"')
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
def _verify_internal_rels_targets(extract_dir: Path) -> list[str]:
|
|
488
|
-
"""Return a list of dangling internal Targets across every .rels in the package.
|
|
489
|
-
|
|
490
|
-
Each entry is formatted as "<rels-path> -> <missing-target>". An empty list
|
|
491
|
-
means every internal Target resolves to a real file in the package.
|
|
492
|
-
"""
|
|
493
|
-
problems: list[str] = []
|
|
494
|
-
for rels_path in extract_dir.rglob('*.rels'):
|
|
495
|
-
rels_rel = rels_path.relative_to(extract_dir).as_posix()
|
|
496
|
-
# `_rels/foo.xml.rels` lives one level below its referent's directory;
|
|
497
|
-
# Targets resolve relative to the parent of that `_rels` folder.
|
|
498
|
-
base_dir = posixpath.dirname(posixpath.dirname(rels_rel))
|
|
499
|
-
content = rels_path.read_text(encoding='utf-8')
|
|
500
|
-
for match in _REL_TARGET_RE.finditer(content):
|
|
501
|
-
element = match.group(0)
|
|
502
|
-
if _TARGET_MODE_EXT_RE.search(element):
|
|
503
|
-
continue
|
|
504
|
-
target_match = _TARGET_ATTR_RE.search(element)
|
|
505
|
-
if not target_match:
|
|
506
|
-
continue
|
|
507
|
-
target = target_match.group(1)
|
|
508
|
-
if target.startswith(('http://', 'https://', 'mailto:')):
|
|
509
|
-
continue
|
|
510
|
-
resolved = posixpath.normpath(posixpath.join(base_dir, target)) if base_dir else posixpath.normpath(target)
|
|
511
|
-
if not (extract_dir / resolved).exists():
|
|
512
|
-
problems.append(f'{rels_rel} -> {resolved}')
|
|
513
|
-
return problems
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
def _presentation_format(width: float, height: float) -> str:
|
|
517
|
-
"""Map the slide aspect ratio to PowerPoint's PresentationFormat label.
|
|
518
|
-
Non-standard ratios (square, portrait, banner crops) report 'Custom'.
|
|
519
|
-
"""
|
|
520
|
-
if width <= 0 or height <= 0:
|
|
521
|
-
return 'Custom'
|
|
522
|
-
ratio = width / height
|
|
523
|
-
for target, label in (
|
|
524
|
-
(4 / 3, 'On-screen Show (4:3)'),
|
|
525
|
-
(16 / 9, 'On-screen Show (16:9)'),
|
|
526
|
-
(16 / 10, 'On-screen Show (16:10)'),
|
|
527
|
-
):
|
|
528
|
-
if abs(ratio - target) < 0.02:
|
|
529
|
-
return label
|
|
530
|
-
return 'Custom'
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
def _stamp_docprops(
|
|
534
|
-
extract_dir: Path,
|
|
535
|
-
slide_count: int,
|
|
536
|
-
pres_format: str,
|
|
537
|
-
meta: dict[str, Any] | None = None,
|
|
538
|
-
) -> None:
|
|
539
|
-
"""Overwrite the misleading python-pptx default metadata with accurate
|
|
540
|
-
values. Factual fields (slide count, export timestamp, presentation format,
|
|
541
|
-
application) are always machine-derived. Authored fields — including the
|
|
542
|
-
title — come solely from an optional per-project `metadata.json`
|
|
543
|
-
(`meta`); whatever it omits stays blank. `lastModifiedBy` follows
|
|
544
|
-
`creator` rather than ever carrying the base template's author or a tool
|
|
545
|
-
name. No field is guessed from slide content: a blank title is preferable
|
|
546
|
-
to an unreliable heuristic pick.
|
|
547
|
-
"""
|
|
548
|
-
meta = meta or {}
|
|
549
|
-
|
|
550
|
-
def field(key: str, default: str = '') -> str:
|
|
551
|
-
value = meta.get(key)
|
|
552
|
-
return value.strip() if isinstance(value, str) and value.strip() else default
|
|
553
|
-
|
|
554
|
-
title = field('title')
|
|
555
|
-
creator = field('creator')
|
|
556
|
-
|
|
557
|
-
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
558
|
-
|
|
559
|
-
core_path = extract_dir / 'docProps' / 'core.xml'
|
|
560
|
-
if core_path.exists():
|
|
561
|
-
core_path.write_text(
|
|
562
|
-
"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n"
|
|
563
|
-
'<cp:coreProperties '
|
|
564
|
-
'xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" '
|
|
565
|
-
'xmlns:dc="http://purl.org/dc/elements/1.1/" '
|
|
566
|
-
'xmlns:dcterms="http://purl.org/dc/terms/" '
|
|
567
|
-
'xmlns:dcmitype="http://purl.org/dc/dcmitype/" '
|
|
568
|
-
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
|
|
569
|
-
f'<dc:title>{escape(title)}</dc:title>'
|
|
570
|
-
f'<dc:subject>{escape(field("subject"))}</dc:subject>'
|
|
571
|
-
f'<dc:creator>{escape(creator)}</dc:creator>'
|
|
572
|
-
f'<cp:keywords>{escape(field("keywords"))}</cp:keywords>'
|
|
573
|
-
f'<dc:description>{escape(field("description"))}</dc:description>'
|
|
574
|
-
f'<dc:language>{escape(field("language"))}</dc:language>'
|
|
575
|
-
f'<cp:lastModifiedBy>{escape(creator)}</cp:lastModifiedBy>'
|
|
576
|
-
'<cp:revision>1</cp:revision>'
|
|
577
|
-
f'<dcterms:created xsi:type="dcterms:W3CDTF">{now}</dcterms:created>'
|
|
578
|
-
f'<dcterms:modified xsi:type="dcterms:W3CDTF">{now}</dcterms:modified>'
|
|
579
|
-
f'<cp:category>{escape(field("category"))}</cp:category>'
|
|
580
|
-
f'<cp:contentStatus>{escape(field("contentStatus"))}</cp:contentStatus>'
|
|
581
|
-
'</cp:coreProperties>',
|
|
582
|
-
encoding='utf-8',
|
|
583
|
-
)
|
|
584
|
-
|
|
585
|
-
app_path = extract_dir / 'docProps' / 'app.xml'
|
|
586
|
-
if app_path.exists():
|
|
587
|
-
app = app_path.read_text(encoding='utf-8')
|
|
588
|
-
app = re.sub(r'<Slides>.*?</Slides>', f'<Slides>{slide_count}</Slides>', app)
|
|
589
|
-
app = re.sub(
|
|
590
|
-
r'<Company>.*?</Company>',
|
|
591
|
-
f'<Company>{escape(field("company"))}</Company>',
|
|
592
|
-
app,
|
|
593
|
-
)
|
|
594
|
-
app = re.sub(
|
|
595
|
-
r'<Manager>.*?</Manager>',
|
|
596
|
-
f'<Manager>{escape(field("manager"))}</Manager>',
|
|
597
|
-
app,
|
|
598
|
-
)
|
|
599
|
-
app = re.sub(
|
|
600
|
-
r'<Application>.*?</Application>',
|
|
601
|
-
'<Application>Microsoft Office PowerPoint</Application>',
|
|
602
|
-
app,
|
|
603
|
-
)
|
|
604
|
-
app = re.sub(
|
|
605
|
-
r'<PresentationFormat>.*?</PresentationFormat>',
|
|
606
|
-
f'<PresentationFormat>{escape(pres_format)}</PresentationFormat>',
|
|
607
|
-
app,
|
|
608
|
-
)
|
|
609
|
-
app_path.write_text(app, encoding='utf-8')
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
def create_pptx_with_native_svg(
|
|
613
|
-
svg_files: list[Path],
|
|
614
|
-
output_path: Path,
|
|
615
|
-
canvas_format: str | None = None,
|
|
616
|
-
verbose: bool = True,
|
|
617
|
-
transition: str | None = 'fade',
|
|
618
|
-
transition_duration: float = 0.5,
|
|
619
|
-
auto_advance: float | None = None,
|
|
620
|
-
use_compat_mode: bool = True,
|
|
621
|
-
notes: dict[str, str] | None = None,
|
|
622
|
-
enable_notes: bool = True,
|
|
623
|
-
use_native_shapes: bool = False,
|
|
624
|
-
animation: str | None = None,
|
|
625
|
-
animation_duration: float = 0.4,
|
|
626
|
-
animation_stagger: float = 0.5,
|
|
627
|
-
animation_trigger: str = 'after-previous',
|
|
628
|
-
animation_config: dict[str, Any] | None = None,
|
|
629
|
-
animation_cli_overrides: dict[str, bool] | None = None,
|
|
630
|
-
narration_audio: dict[str, Path] | None = None,
|
|
631
|
-
use_narration_timings: bool = False,
|
|
632
|
-
narration_padding: float = 0.5,
|
|
633
|
-
cache_dir: Path | None = None,
|
|
634
|
-
workers: int | None = None,
|
|
635
|
-
merge_paragraphs: bool = True,
|
|
636
|
-
image_optimize: bool = True,
|
|
637
|
-
image_max_dimension: int | None = 2560,
|
|
638
|
-
image_sizing: str = 'cap',
|
|
639
|
-
image_scale: float = 2.0,
|
|
640
|
-
image_quality: int = 85,
|
|
641
|
-
native_objects: bool = False,
|
|
642
|
-
conversion_trace_path: Path | None = None,
|
|
643
|
-
doc_metadata: dict[str, Any] | None = None,
|
|
644
|
-
) -> bool:
|
|
645
|
-
"""Create a PPTX file with native SVG.
|
|
646
|
-
|
|
647
|
-
Args:
|
|
648
|
-
svg_files: List of SVG files.
|
|
649
|
-
output_path: Output PPTX path.
|
|
650
|
-
canvas_format: Canvas format key.
|
|
651
|
-
verbose: Whether to output detailed information.
|
|
652
|
-
transition: Transition effect name.
|
|
653
|
-
transition_duration: Transition duration in seconds.
|
|
654
|
-
auto_advance: Auto-advance interval in seconds.
|
|
655
|
-
use_compat_mode: Use Office compatibility mode (PNG + SVG dual format).
|
|
656
|
-
notes: Notes dict, key is SVG stem, value is notes content.
|
|
657
|
-
enable_notes: Whether to enable notes embedding.
|
|
658
|
-
use_native_shapes: Convert SVG to native DrawingML shapes.
|
|
659
|
-
animation: Per-element entrance animation mode (single effect name,
|
|
660
|
-
'mixed', 'random', or None to disable). Native shapes mode only.
|
|
661
|
-
animation_duration: Per-element entrance duration in seconds.
|
|
662
|
-
animation_stagger: Delay between elements in `after-previous`
|
|
663
|
-
trigger mode (seconds). Ignored otherwise.
|
|
664
|
-
animation_trigger: PowerPoint Start mode — `'after-previous'` (default),
|
|
665
|
-
`'on-click'`, or `'with-previous'`.
|
|
666
|
-
animation_config: Optional sidecar overrides loaded from animations.json.
|
|
667
|
-
animation_cli_overrides: Flags indicating explicit CLI overrides.
|
|
668
|
-
narration_audio: Optional dict mapping SVG stem to narration audio file.
|
|
669
|
-
use_narration_timings: Whether to set slide auto-advance from audio duration.
|
|
670
|
-
narration_padding: Extra seconds added after each narration before advancing.
|
|
671
|
-
image_optimize: Whether native export downscales oversized raster images.
|
|
672
|
-
image_max_dimension: Maximum optimized image dimension in pixels.
|
|
673
|
-
image_sizing: `cap` only limits source dimensions; `display` sizes
|
|
674
|
-
from rendered SVG boxes.
|
|
675
|
-
image_scale: Target image pixels per SVG display pixel.
|
|
676
|
-
image_quality: JPEG quality used for opaque optimized rasters.
|
|
677
|
-
native_objects: Convert explicit `data-pptx-native` table/chart
|
|
678
|
-
markers to native PowerPoint objects. Default off.
|
|
679
|
-
conversion_trace_path: Optional JSON path for native conversion diagnostics.
|
|
680
|
-
|
|
681
|
-
Returns:
|
|
682
|
-
Whether all slides were successfully created.
|
|
683
|
-
"""
|
|
684
|
-
if not svg_files:
|
|
685
|
-
print("Error: No SVG files found")
|
|
686
|
-
return False
|
|
687
|
-
|
|
688
|
-
# Native shapes mode takes priority over compat mode
|
|
689
|
-
if use_native_shapes:
|
|
690
|
-
use_compat_mode = False
|
|
691
|
-
|
|
692
|
-
# Check compatibility mode dependencies
|
|
693
|
-
renderer_name, renderer_status, renderer_hint = get_png_renderer_info()
|
|
694
|
-
if not use_native_shapes and use_compat_mode and PNG_RENDERER is None:
|
|
695
|
-
print("Warning: No PNG rendering library installed, cannot use compatibility mode")
|
|
696
|
-
print(f" {renderer_hint}")
|
|
697
|
-
print(" Will use pure SVG mode (may not display in Office LTSC 2021 and similar versions)")
|
|
698
|
-
use_compat_mode = False
|
|
699
|
-
|
|
700
|
-
# Auto-detect canvas format or get dimensions from viewBox
|
|
701
|
-
custom_pixels: tuple[int, int] | None = None
|
|
702
|
-
if canvas_format is None:
|
|
703
|
-
canvas_format = detect_format_from_svg(svg_files[0])
|
|
704
|
-
if canvas_format and verbose:
|
|
705
|
-
format_name = CANVAS_FORMATS.get(canvas_format, {}).get('name', canvas_format)
|
|
706
|
-
print(f" Detected canvas format: {format_name}")
|
|
707
|
-
|
|
708
|
-
if canvas_format is None:
|
|
709
|
-
custom_pixels = get_viewbox_dimensions(svg_files[0])
|
|
710
|
-
if custom_pixels and verbose:
|
|
711
|
-
print(f" Using SVG viewBox dimensions: {custom_pixels[0]} x {custom_pixels[1]} px")
|
|
712
|
-
|
|
713
|
-
if canvas_format is None and custom_pixels is None:
|
|
714
|
-
canvas_format = 'ppt169'
|
|
715
|
-
if verbose:
|
|
716
|
-
print(f" Using default format: PPT 16:9")
|
|
717
|
-
|
|
718
|
-
width_emu, height_emu = get_slide_dimensions(canvas_format or 'ppt169', custom_pixels)
|
|
719
|
-
pixel_width, pixel_height = get_pixel_dimensions(canvas_format or 'ppt169', custom_pixels)
|
|
720
|
-
|
|
721
|
-
if verbose:
|
|
722
|
-
print(f" Slide dimensions: {pixel_width} x {pixel_height} px")
|
|
723
|
-
print(f" SVG file count: {len(svg_files)}")
|
|
724
|
-
if use_native_shapes:
|
|
725
|
-
print(f" Mode: Native DrawingML shapes (directly editable)")
|
|
726
|
-
print(
|
|
727
|
-
" Native table/chart objects: "
|
|
728
|
-
f"{'Enabled' if native_objects else 'Disabled'}"
|
|
729
|
-
)
|
|
730
|
-
if image_optimize:
|
|
731
|
-
if image_sizing == 'display':
|
|
732
|
-
image_mode = (
|
|
733
|
-
f"display scale {image_scale:g}, "
|
|
734
|
-
f"max {image_max_dimension or 'unlimited'} px"
|
|
735
|
-
)
|
|
736
|
-
else:
|
|
737
|
-
image_mode = f"cap max {image_max_dimension or 'unlimited'} px"
|
|
738
|
-
print(
|
|
739
|
-
" Image optimization: Enabled "
|
|
740
|
-
f"({image_mode}, JPEG q{image_quality})"
|
|
741
|
-
)
|
|
742
|
-
else:
|
|
743
|
-
print(" Image optimization: Disabled")
|
|
744
|
-
elif use_compat_mode:
|
|
745
|
-
print(f" Compatibility mode: Enabled (PNG + SVG dual format)")
|
|
746
|
-
print(f" PNG renderer: {renderer_name} {renderer_status}")
|
|
747
|
-
else:
|
|
748
|
-
print(f" Compatibility mode: Disabled (pure SVG)")
|
|
749
|
-
if transition:
|
|
750
|
-
trans_name = TRANSITIONS.get(transition, {}).get('name', transition) if TRANSITIONS else transition
|
|
751
|
-
print(f" Transition effect: {trans_name}")
|
|
752
|
-
if enable_notes and notes:
|
|
753
|
-
print(f" Speaker notes: {len(notes)} page(s)")
|
|
754
|
-
elif enable_notes:
|
|
755
|
-
print(f" Speaker notes: Enabled (no notes files found)")
|
|
756
|
-
else:
|
|
757
|
-
print(f" Speaker notes: Disabled")
|
|
758
|
-
print()
|
|
759
|
-
|
|
760
|
-
animation_cli_overrides = animation_cli_overrides or {}
|
|
761
|
-
|
|
762
|
-
temp_dir = _create_writable_work_dir(output_path)
|
|
763
|
-
|
|
764
|
-
try:
|
|
765
|
-
# Create base PPTX with python-pptx
|
|
766
|
-
prs = Presentation()
|
|
767
|
-
prs.slide_width = width_emu
|
|
768
|
-
prs.slide_height = height_emu
|
|
769
|
-
|
|
770
|
-
blank_layout = prs.slide_layouts[6]
|
|
771
|
-
for _ in svg_files:
|
|
772
|
-
prs.slides.add_slide(blank_layout)
|
|
773
|
-
|
|
774
|
-
base_pptx = temp_dir / 'base.pptx'
|
|
775
|
-
prs.save(str(base_pptx))
|
|
776
|
-
|
|
777
|
-
# Extract PPTX
|
|
778
|
-
extract_dir = temp_dir / 'pptx_content'
|
|
779
|
-
with zipfile.ZipFile(base_pptx, 'r') as zf:
|
|
780
|
-
zf.extractall(extract_dir)
|
|
781
|
-
|
|
782
|
-
media_dir = extract_dir / 'ppt' / 'media'
|
|
783
|
-
media_dir.mkdir(exist_ok=True)
|
|
784
|
-
|
|
785
|
-
prerender_results: dict[int, bool] | None = None
|
|
786
|
-
if not use_native_shapes and use_compat_mode and PNG_RENDERER is not None:
|
|
787
|
-
if workers is None:
|
|
788
|
-
resolved_workers = min(os.cpu_count() or 2, len(svg_files), 8)
|
|
789
|
-
else:
|
|
790
|
-
resolved_workers = max(0, workers)
|
|
791
|
-
if verbose:
|
|
792
|
-
cache_label = str(cache_dir) if cache_dir else 'disabled'
|
|
793
|
-
mode = f'parallel x{resolved_workers}' if resolved_workers > 1 else 'sequential'
|
|
794
|
-
print(f" Pre-rendering PNGs ({mode}, cache: {cache_label})")
|
|
795
|
-
prerender_results = _prerender_legacy_pngs(
|
|
796
|
-
svg_files, media_dir, pixel_width, pixel_height,
|
|
797
|
-
cache_dir, resolved_workers, verbose,
|
|
798
|
-
)
|
|
799
|
-
if verbose:
|
|
800
|
-
print()
|
|
801
|
-
|
|
802
|
-
success_count = 0
|
|
803
|
-
has_any_image = False
|
|
804
|
-
media_cache: dict[tuple[str, str], str] = {}
|
|
805
|
-
image_exts_used: set[str] = set()
|
|
806
|
-
package_exts_used: set[str] = set()
|
|
807
|
-
package_content_overrides: dict[str, str] = {}
|
|
808
|
-
notes_slides_created: set[int] = set()
|
|
809
|
-
narration_slides_created: set[int] = set()
|
|
810
|
-
audio_exts_used: set[str] = set()
|
|
811
|
-
mixed_animation_offset = 0
|
|
812
|
-
conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else None
|
|
813
|
-
|
|
814
|
-
for i, svg_path in enumerate(svg_files, 1):
|
|
815
|
-
slide_num = i
|
|
816
|
-
|
|
817
|
-
try:
|
|
818
|
-
# ---- Native shapes mode ----
|
|
819
|
-
if use_native_shapes:
|
|
820
|
-
slide_cfg = _slide_config(animation_config, svg_path.stem)
|
|
821
|
-
(
|
|
822
|
-
slide_xml,
|
|
823
|
-
media_files_dict,
|
|
824
|
-
rel_entries,
|
|
825
|
-
anim_targets,
|
|
826
|
-
package_files_dict,
|
|
827
|
-
content_type_overrides,
|
|
828
|
-
) = (
|
|
829
|
-
convert_svg_to_slide_shapes(
|
|
830
|
-
svg_path, slide_num=slide_num, verbose=verbose,
|
|
831
|
-
merge_paragraphs=merge_paragraphs,
|
|
832
|
-
image_optimize=image_optimize,
|
|
833
|
-
image_max_dimension=image_max_dimension,
|
|
834
|
-
image_sizing=image_sizing,
|
|
835
|
-
image_scale=image_scale,
|
|
836
|
-
image_quality=image_quality,
|
|
837
|
-
native_objects=native_objects,
|
|
838
|
-
trace_out=conversion_trace,
|
|
839
|
-
)
|
|
840
|
-
)
|
|
841
|
-
slide_transition, slide_transition_duration, slide_auto_advance = (
|
|
842
|
-
_slide_transition_settings(
|
|
843
|
-
slide_cfg,
|
|
844
|
-
transition,
|
|
845
|
-
transition_duration,
|
|
846
|
-
auto_advance,
|
|
847
|
-
animation_cli_overrides,
|
|
848
|
-
)
|
|
849
|
-
)
|
|
850
|
-
(
|
|
851
|
-
slide_animation,
|
|
852
|
-
slide_animation_duration,
|
|
853
|
-
slide_animation_stagger,
|
|
854
|
-
slide_animation_trigger,
|
|
855
|
-
) = _slide_animation_settings(
|
|
856
|
-
slide_cfg,
|
|
857
|
-
animation,
|
|
858
|
-
animation_duration,
|
|
859
|
-
animation_stagger,
|
|
860
|
-
animation_trigger,
|
|
861
|
-
animation_cli_overrides,
|
|
862
|
-
)
|
|
863
|
-
|
|
864
|
-
# Order matters: OOXML schema requires <p:transition>
|
|
865
|
-
# to precede <p:timing> inside <p:sld>. Both use the same
|
|
866
|
-
# </p:sld> string-replace anchor, so transition must be
|
|
867
|
-
# injected first and timing second.
|
|
868
|
-
if slide_transition and ANIMATIONS_AVAILABLE and create_transition_xml:
|
|
869
|
-
transition_xml = '\n' + create_transition_xml(
|
|
870
|
-
effect=slide_transition,
|
|
871
|
-
duration=slide_transition_duration,
|
|
872
|
-
advance_after=slide_auto_advance,
|
|
873
|
-
)
|
|
874
|
-
slide_xml = slide_xml.replace(
|
|
875
|
-
'</p:sld>',
|
|
876
|
-
transition_xml + '\n</p:sld>',
|
|
877
|
-
)
|
|
878
|
-
|
|
879
|
-
if (slide_animation and slide_animation != 'none'
|
|
880
|
-
and create_sequence_timing_xml
|
|
881
|
-
and pick_animation_effect
|
|
882
|
-
and anim_targets):
|
|
883
|
-
seq_targets, mixed_count = _build_sequence_targets(
|
|
884
|
-
anim_targets,
|
|
885
|
-
slide_cfg,
|
|
886
|
-
slide_animation,
|
|
887
|
-
slide_animation_duration,
|
|
888
|
-
slide_animation_stagger,
|
|
889
|
-
mixed_animation_offset,
|
|
890
|
-
)
|
|
891
|
-
if slide_animation in ('mixed', 'auto'):
|
|
892
|
-
mixed_animation_offset += mixed_count
|
|
893
|
-
timing_xml = '\n' + create_sequence_timing_xml(
|
|
894
|
-
seq_targets, duration=slide_animation_duration,
|
|
895
|
-
trigger=slide_animation_trigger,
|
|
896
|
-
)
|
|
897
|
-
slide_xml = slide_xml.replace(
|
|
898
|
-
'</p:sld>',
|
|
899
|
-
timing_xml + '\n</p:sld>',
|
|
900
|
-
)
|
|
901
|
-
|
|
902
|
-
# Write slide XML
|
|
903
|
-
slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
|
|
904
|
-
with open(slide_xml_path, 'w', encoding='utf-8') as f:
|
|
905
|
-
f.write(slide_xml)
|
|
906
|
-
|
|
907
|
-
# Write media files
|
|
908
|
-
media_name_map: dict[str, str] = {}
|
|
909
|
-
for media_name, media_data in media_files_dict.items():
|
|
910
|
-
ext = media_name.rsplit('.', 1)[-1].lower()
|
|
911
|
-
media_hash = hashlib.sha256(media_data).hexdigest()
|
|
912
|
-
cache_key = (ext, media_hash)
|
|
913
|
-
cached_name = media_cache.get(cache_key)
|
|
914
|
-
|
|
915
|
-
if cached_name is None:
|
|
916
|
-
cached_name = f'image_{media_hash[:16]}.{ext}'
|
|
917
|
-
media_cache[cache_key] = cached_name
|
|
918
|
-
with open(media_dir / cached_name, 'wb') as f:
|
|
919
|
-
f.write(media_data)
|
|
920
|
-
|
|
921
|
-
media_name_map[media_name] = cached_name
|
|
922
|
-
|
|
923
|
-
for rel in rel_entries:
|
|
924
|
-
target = rel.get('target', '')
|
|
925
|
-
if not target.startswith('../media/'):
|
|
926
|
-
continue
|
|
927
|
-
media_name = target.split('../media/', 1)[1]
|
|
928
|
-
mapped_name = media_name_map.get(media_name)
|
|
929
|
-
if mapped_name:
|
|
930
|
-
rel['target'] = f'../media/{mapped_name}'
|
|
931
|
-
|
|
932
|
-
# Write non-media OOXML package parts produced by native
|
|
933
|
-
# object converters, e.g. chart XML, chart rels, and
|
|
934
|
-
# embedded workbooks.
|
|
935
|
-
for part_name, part_data in package_files_dict.items():
|
|
936
|
-
package_path = extract_dir / part_name
|
|
937
|
-
package_path.parent.mkdir(parents=True, exist_ok=True)
|
|
938
|
-
with open(package_path, 'wb') as f:
|
|
939
|
-
f.write(part_data)
|
|
940
|
-
suffix = package_path.suffix.lstrip('.').lower()
|
|
941
|
-
if suffix:
|
|
942
|
-
package_exts_used.add(suffix)
|
|
943
|
-
package_content_overrides.update(content_type_overrides)
|
|
944
|
-
|
|
945
|
-
# Build relationships XML
|
|
946
|
-
rels_dir = extract_dir / 'ppt' / 'slides' / '_rels'
|
|
947
|
-
rels_dir.mkdir(exist_ok=True)
|
|
948
|
-
rels_path = rels_dir / f'slide{slide_num}.xml.rels'
|
|
949
|
-
|
|
950
|
-
extra_rels = ''
|
|
951
|
-
for rel in rel_entries:
|
|
952
|
-
extra_rels += (
|
|
953
|
-
f'\n <Relationship Id="{rel["id"]}" '
|
|
954
|
-
f'Type="{rel["type"]}" Target="{rel["target"]}"/>'
|
|
955
|
-
)
|
|
956
|
-
|
|
957
|
-
rels_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
958
|
-
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
959
|
-
<Relationship Id="rId1"
|
|
960
|
-
Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
|
|
961
|
-
Target="../slideLayouts/slideLayout1.xml"/>{extra_rels}
|
|
962
|
-
</Relationships>'''
|
|
963
|
-
with open(rels_path, 'w', encoding='utf-8') as f:
|
|
964
|
-
f.write(rels_xml)
|
|
965
|
-
|
|
966
|
-
# Track image formats for Content_Types
|
|
967
|
-
for media_name in media_name_map.values():
|
|
968
|
-
ext = media_name.rsplit('.', 1)[-1].lower()
|
|
969
|
-
_content_type_for_extension(ext)
|
|
970
|
-
image_exts_used.add(ext)
|
|
971
|
-
has_any_image = True
|
|
972
|
-
|
|
973
|
-
# ---- Legacy SVG embedding mode ----
|
|
974
|
-
else:
|
|
975
|
-
slide_cfg = _slide_config(animation_config, svg_path.stem)
|
|
976
|
-
slide_transition, slide_transition_duration, slide_auto_advance = (
|
|
977
|
-
_slide_transition_settings(
|
|
978
|
-
slide_cfg,
|
|
979
|
-
transition,
|
|
980
|
-
transition_duration,
|
|
981
|
-
auto_advance,
|
|
982
|
-
animation_cli_overrides,
|
|
983
|
-
)
|
|
984
|
-
)
|
|
985
|
-
svg_filename = f'image{i}.svg'
|
|
986
|
-
png_filename = f'image{i}.png'
|
|
987
|
-
png_rid = 'rId2'
|
|
988
|
-
svg_rid = 'rId3' if use_compat_mode else 'rId2'
|
|
989
|
-
|
|
990
|
-
shutil.copy(svg_path, media_dir / svg_filename)
|
|
991
|
-
|
|
992
|
-
slide_has_png = False
|
|
993
|
-
if use_compat_mode:
|
|
994
|
-
if prerender_results is not None:
|
|
995
|
-
png_success = prerender_results.get(i, False)
|
|
996
|
-
else:
|
|
997
|
-
png_path = media_dir / png_filename
|
|
998
|
-
png_success = convert_svg_to_png(
|
|
999
|
-
svg_path, png_path,
|
|
1000
|
-
width=pixel_width, height=pixel_height,
|
|
1001
|
-
)
|
|
1002
|
-
if png_success:
|
|
1003
|
-
slide_has_png = True
|
|
1004
|
-
has_any_image = True
|
|
1005
|
-
image_exts_used.add('png')
|
|
1006
|
-
else:
|
|
1007
|
-
if verbose:
|
|
1008
|
-
print(
|
|
1009
|
-
f" [{i}/{len(svg_files)}] {svg_path.name} - "
|
|
1010
|
-
"PNG generation failed, using pure SVG"
|
|
1011
|
-
)
|
|
1012
|
-
svg_rid = 'rId2'
|
|
1013
|
-
|
|
1014
|
-
slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
|
|
1015
|
-
slide_xml = create_slide_xml_with_svg(
|
|
1016
|
-
slide_num,
|
|
1017
|
-
png_rid=png_rid, svg_rid=svg_rid,
|
|
1018
|
-
width_emu=width_emu, height_emu=height_emu,
|
|
1019
|
-
transition=slide_transition,
|
|
1020
|
-
transition_duration=slide_transition_duration,
|
|
1021
|
-
auto_advance=slide_auto_advance,
|
|
1022
|
-
use_compat_mode=(use_compat_mode and slide_has_png),
|
|
1023
|
-
)
|
|
1024
|
-
with open(slide_xml_path, 'w', encoding='utf-8') as f:
|
|
1025
|
-
f.write(slide_xml)
|
|
1026
|
-
|
|
1027
|
-
rels_dir = extract_dir / 'ppt' / 'slides' / '_rels'
|
|
1028
|
-
rels_dir.mkdir(exist_ok=True)
|
|
1029
|
-
rels_path = rels_dir / f'slide{slide_num}.xml.rels'
|
|
1030
|
-
rels_xml = create_slide_rels_xml(
|
|
1031
|
-
png_rid=png_rid, png_filename=png_filename,
|
|
1032
|
-
svg_rid=svg_rid, svg_filename=svg_filename,
|
|
1033
|
-
use_compat_mode=(use_compat_mode and slide_has_png),
|
|
1034
|
-
)
|
|
1035
|
-
with open(rels_path, 'w', encoding='utf-8') as f:
|
|
1036
|
-
f.write(rels_xml)
|
|
1037
|
-
|
|
1038
|
-
# --- Process notes (shared between native and legacy mode) ---
|
|
1039
|
-
notes_content = ''
|
|
1040
|
-
if enable_notes:
|
|
1041
|
-
svg_stem = svg_path.stem
|
|
1042
|
-
notes_content = notes.get(svg_stem, '') if notes else ''
|
|
1043
|
-
notes_text = markdown_to_plain_text(notes_content) if notes_content else ''
|
|
1044
|
-
if notes_text:
|
|
1045
|
-
_ensure_notes_master(extract_dir)
|
|
1046
|
-
|
|
1047
|
-
notes_slides_dir = extract_dir / 'ppt' / 'notesSlides'
|
|
1048
|
-
notes_slides_dir.mkdir(exist_ok=True)
|
|
1049
|
-
|
|
1050
|
-
notes_xml_path = notes_slides_dir / f'notesSlide{slide_num}.xml'
|
|
1051
|
-
notes_xml = create_notes_slide_xml(slide_num, notes_text)
|
|
1052
|
-
with open(notes_xml_path, 'w', encoding='utf-8') as f:
|
|
1053
|
-
f.write(notes_xml)
|
|
1054
|
-
|
|
1055
|
-
notes_rels_dir = notes_slides_dir / '_rels'
|
|
1056
|
-
notes_rels_dir.mkdir(exist_ok=True)
|
|
1057
|
-
notes_rels_path = notes_rels_dir / f'notesSlide{slide_num}.xml.rels'
|
|
1058
|
-
notes_rels_xml = create_notes_slide_rels_xml(slide_num)
|
|
1059
|
-
with open(notes_rels_path, 'w', encoding='utf-8') as f:
|
|
1060
|
-
f.write(notes_rels_xml)
|
|
1061
|
-
|
|
1062
|
-
_append_relationship(
|
|
1063
|
-
rels_path,
|
|
1064
|
-
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide',
|
|
1065
|
-
f'../notesSlides/notesSlide{slide_num}.xml',
|
|
1066
|
-
)
|
|
1067
|
-
notes_slides_created.add(slide_num)
|
|
1068
|
-
|
|
1069
|
-
# --- Process narration audio (shared between native and legacy mode) ---
|
|
1070
|
-
svg_stem = svg_path.stem
|
|
1071
|
-
audio_path = narration_audio.get(svg_stem) if narration_audio else None
|
|
1072
|
-
if audio_path:
|
|
1073
|
-
slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
|
|
1074
|
-
rels_path = extract_dir / 'ppt' / 'slides' / '_rels' / f'slide{slide_num}.xml.rels'
|
|
1075
|
-
|
|
1076
|
-
ext = audio_path.suffix.lower()
|
|
1077
|
-
media_name = f'narration{slide_num}{ext}'
|
|
1078
|
-
shutil.copy2(audio_path, media_dir / media_name)
|
|
1079
|
-
audio_exts_used.add(ext)
|
|
1080
|
-
|
|
1081
|
-
poster_name = 'narration_poster.png'
|
|
1082
|
-
poster_path = media_dir / poster_name
|
|
1083
|
-
if not poster_path.exists():
|
|
1084
|
-
poster_path.write_bytes(AUDIO_MARKER_PNG_BYTES)
|
|
1085
|
-
has_any_image = True
|
|
1086
|
-
image_exts_used.add('png')
|
|
1087
|
-
|
|
1088
|
-
media_rid = _append_relationship(
|
|
1089
|
-
rels_path,
|
|
1090
|
-
MEDIA_REL_TYPE,
|
|
1091
|
-
f'../media/{media_name}',
|
|
1092
|
-
)
|
|
1093
|
-
audio_rid = _append_relationship(
|
|
1094
|
-
rels_path,
|
|
1095
|
-
AUDIO_REL_TYPE,
|
|
1096
|
-
f'../media/{media_name}',
|
|
1097
|
-
)
|
|
1098
|
-
poster_rid = _append_relationship(
|
|
1099
|
-
rels_path,
|
|
1100
|
-
IMAGE_REL_TYPE,
|
|
1101
|
-
f'../media/{poster_name}',
|
|
1102
|
-
)
|
|
1103
|
-
|
|
1104
|
-
slide_xml = slide_xml_path.read_text(encoding='utf-8')
|
|
1105
|
-
narration_shape_id = next_shape_id(slide_xml)
|
|
1106
|
-
slide_xml = inject_narration(
|
|
1107
|
-
slide_xml,
|
|
1108
|
-
shape_id=narration_shape_id,
|
|
1109
|
-
shape_name=media_name,
|
|
1110
|
-
audio_rid=audio_rid,
|
|
1111
|
-
media_rid=media_rid,
|
|
1112
|
-
poster_rid=poster_rid,
|
|
1113
|
-
)
|
|
1114
|
-
|
|
1115
|
-
if use_narration_timings:
|
|
1116
|
-
duration = probe_audio_duration(audio_path)
|
|
1117
|
-
if duration is None:
|
|
1118
|
-
raise RuntimeError(
|
|
1119
|
-
f"Unable to read narration duration with ffprobe: {audio_path}"
|
|
1120
|
-
)
|
|
1121
|
-
slide_xml = apply_recorded_timing(
|
|
1122
|
-
slide_xml,
|
|
1123
|
-
advance_after=duration + narration_padding,
|
|
1124
|
-
transition_duration=slide_transition_duration,
|
|
1125
|
-
transition_effect=slide_transition or 'fade',
|
|
1126
|
-
)
|
|
1127
|
-
slide_xml_path.write_text(slide_xml, encoding='utf-8')
|
|
1128
|
-
narration_slides_created.add(slide_num)
|
|
1129
|
-
|
|
1130
|
-
if verbose:
|
|
1131
|
-
if use_native_shapes:
|
|
1132
|
-
mode_str = " (Native)"
|
|
1133
|
-
elif use_compat_mode and not use_native_shapes:
|
|
1134
|
-
mode_str = " (PNG+SVG)" if has_any_image else " (SVG)"
|
|
1135
|
-
else:
|
|
1136
|
-
mode_str = " (SVG)"
|
|
1137
|
-
has_notes = slide_num in notes_slides_created
|
|
1138
|
-
notes_str = " +notes" if has_notes else ""
|
|
1139
|
-
narration_str = " +narration" if slide_num in narration_slides_created else ""
|
|
1140
|
-
print(f" [{i}/{len(svg_files)}] {svg_path.name}{mode_str}{notes_str}{narration_str}")
|
|
1141
|
-
|
|
1142
|
-
success_count += 1
|
|
1143
|
-
|
|
1144
|
-
except Exception as e:
|
|
1145
|
-
if verbose:
|
|
1146
|
-
print(f" [{i}/{len(svg_files)}] {svg_path.name} - Error: {e}")
|
|
1147
|
-
if use_native_shapes:
|
|
1148
|
-
raise
|
|
1149
|
-
|
|
1150
|
-
# Update [Content_Types].xml
|
|
1151
|
-
content_types_path = extract_dir / '[Content_Types].xml'
|
|
1152
|
-
with open(content_types_path, 'r', encoding='utf-8') as f:
|
|
1153
|
-
content_types = f.read()
|
|
1154
|
-
|
|
1155
|
-
if not use_native_shapes:
|
|
1156
|
-
content_types = _add_default_content_type(content_types, 'svg', 'image/svg+xml')
|
|
1157
|
-
for ext in sorted(image_exts_used):
|
|
1158
|
-
content_types = _add_default_content_type(
|
|
1159
|
-
content_types,
|
|
1160
|
-
ext,
|
|
1161
|
-
_content_type_for_extension(ext),
|
|
1162
|
-
)
|
|
1163
|
-
if 'xlsx' in package_exts_used:
|
|
1164
|
-
content_types = _add_default_content_type(
|
|
1165
|
-
content_types,
|
|
1166
|
-
'xlsx',
|
|
1167
|
-
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
1168
|
-
)
|
|
1169
|
-
for part_name, content_type in sorted(package_content_overrides.items()):
|
|
1170
|
-
content_types = _add_content_type_override(content_types, part_name, content_type)
|
|
1171
|
-
with open(content_types_path, 'w', encoding='utf-8') as f:
|
|
1172
|
-
f.write(content_types)
|
|
1173
|
-
|
|
1174
|
-
if audio_exts_used:
|
|
1175
|
-
for ext in sorted(audio_exts_used):
|
|
1176
|
-
content_type = AUDIO_CONTENT_TYPES.get(ext)
|
|
1177
|
-
if content_type:
|
|
1178
|
-
content_types = _add_default_content_type(content_types, ext, content_type)
|
|
1179
|
-
if 'Extension="png"' not in content_types:
|
|
1180
|
-
content_types = _add_default_content_type(content_types, 'png', 'image/png')
|
|
1181
|
-
with open(content_types_path, 'w', encoding='utf-8') as f:
|
|
1182
|
-
f.write(content_types)
|
|
1183
|
-
|
|
1184
|
-
# Add notes master / slides content types
|
|
1185
|
-
if enable_notes and notes_slides_created:
|
|
1186
|
-
notes_theme_override = (
|
|
1187
|
-
' <Override PartName="/ppt/theme/theme2.xml" '
|
|
1188
|
-
'ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>'
|
|
1189
|
-
)
|
|
1190
|
-
if notes_theme_override not in content_types:
|
|
1191
|
-
content_types = content_types.replace(
|
|
1192
|
-
'</Types>',
|
|
1193
|
-
notes_theme_override + '\n</Types>',
|
|
1194
|
-
)
|
|
1195
|
-
notes_master_override = (
|
|
1196
|
-
' <Override PartName="/ppt/notesMasters/notesMaster1.xml" '
|
|
1197
|
-
'ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>'
|
|
1198
|
-
)
|
|
1199
|
-
if notes_master_override not in content_types:
|
|
1200
|
-
content_types = content_types.replace(
|
|
1201
|
-
'</Types>',
|
|
1202
|
-
notes_master_override + '\n</Types>',
|
|
1203
|
-
)
|
|
1204
|
-
for i in sorted(notes_slides_created):
|
|
1205
|
-
override = (
|
|
1206
|
-
f' <Override PartName="/ppt/notesSlides/notesSlide{i}.xml" '
|
|
1207
|
-
f'ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>'
|
|
1208
|
-
)
|
|
1209
|
-
if override not in content_types:
|
|
1210
|
-
content_types = content_types.replace('</Types>', override + '\n</Types>')
|
|
1211
|
-
with open(content_types_path, 'w', encoding='utf-8') as f:
|
|
1212
|
-
f.write(content_types)
|
|
1213
|
-
|
|
1214
|
-
rels_problems = _verify_internal_rels_targets(extract_dir)
|
|
1215
|
-
if rels_problems:
|
|
1216
|
-
details = '\n'.join(f' - {p}' for p in rels_problems)
|
|
1217
|
-
raise RuntimeError(
|
|
1218
|
-
'PPTX package contains dangling internal relationship targets; '
|
|
1219
|
-
'PowerPoint will report the file as corrupt:\n' + details
|
|
1220
|
-
)
|
|
1221
|
-
|
|
1222
|
-
# Replace the python-pptx base-template metadata (stale "Steve Canny"
|
|
1223
|
-
# author, 2013 dates, "generated using python-pptx", Slides=0) with
|
|
1224
|
-
# accurate, tool-neutral document properties.
|
|
1225
|
-
pres_format = _presentation_format(width_emu, height_emu)
|
|
1226
|
-
_stamp_docprops(extract_dir, len(svg_files), pres_format, doc_metadata)
|
|
1227
|
-
|
|
1228
|
-
# Repackage PPTX to a temporary file first. The public output path is
|
|
1229
|
-
# replaced only after every slide and relationship has succeeded.
|
|
1230
|
-
temp_output_path = temp_dir / 'result.pptx'
|
|
1231
|
-
with zipfile.ZipFile(temp_output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
1232
|
-
for file_path in extract_dir.rglob('*'):
|
|
1233
|
-
if file_path.is_file():
|
|
1234
|
-
arcname = file_path.relative_to(extract_dir)
|
|
1235
|
-
zf.write(file_path, arcname)
|
|
1236
|
-
shutil.move(str(temp_output_path), str(output_path))
|
|
1237
|
-
permission_warnings = _relax_output_permissions(output_path)
|
|
1238
|
-
|
|
1239
|
-
if conversion_trace_path and conversion_trace is not None:
|
|
1240
|
-
conversion_trace_path.parent.mkdir(parents=True, exist_ok=True)
|
|
1241
|
-
payload = {
|
|
1242
|
-
'output': str(output_path),
|
|
1243
|
-
'slide_count': len(svg_files),
|
|
1244
|
-
'slides': conversion_trace,
|
|
1245
|
-
}
|
|
1246
|
-
conversion_trace_path.write_text(
|
|
1247
|
-
json.dumps(payload, ensure_ascii=False, indent=2),
|
|
1248
|
-
encoding='utf-8',
|
|
1249
|
-
)
|
|
1250
|
-
|
|
1251
|
-
if verbose:
|
|
1252
|
-
print()
|
|
1253
|
-
print(f"[Done] Saved: {output_path}")
|
|
1254
|
-
for warning in permission_warnings:
|
|
1255
|
-
print(f" [warn] {warning}")
|
|
1256
|
-
if conversion_trace_path and conversion_trace is not None:
|
|
1257
|
-
print(f" Trace: {conversion_trace_path}")
|
|
1258
|
-
print(f" Succeeded: {success_count}, Failed: {len(svg_files) - success_count}")
|
|
1259
|
-
if use_compat_mode and has_any_image:
|
|
1260
|
-
print(f" Mode: Office compatibility mode (supports all Office versions)")
|
|
1261
|
-
if renderer_hint:
|
|
1262
|
-
print(f" [Tip] {renderer_hint}")
|
|
1263
|
-
|
|
1264
|
-
return success_count == len(svg_files)
|
|
1265
|
-
|
|
1266
|
-
finally:
|
|
1267
|
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
1
|
+
"""Core PPTX assembly: create_pptx_with_native_svg."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import mimetypes
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import posixpath
|
|
11
|
+
import shutil
|
|
12
|
+
import stat
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
import uuid
|
|
16
|
+
import zipfile
|
|
17
|
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
from xml.sax.saxutils import escape
|
|
22
|
+
|
|
23
|
+
from pptx import Presentation
|
|
24
|
+
from pptx.util import Emu
|
|
25
|
+
|
|
26
|
+
from ..drawingml.converter import convert_svg_to_slide_shapes
|
|
27
|
+
from .dimensions import (
|
|
28
|
+
CANVAS_FORMATS,
|
|
29
|
+
get_slide_dimensions, get_pixel_dimensions,
|
|
30
|
+
get_viewbox_dimensions, detect_format_from_svg,
|
|
31
|
+
)
|
|
32
|
+
from .media import (
|
|
33
|
+
PNG_RENDERER,
|
|
34
|
+
get_png_renderer_info, convert_svg_to_png, convert_svg_to_png_cached,
|
|
35
|
+
)
|
|
36
|
+
from .notes import (
|
|
37
|
+
markdown_to_plain_text,
|
|
38
|
+
create_notes_master_rels_xml,
|
|
39
|
+
create_notes_master_xml,
|
|
40
|
+
create_notes_slide_xml,
|
|
41
|
+
create_notes_slide_rels_xml,
|
|
42
|
+
)
|
|
43
|
+
from .narration import (
|
|
44
|
+
AUDIO_CONTENT_TYPES,
|
|
45
|
+
AUDIO_REL_TYPE,
|
|
46
|
+
AUDIO_MARKER_PNG_BYTES,
|
|
47
|
+
IMAGE_REL_TYPE,
|
|
48
|
+
MEDIA_REL_TYPE,
|
|
49
|
+
apply_recorded_timing,
|
|
50
|
+
inject_narration,
|
|
51
|
+
next_shape_id,
|
|
52
|
+
probe_audio_duration,
|
|
53
|
+
)
|
|
54
|
+
from .slide_xml import (
|
|
55
|
+
ANIMATIONS_AVAILABLE, TRANSITIONS,
|
|
56
|
+
create_slide_xml_with_svg, create_slide_rels_xml,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# Re-import create_transition_xml only if available
|
|
60
|
+
try:
|
|
61
|
+
from pptx_animations import (
|
|
62
|
+
create_transition_xml,
|
|
63
|
+
create_sequence_timing_xml,
|
|
64
|
+
pick_animation_effect,
|
|
65
|
+
)
|
|
66
|
+
except ImportError:
|
|
67
|
+
create_transition_xml = None
|
|
68
|
+
create_sequence_timing_xml = None
|
|
69
|
+
pick_animation_effect = None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _append_relationship(
|
|
73
|
+
rels_path: Path,
|
|
74
|
+
rel_type: str,
|
|
75
|
+
target: str,
|
|
76
|
+
) -> str:
|
|
77
|
+
"""Append a relationship entry with the next available rId."""
|
|
78
|
+
with open(rels_path, 'r', encoding='utf-8') as f:
|
|
79
|
+
rels_content = f.read()
|
|
80
|
+
|
|
81
|
+
rid_numbers = [int(match) for match in re.findall(r'Id="rId(\d+)"', rels_content)]
|
|
82
|
+
next_rid = f'rId{max(rid_numbers, default=0) + 1}'
|
|
83
|
+
rel_xml = (
|
|
84
|
+
f' <Relationship Id="{next_rid}" '
|
|
85
|
+
f'Type="{rel_type}" Target="{target}"/>'
|
|
86
|
+
)
|
|
87
|
+
rels_content = rels_content.replace(
|
|
88
|
+
'</Relationships>', rel_xml + '\n</Relationships>',
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
with open(rels_path, 'w', encoding='utf-8') as f:
|
|
92
|
+
f.write(rels_content)
|
|
93
|
+
|
|
94
|
+
return next_rid
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _find_relationship_id(
|
|
98
|
+
rels_path: Path,
|
|
99
|
+
rel_type: str,
|
|
100
|
+
target: str,
|
|
101
|
+
) -> str | None:
|
|
102
|
+
"""Find an existing relationship id by type and target."""
|
|
103
|
+
if not rels_path.exists():
|
|
104
|
+
return None
|
|
105
|
+
rels_content = rels_path.read_text(encoding='utf-8')
|
|
106
|
+
pattern = (
|
|
107
|
+
r'<Relationship\b[^>]*\bId="([^"]+)"[^>]*'
|
|
108
|
+
rf'\bType="{re.escape(rel_type)}"[^>]*'
|
|
109
|
+
rf'\bTarget="{re.escape(target)}"[^>]*/>'
|
|
110
|
+
)
|
|
111
|
+
match = re.search(pattern, rels_content)
|
|
112
|
+
return match.group(1) if match else None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _add_default_content_type(content_types: str, extension: str, content_type: str) -> str:
|
|
116
|
+
"""Add a Default content type if it is not already present."""
|
|
117
|
+
ext = extension.lstrip(".")
|
|
118
|
+
if f'Extension="{ext}"' in content_types:
|
|
119
|
+
return content_types
|
|
120
|
+
entry = f' <Default Extension="{ext}" ContentType="{content_type}"/>'
|
|
121
|
+
override_pos = content_types.find('<Override ')
|
|
122
|
+
if override_pos >= 0:
|
|
123
|
+
return content_types[:override_pos] + entry + '\n' + content_types[override_pos:]
|
|
124
|
+
return content_types.replace('</Types>', entry + '\n</Types>')
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _add_content_type_override(content_types: str, part_name: str, content_type: str) -> str:
|
|
128
|
+
"""Add an Override content type if it is not already present."""
|
|
129
|
+
normalized = '/' + part_name.lstrip('/')
|
|
130
|
+
if f'PartName="{normalized}"' in content_types:
|
|
131
|
+
return content_types
|
|
132
|
+
entry = f' <Override PartName="{normalized}" ContentType="{content_type}"/>'
|
|
133
|
+
return content_types.replace('</Types>', entry + '\n</Types>')
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
_IMAGE_CONTENT_TYPES = {
|
|
137
|
+
'png': 'image/png',
|
|
138
|
+
'jpg': 'image/jpeg',
|
|
139
|
+
'jpeg': 'image/jpeg',
|
|
140
|
+
'gif': 'image/gif',
|
|
141
|
+
'webp': 'image/webp',
|
|
142
|
+
'svg': 'image/svg+xml',
|
|
143
|
+
'bmp': 'image/bmp',
|
|
144
|
+
'emf': 'image/x-emf',
|
|
145
|
+
'tif': 'image/tiff',
|
|
146
|
+
'tiff': 'image/tiff',
|
|
147
|
+
'wmf': 'image/x-wmf',
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _content_type_for_extension(ext: str) -> str:
|
|
152
|
+
clean = ext.lower().lstrip('.')
|
|
153
|
+
content_type = _IMAGE_CONTENT_TYPES.get(clean) or mimetypes.guess_type(f'x.{clean}')[0]
|
|
154
|
+
if not content_type:
|
|
155
|
+
raise ValueError(f"Unknown media content type for extension: {ext}")
|
|
156
|
+
return content_type
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _as_dict(value: Any) -> dict[str, Any]:
|
|
160
|
+
return value if isinstance(value, dict) else {}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _create_writable_work_dir(output_path: Path) -> Path:
|
|
164
|
+
"""Create a real writable work directory for PPTX assembly."""
|
|
165
|
+
parents = [output_path.parent, Path.cwd(), Path(tempfile.gettempdir())]
|
|
166
|
+
seen: set[str] = set()
|
|
167
|
+
errors: list[str] = []
|
|
168
|
+
|
|
169
|
+
for parent in parents:
|
|
170
|
+
parent = parent if str(parent) else Path(".")
|
|
171
|
+
try:
|
|
172
|
+
key = str(parent.resolve())
|
|
173
|
+
except OSError:
|
|
174
|
+
key = str(parent.absolute())
|
|
175
|
+
if key in seen:
|
|
176
|
+
continue
|
|
177
|
+
seen.add(key)
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
181
|
+
except OSError as exc:
|
|
182
|
+
errors.append(f"{parent}: cannot create parent ({exc})")
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
for _ in range(3):
|
|
186
|
+
work_dir = parent / f".pptx-build-{os.getpid()}-{uuid.uuid4().hex}"
|
|
187
|
+
try:
|
|
188
|
+
work_dir.mkdir(mode=0o700)
|
|
189
|
+
probe_path = work_dir / ".write-probe"
|
|
190
|
+
probe_path.write_text("ok", encoding="utf-8")
|
|
191
|
+
probe_path.unlink()
|
|
192
|
+
return work_dir
|
|
193
|
+
except OSError as exc:
|
|
194
|
+
errors.append(f"{work_dir}: {exc}")
|
|
195
|
+
shutil.rmtree(work_dir, ignore_errors=True)
|
|
196
|
+
|
|
197
|
+
details = "\n - ".join(errors) if errors else "no candidate directories available"
|
|
198
|
+
raise PermissionError(
|
|
199
|
+
"Unable to create a writable PPTX work directory. "
|
|
200
|
+
"Set the output path to a writable project directory or adjust sandbox permissions. "
|
|
201
|
+
f"Tried:\n - {details}"
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _relax_output_permissions(output_path: Path) -> list[str]:
|
|
206
|
+
"""Make exported files readable outside the sandbox owner where possible."""
|
|
207
|
+
warnings: list[str] = []
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
current_mode = output_path.stat().st_mode
|
|
211
|
+
readable_mode = (
|
|
212
|
+
current_mode
|
|
213
|
+
| stat.S_IRUSR
|
|
214
|
+
| stat.S_IWUSR
|
|
215
|
+
| stat.S_IRGRP
|
|
216
|
+
| stat.S_IROTH
|
|
217
|
+
)
|
|
218
|
+
os.chmod(output_path, readable_mode)
|
|
219
|
+
except OSError as exc:
|
|
220
|
+
warnings.append(f"chmod skipped for {output_path}: {exc}")
|
|
221
|
+
|
|
222
|
+
if os.name != 'nt':
|
|
223
|
+
return warnings
|
|
224
|
+
|
|
225
|
+
# Windows ACLs can remain sandbox-only even when the file mode looks sane.
|
|
226
|
+
# Grant the built-in Users SID read access; the SID avoids localization
|
|
227
|
+
# issues on non-English Windows installations.
|
|
228
|
+
try:
|
|
229
|
+
result = subprocess.run(
|
|
230
|
+
['icacls', str(output_path), '/grant', '*S-1-5-32-545:R'],
|
|
231
|
+
capture_output=True,
|
|
232
|
+
text=True,
|
|
233
|
+
check=False,
|
|
234
|
+
)
|
|
235
|
+
except OSError as exc:
|
|
236
|
+
warnings.append(f"icacls skipped for {output_path}: {exc}")
|
|
237
|
+
else:
|
|
238
|
+
if result.returncode != 0:
|
|
239
|
+
message = (result.stderr or result.stdout or '').strip()
|
|
240
|
+
details = f": {message}" if message else ''
|
|
241
|
+
warnings.append(f"icacls failed for {output_path}{details}")
|
|
242
|
+
|
|
243
|
+
return warnings
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
_NOTES_MASTER_REL_TYPE = (
|
|
247
|
+
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster'
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _ensure_notes_master(extract_dir: Path) -> None:
|
|
252
|
+
"""Create notesMaster parts and wire them into the presentation package."""
|
|
253
|
+
ppt_dir = extract_dir / 'ppt'
|
|
254
|
+
notes_masters_dir = ppt_dir / 'notesMasters'
|
|
255
|
+
notes_masters_dir.mkdir(exist_ok=True)
|
|
256
|
+
|
|
257
|
+
notes_master_path = notes_masters_dir / 'notesMaster1.xml'
|
|
258
|
+
if not notes_master_path.exists():
|
|
259
|
+
notes_master_path.write_text(create_notes_master_xml(), encoding='utf-8')
|
|
260
|
+
|
|
261
|
+
theme_dir = ppt_dir / 'theme'
|
|
262
|
+
theme_dir.mkdir(exist_ok=True)
|
|
263
|
+
theme1_path = theme_dir / 'theme1.xml'
|
|
264
|
+
theme2_path = theme_dir / 'theme2.xml'
|
|
265
|
+
if not theme2_path.exists():
|
|
266
|
+
if theme1_path.exists():
|
|
267
|
+
shutil.copy2(theme1_path, theme2_path)
|
|
268
|
+
else:
|
|
269
|
+
raise RuntimeError('Cannot create notes theme: ppt/theme/theme1.xml is missing')
|
|
270
|
+
|
|
271
|
+
notes_master_rels_dir = notes_masters_dir / '_rels'
|
|
272
|
+
notes_master_rels_dir.mkdir(exist_ok=True)
|
|
273
|
+
notes_master_rels_path = notes_master_rels_dir / 'notesMaster1.xml.rels'
|
|
274
|
+
if not notes_master_rels_path.exists():
|
|
275
|
+
notes_master_rels_path.write_text(
|
|
276
|
+
create_notes_master_rels_xml(),
|
|
277
|
+
encoding='utf-8',
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
presentation_rels_path = ppt_dir / '_rels' / 'presentation.xml.rels'
|
|
281
|
+
notes_master_rid = _find_relationship_id(
|
|
282
|
+
presentation_rels_path,
|
|
283
|
+
_NOTES_MASTER_REL_TYPE,
|
|
284
|
+
'notesMasters/notesMaster1.xml',
|
|
285
|
+
)
|
|
286
|
+
if notes_master_rid is None:
|
|
287
|
+
notes_master_rid = _append_relationship(
|
|
288
|
+
presentation_rels_path,
|
|
289
|
+
_NOTES_MASTER_REL_TYPE,
|
|
290
|
+
'notesMasters/notesMaster1.xml',
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
presentation_path = ppt_dir / 'presentation.xml'
|
|
294
|
+
presentation_xml = presentation_path.read_text(encoding='utf-8')
|
|
295
|
+
if '<p:notesMasterIdLst>' in presentation_xml:
|
|
296
|
+
return
|
|
297
|
+
notes_master_lst = (
|
|
298
|
+
f'<p:notesMasterIdLst><p:notesMasterId r:id="{notes_master_rid}"/>'
|
|
299
|
+
'</p:notesMasterIdLst>'
|
|
300
|
+
)
|
|
301
|
+
if '</p:sldMasterIdLst>' not in presentation_xml:
|
|
302
|
+
raise RuntimeError('presentation.xml is missing p:sldMasterIdLst')
|
|
303
|
+
presentation_xml = presentation_xml.replace(
|
|
304
|
+
'</p:sldMasterIdLst>',
|
|
305
|
+
'</p:sldMasterIdLst>' + notes_master_lst,
|
|
306
|
+
1,
|
|
307
|
+
)
|
|
308
|
+
presentation_path.write_text(presentation_xml, encoding='utf-8')
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _to_float(value: Any, default: float) -> float:
|
|
312
|
+
if value is None:
|
|
313
|
+
return default
|
|
314
|
+
try:
|
|
315
|
+
number = float(value)
|
|
316
|
+
except (TypeError, ValueError):
|
|
317
|
+
return default
|
|
318
|
+
return number if number >= 0 else default
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _slide_config(animation_config: dict[str, Any] | None, svg_stem: str) -> dict[str, Any]:
|
|
322
|
+
if not animation_config:
|
|
323
|
+
return {}
|
|
324
|
+
slides = _as_dict(animation_config.get('slides'))
|
|
325
|
+
return _as_dict(slides.get(svg_stem))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _slide_transition_settings(
|
|
329
|
+
slide_cfg: dict[str, Any],
|
|
330
|
+
transition: str | None,
|
|
331
|
+
duration: float,
|
|
332
|
+
auto_advance: float | None,
|
|
333
|
+
cli_overrides: dict[str, bool],
|
|
334
|
+
) -> tuple[str | None, float, float | None]:
|
|
335
|
+
trans_cfg = _as_dict(slide_cfg.get('transition'))
|
|
336
|
+
effect = transition
|
|
337
|
+
if not cli_overrides.get('transition') and 'effect' in trans_cfg:
|
|
338
|
+
cfg_effect = str(trans_cfg.get('effect'))
|
|
339
|
+
effect = None if cfg_effect == 'none' else cfg_effect
|
|
340
|
+
if not cli_overrides.get('transition_duration'):
|
|
341
|
+
duration = _to_float(trans_cfg.get('duration'), duration)
|
|
342
|
+
if not cli_overrides.get('auto_advance') and 'auto_advance' in trans_cfg:
|
|
343
|
+
auto_advance = _to_float(trans_cfg.get('auto_advance'), auto_advance or 0)
|
|
344
|
+
return effect, duration, auto_advance
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _slide_animation_settings(
|
|
348
|
+
slide_cfg: dict[str, Any],
|
|
349
|
+
animation: str | None,
|
|
350
|
+
duration: float,
|
|
351
|
+
stagger: float,
|
|
352
|
+
trigger: str,
|
|
353
|
+
cli_overrides: dict[str, bool],
|
|
354
|
+
) -> tuple[str | None, float, float, str]:
|
|
355
|
+
anim_cfg = _as_dict(slide_cfg.get('animation'))
|
|
356
|
+
effect = animation
|
|
357
|
+
if not cli_overrides.get('animation') and 'effect' in anim_cfg:
|
|
358
|
+
cfg_effect = str(anim_cfg.get('effect'))
|
|
359
|
+
effect = None if cfg_effect == 'none' else cfg_effect
|
|
360
|
+
if not cli_overrides.get('animation_duration'):
|
|
361
|
+
duration = _to_float(anim_cfg.get('duration'), duration)
|
|
362
|
+
if not cli_overrides.get('animation_stagger'):
|
|
363
|
+
stagger = _to_float(anim_cfg.get('stagger'), stagger)
|
|
364
|
+
if not cli_overrides.get('animation_trigger') and anim_cfg.get('trigger'):
|
|
365
|
+
trigger = str(anim_cfg.get('trigger'))
|
|
366
|
+
return effect, duration, stagger, trigger
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _build_sequence_targets(
|
|
370
|
+
anim_targets: list[tuple[int, str]],
|
|
371
|
+
slide_cfg: dict[str, Any],
|
|
372
|
+
animation: str,
|
|
373
|
+
duration: float,
|
|
374
|
+
stagger: float,
|
|
375
|
+
mixed_animation_offset: int,
|
|
376
|
+
) -> tuple[list[tuple[int, int, str, float]], int]:
|
|
377
|
+
groups_cfg = _as_dict(slide_cfg.get('groups'))
|
|
378
|
+
ordered: list[tuple[int, int, int, str, dict[str, Any]]] = []
|
|
379
|
+
for idx, (sid, svg_id) in enumerate(anim_targets):
|
|
380
|
+
group_cfg = _as_dict(groups_cfg.get(svg_id))
|
|
381
|
+
if str(group_cfg.get('effect', '')).lower() == 'none':
|
|
382
|
+
continue
|
|
383
|
+
order_value = group_cfg.get('order')
|
|
384
|
+
try:
|
|
385
|
+
order = int(order_value)
|
|
386
|
+
has_order = 0
|
|
387
|
+
except (TypeError, ValueError):
|
|
388
|
+
order = idx
|
|
389
|
+
has_order = 1
|
|
390
|
+
group_entry = dict(group_cfg)
|
|
391
|
+
group_entry['_shape_id'] = sid
|
|
392
|
+
ordered.append((has_order, order, idx, svg_id, group_entry))
|
|
393
|
+
|
|
394
|
+
ordered.sort(key=lambda item: (item[0], item[1], item[2]))
|
|
395
|
+
|
|
396
|
+
seq_targets: list[tuple[int, int, str, float]] = []
|
|
397
|
+
for seq_idx, (_has_order, _order, _original_idx, _svg_id, group_cfg) in enumerate(ordered):
|
|
398
|
+
shape_id = int(group_cfg['_shape_id'])
|
|
399
|
+
raw_effect = group_cfg.get('effect')
|
|
400
|
+
if raw_effect in ('auto', 'mixed', 'random'):
|
|
401
|
+
effect = pick_animation_effect(
|
|
402
|
+
str(raw_effect), seq_idx, mixed_animation_offset, group_id=_svg_id,
|
|
403
|
+
)
|
|
404
|
+
else:
|
|
405
|
+
effect = str(raw_effect or pick_animation_effect(
|
|
406
|
+
animation, seq_idx, mixed_animation_offset, group_id=_svg_id,
|
|
407
|
+
))
|
|
408
|
+
item_duration = _to_float(group_cfg.get('duration'), duration)
|
|
409
|
+
delay_seconds = _to_float(
|
|
410
|
+
group_cfg.get('delay'),
|
|
411
|
+
0 if seq_idx == 0 else stagger,
|
|
412
|
+
)
|
|
413
|
+
seq_targets.append((shape_id, int(delay_seconds * 1000), effect, item_duration))
|
|
414
|
+
|
|
415
|
+
mixed_count = 0
|
|
416
|
+
if animation == 'mixed':
|
|
417
|
+
mixed_count = sum(1 for _target in seq_targets[1:])
|
|
418
|
+
elif animation == 'auto':
|
|
419
|
+
# 'auto' accumulates a cross-slide offset so the image pool and the
|
|
420
|
+
# unmatched-id fallback rotate as the deck advances. Single-effect
|
|
421
|
+
# semantic matches (title→fade, chart→wipe etc.) are unaffected
|
|
422
|
+
# because they ignore the offset.
|
|
423
|
+
mixed_count = len(seq_targets)
|
|
424
|
+
return seq_targets, mixed_count
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _prerender_legacy_pngs(
|
|
428
|
+
svg_files: list[Path],
|
|
429
|
+
media_dir: Path,
|
|
430
|
+
pixel_width: int,
|
|
431
|
+
pixel_height: int,
|
|
432
|
+
cache_dir: Path | None,
|
|
433
|
+
workers: int,
|
|
434
|
+
verbose: bool,
|
|
435
|
+
) -> dict[int, bool]:
|
|
436
|
+
"""Render every SVG→PNG into media_dir in parallel.
|
|
437
|
+
|
|
438
|
+
Returns {1-based slide index: success}. Falls back to sequential when
|
|
439
|
+
workers<=1 or len(svg_files)<=2.
|
|
440
|
+
"""
|
|
441
|
+
results: dict[int, bool] = {}
|
|
442
|
+
targets: list[tuple[int, Path, Path]] = [
|
|
443
|
+
(i, svg, media_dir / f'image{i}.png')
|
|
444
|
+
for i, svg in enumerate(svg_files, 1)
|
|
445
|
+
]
|
|
446
|
+
|
|
447
|
+
if workers <= 1 or len(targets) <= 2:
|
|
448
|
+
for i, svg, png in targets:
|
|
449
|
+
ok = convert_svg_to_png_cached(svg, png, pixel_width, pixel_height, cache_dir)
|
|
450
|
+
results[i] = ok
|
|
451
|
+
if verbose:
|
|
452
|
+
tag = 'cached/ok' if ok else 'failed'
|
|
453
|
+
print(f" [PNG {i}/{len(targets)}] {svg.name} - {tag}")
|
|
454
|
+
return results
|
|
455
|
+
|
|
456
|
+
with ProcessPoolExecutor(max_workers=workers) as pool:
|
|
457
|
+
future_map = {
|
|
458
|
+
pool.submit(
|
|
459
|
+
convert_svg_to_png_cached,
|
|
460
|
+
svg, png, pixel_width, pixel_height, cache_dir,
|
|
461
|
+
): (i, svg)
|
|
462
|
+
for i, svg, png in targets
|
|
463
|
+
}
|
|
464
|
+
done = 0
|
|
465
|
+
for future in as_completed(future_map):
|
|
466
|
+
i, svg = future_map[future]
|
|
467
|
+
try:
|
|
468
|
+
ok = future.result()
|
|
469
|
+
except Exception as exc:
|
|
470
|
+
ok = False
|
|
471
|
+
if verbose:
|
|
472
|
+
print(f" [PNG] {svg.name} - worker error: {exc}")
|
|
473
|
+
results[i] = ok
|
|
474
|
+
done += 1
|
|
475
|
+
if verbose:
|
|
476
|
+
tag = 'cached/ok' if ok else 'failed'
|
|
477
|
+
print(f" [PNG {done}/{len(targets)}] {svg.name} - {tag}")
|
|
478
|
+
|
|
479
|
+
return results
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
_REL_TARGET_RE = re.compile(r'<Relationship\b[^/]*?/>', re.DOTALL)
|
|
483
|
+
_TARGET_ATTR_RE = re.compile(r'Target="([^"]+)"')
|
|
484
|
+
_TARGET_MODE_EXT_RE = re.compile(r'TargetMode="External"')
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _verify_internal_rels_targets(extract_dir: Path) -> list[str]:
|
|
488
|
+
"""Return a list of dangling internal Targets across every .rels in the package.
|
|
489
|
+
|
|
490
|
+
Each entry is formatted as "<rels-path> -> <missing-target>". An empty list
|
|
491
|
+
means every internal Target resolves to a real file in the package.
|
|
492
|
+
"""
|
|
493
|
+
problems: list[str] = []
|
|
494
|
+
for rels_path in extract_dir.rglob('*.rels'):
|
|
495
|
+
rels_rel = rels_path.relative_to(extract_dir).as_posix()
|
|
496
|
+
# `_rels/foo.xml.rels` lives one level below its referent's directory;
|
|
497
|
+
# Targets resolve relative to the parent of that `_rels` folder.
|
|
498
|
+
base_dir = posixpath.dirname(posixpath.dirname(rels_rel))
|
|
499
|
+
content = rels_path.read_text(encoding='utf-8')
|
|
500
|
+
for match in _REL_TARGET_RE.finditer(content):
|
|
501
|
+
element = match.group(0)
|
|
502
|
+
if _TARGET_MODE_EXT_RE.search(element):
|
|
503
|
+
continue
|
|
504
|
+
target_match = _TARGET_ATTR_RE.search(element)
|
|
505
|
+
if not target_match:
|
|
506
|
+
continue
|
|
507
|
+
target = target_match.group(1)
|
|
508
|
+
if target.startswith(('http://', 'https://', 'mailto:')):
|
|
509
|
+
continue
|
|
510
|
+
resolved = posixpath.normpath(posixpath.join(base_dir, target)) if base_dir else posixpath.normpath(target)
|
|
511
|
+
if not (extract_dir / resolved).exists():
|
|
512
|
+
problems.append(f'{rels_rel} -> {resolved}')
|
|
513
|
+
return problems
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _presentation_format(width: float, height: float) -> str:
|
|
517
|
+
"""Map the slide aspect ratio to PowerPoint's PresentationFormat label.
|
|
518
|
+
Non-standard ratios (square, portrait, banner crops) report 'Custom'.
|
|
519
|
+
"""
|
|
520
|
+
if width <= 0 or height <= 0:
|
|
521
|
+
return 'Custom'
|
|
522
|
+
ratio = width / height
|
|
523
|
+
for target, label in (
|
|
524
|
+
(4 / 3, 'On-screen Show (4:3)'),
|
|
525
|
+
(16 / 9, 'On-screen Show (16:9)'),
|
|
526
|
+
(16 / 10, 'On-screen Show (16:10)'),
|
|
527
|
+
):
|
|
528
|
+
if abs(ratio - target) < 0.02:
|
|
529
|
+
return label
|
|
530
|
+
return 'Custom'
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _stamp_docprops(
|
|
534
|
+
extract_dir: Path,
|
|
535
|
+
slide_count: int,
|
|
536
|
+
pres_format: str,
|
|
537
|
+
meta: dict[str, Any] | None = None,
|
|
538
|
+
) -> None:
|
|
539
|
+
"""Overwrite the misleading python-pptx default metadata with accurate
|
|
540
|
+
values. Factual fields (slide count, export timestamp, presentation format,
|
|
541
|
+
application) are always machine-derived. Authored fields — including the
|
|
542
|
+
title — come solely from an optional per-project `metadata.json`
|
|
543
|
+
(`meta`); whatever it omits stays blank. `lastModifiedBy` follows
|
|
544
|
+
`creator` rather than ever carrying the base template's author or a tool
|
|
545
|
+
name. No field is guessed from slide content: a blank title is preferable
|
|
546
|
+
to an unreliable heuristic pick.
|
|
547
|
+
"""
|
|
548
|
+
meta = meta or {}
|
|
549
|
+
|
|
550
|
+
def field(key: str, default: str = '') -> str:
|
|
551
|
+
value = meta.get(key)
|
|
552
|
+
return value.strip() if isinstance(value, str) and value.strip() else default
|
|
553
|
+
|
|
554
|
+
title = field('title')
|
|
555
|
+
creator = field('creator')
|
|
556
|
+
|
|
557
|
+
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
558
|
+
|
|
559
|
+
core_path = extract_dir / 'docProps' / 'core.xml'
|
|
560
|
+
if core_path.exists():
|
|
561
|
+
core_path.write_text(
|
|
562
|
+
"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n"
|
|
563
|
+
'<cp:coreProperties '
|
|
564
|
+
'xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" '
|
|
565
|
+
'xmlns:dc="http://purl.org/dc/elements/1.1/" '
|
|
566
|
+
'xmlns:dcterms="http://purl.org/dc/terms/" '
|
|
567
|
+
'xmlns:dcmitype="http://purl.org/dc/dcmitype/" '
|
|
568
|
+
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
|
|
569
|
+
f'<dc:title>{escape(title)}</dc:title>'
|
|
570
|
+
f'<dc:subject>{escape(field("subject"))}</dc:subject>'
|
|
571
|
+
f'<dc:creator>{escape(creator)}</dc:creator>'
|
|
572
|
+
f'<cp:keywords>{escape(field("keywords"))}</cp:keywords>'
|
|
573
|
+
f'<dc:description>{escape(field("description"))}</dc:description>'
|
|
574
|
+
f'<dc:language>{escape(field("language"))}</dc:language>'
|
|
575
|
+
f'<cp:lastModifiedBy>{escape(creator)}</cp:lastModifiedBy>'
|
|
576
|
+
'<cp:revision>1</cp:revision>'
|
|
577
|
+
f'<dcterms:created xsi:type="dcterms:W3CDTF">{now}</dcterms:created>'
|
|
578
|
+
f'<dcterms:modified xsi:type="dcterms:W3CDTF">{now}</dcterms:modified>'
|
|
579
|
+
f'<cp:category>{escape(field("category"))}</cp:category>'
|
|
580
|
+
f'<cp:contentStatus>{escape(field("contentStatus"))}</cp:contentStatus>'
|
|
581
|
+
'</cp:coreProperties>',
|
|
582
|
+
encoding='utf-8',
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
app_path = extract_dir / 'docProps' / 'app.xml'
|
|
586
|
+
if app_path.exists():
|
|
587
|
+
app = app_path.read_text(encoding='utf-8')
|
|
588
|
+
app = re.sub(r'<Slides>.*?</Slides>', f'<Slides>{slide_count}</Slides>', app)
|
|
589
|
+
app = re.sub(
|
|
590
|
+
r'<Company>.*?</Company>',
|
|
591
|
+
f'<Company>{escape(field("company"))}</Company>',
|
|
592
|
+
app,
|
|
593
|
+
)
|
|
594
|
+
app = re.sub(
|
|
595
|
+
r'<Manager>.*?</Manager>',
|
|
596
|
+
f'<Manager>{escape(field("manager"))}</Manager>',
|
|
597
|
+
app,
|
|
598
|
+
)
|
|
599
|
+
app = re.sub(
|
|
600
|
+
r'<Application>.*?</Application>',
|
|
601
|
+
'<Application>Microsoft Office PowerPoint</Application>',
|
|
602
|
+
app,
|
|
603
|
+
)
|
|
604
|
+
app = re.sub(
|
|
605
|
+
r'<PresentationFormat>.*?</PresentationFormat>',
|
|
606
|
+
f'<PresentationFormat>{escape(pres_format)}</PresentationFormat>',
|
|
607
|
+
app,
|
|
608
|
+
)
|
|
609
|
+
app_path.write_text(app, encoding='utf-8')
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def create_pptx_with_native_svg(
|
|
613
|
+
svg_files: list[Path],
|
|
614
|
+
output_path: Path,
|
|
615
|
+
canvas_format: str | None = None,
|
|
616
|
+
verbose: bool = True,
|
|
617
|
+
transition: str | None = 'fade',
|
|
618
|
+
transition_duration: float = 0.5,
|
|
619
|
+
auto_advance: float | None = None,
|
|
620
|
+
use_compat_mode: bool = True,
|
|
621
|
+
notes: dict[str, str] | None = None,
|
|
622
|
+
enable_notes: bool = True,
|
|
623
|
+
use_native_shapes: bool = False,
|
|
624
|
+
animation: str | None = None,
|
|
625
|
+
animation_duration: float = 0.4,
|
|
626
|
+
animation_stagger: float = 0.5,
|
|
627
|
+
animation_trigger: str = 'after-previous',
|
|
628
|
+
animation_config: dict[str, Any] | None = None,
|
|
629
|
+
animation_cli_overrides: dict[str, bool] | None = None,
|
|
630
|
+
narration_audio: dict[str, Path] | None = None,
|
|
631
|
+
use_narration_timings: bool = False,
|
|
632
|
+
narration_padding: float = 0.5,
|
|
633
|
+
cache_dir: Path | None = None,
|
|
634
|
+
workers: int | None = None,
|
|
635
|
+
merge_paragraphs: bool = True,
|
|
636
|
+
image_optimize: bool = True,
|
|
637
|
+
image_max_dimension: int | None = 2560,
|
|
638
|
+
image_sizing: str = 'cap',
|
|
639
|
+
image_scale: float = 2.0,
|
|
640
|
+
image_quality: int = 85,
|
|
641
|
+
native_objects: bool = False,
|
|
642
|
+
conversion_trace_path: Path | None = None,
|
|
643
|
+
doc_metadata: dict[str, Any] | None = None,
|
|
644
|
+
) -> bool:
|
|
645
|
+
"""Create a PPTX file with native SVG.
|
|
646
|
+
|
|
647
|
+
Args:
|
|
648
|
+
svg_files: List of SVG files.
|
|
649
|
+
output_path: Output PPTX path.
|
|
650
|
+
canvas_format: Canvas format key.
|
|
651
|
+
verbose: Whether to output detailed information.
|
|
652
|
+
transition: Transition effect name.
|
|
653
|
+
transition_duration: Transition duration in seconds.
|
|
654
|
+
auto_advance: Auto-advance interval in seconds.
|
|
655
|
+
use_compat_mode: Use Office compatibility mode (PNG + SVG dual format).
|
|
656
|
+
notes: Notes dict, key is SVG stem, value is notes content.
|
|
657
|
+
enable_notes: Whether to enable notes embedding.
|
|
658
|
+
use_native_shapes: Convert SVG to native DrawingML shapes.
|
|
659
|
+
animation: Per-element entrance animation mode (single effect name,
|
|
660
|
+
'mixed', 'random', or None to disable). Native shapes mode only.
|
|
661
|
+
animation_duration: Per-element entrance duration in seconds.
|
|
662
|
+
animation_stagger: Delay between elements in `after-previous`
|
|
663
|
+
trigger mode (seconds). Ignored otherwise.
|
|
664
|
+
animation_trigger: PowerPoint Start mode — `'after-previous'` (default),
|
|
665
|
+
`'on-click'`, or `'with-previous'`.
|
|
666
|
+
animation_config: Optional sidecar overrides loaded from animations.json.
|
|
667
|
+
animation_cli_overrides: Flags indicating explicit CLI overrides.
|
|
668
|
+
narration_audio: Optional dict mapping SVG stem to narration audio file.
|
|
669
|
+
use_narration_timings: Whether to set slide auto-advance from audio duration.
|
|
670
|
+
narration_padding: Extra seconds added after each narration before advancing.
|
|
671
|
+
image_optimize: Whether native export downscales oversized raster images.
|
|
672
|
+
image_max_dimension: Maximum optimized image dimension in pixels.
|
|
673
|
+
image_sizing: `cap` only limits source dimensions; `display` sizes
|
|
674
|
+
from rendered SVG boxes.
|
|
675
|
+
image_scale: Target image pixels per SVG display pixel.
|
|
676
|
+
image_quality: JPEG quality used for opaque optimized rasters.
|
|
677
|
+
native_objects: Convert explicit `data-pptx-native` table/chart
|
|
678
|
+
markers to native PowerPoint objects. Default off.
|
|
679
|
+
conversion_trace_path: Optional JSON path for native conversion diagnostics.
|
|
680
|
+
|
|
681
|
+
Returns:
|
|
682
|
+
Whether all slides were successfully created.
|
|
683
|
+
"""
|
|
684
|
+
if not svg_files:
|
|
685
|
+
print("Error: No SVG files found")
|
|
686
|
+
return False
|
|
687
|
+
|
|
688
|
+
# Native shapes mode takes priority over compat mode
|
|
689
|
+
if use_native_shapes:
|
|
690
|
+
use_compat_mode = False
|
|
691
|
+
|
|
692
|
+
# Check compatibility mode dependencies
|
|
693
|
+
renderer_name, renderer_status, renderer_hint = get_png_renderer_info()
|
|
694
|
+
if not use_native_shapes and use_compat_mode and PNG_RENDERER is None:
|
|
695
|
+
print("Warning: No PNG rendering library installed, cannot use compatibility mode")
|
|
696
|
+
print(f" {renderer_hint}")
|
|
697
|
+
print(" Will use pure SVG mode (may not display in Office LTSC 2021 and similar versions)")
|
|
698
|
+
use_compat_mode = False
|
|
699
|
+
|
|
700
|
+
# Auto-detect canvas format or get dimensions from viewBox
|
|
701
|
+
custom_pixels: tuple[int, int] | None = None
|
|
702
|
+
if canvas_format is None:
|
|
703
|
+
canvas_format = detect_format_from_svg(svg_files[0])
|
|
704
|
+
if canvas_format and verbose:
|
|
705
|
+
format_name = CANVAS_FORMATS.get(canvas_format, {}).get('name', canvas_format)
|
|
706
|
+
print(f" Detected canvas format: {format_name}")
|
|
707
|
+
|
|
708
|
+
if canvas_format is None:
|
|
709
|
+
custom_pixels = get_viewbox_dimensions(svg_files[0])
|
|
710
|
+
if custom_pixels and verbose:
|
|
711
|
+
print(f" Using SVG viewBox dimensions: {custom_pixels[0]} x {custom_pixels[1]} px")
|
|
712
|
+
|
|
713
|
+
if canvas_format is None and custom_pixels is None:
|
|
714
|
+
canvas_format = 'ppt169'
|
|
715
|
+
if verbose:
|
|
716
|
+
print(f" Using default format: PPT 16:9")
|
|
717
|
+
|
|
718
|
+
width_emu, height_emu = get_slide_dimensions(canvas_format or 'ppt169', custom_pixels)
|
|
719
|
+
pixel_width, pixel_height = get_pixel_dimensions(canvas_format or 'ppt169', custom_pixels)
|
|
720
|
+
|
|
721
|
+
if verbose:
|
|
722
|
+
print(f" Slide dimensions: {pixel_width} x {pixel_height} px")
|
|
723
|
+
print(f" SVG file count: {len(svg_files)}")
|
|
724
|
+
if use_native_shapes:
|
|
725
|
+
print(f" Mode: Native DrawingML shapes (directly editable)")
|
|
726
|
+
print(
|
|
727
|
+
" Native table/chart objects: "
|
|
728
|
+
f"{'Enabled' if native_objects else 'Disabled'}"
|
|
729
|
+
)
|
|
730
|
+
if image_optimize:
|
|
731
|
+
if image_sizing == 'display':
|
|
732
|
+
image_mode = (
|
|
733
|
+
f"display scale {image_scale:g}, "
|
|
734
|
+
f"max {image_max_dimension or 'unlimited'} px"
|
|
735
|
+
)
|
|
736
|
+
else:
|
|
737
|
+
image_mode = f"cap max {image_max_dimension or 'unlimited'} px"
|
|
738
|
+
print(
|
|
739
|
+
" Image optimization: Enabled "
|
|
740
|
+
f"({image_mode}, JPEG q{image_quality})"
|
|
741
|
+
)
|
|
742
|
+
else:
|
|
743
|
+
print(" Image optimization: Disabled")
|
|
744
|
+
elif use_compat_mode:
|
|
745
|
+
print(f" Compatibility mode: Enabled (PNG + SVG dual format)")
|
|
746
|
+
print(f" PNG renderer: {renderer_name} {renderer_status}")
|
|
747
|
+
else:
|
|
748
|
+
print(f" Compatibility mode: Disabled (pure SVG)")
|
|
749
|
+
if transition:
|
|
750
|
+
trans_name = TRANSITIONS.get(transition, {}).get('name', transition) if TRANSITIONS else transition
|
|
751
|
+
print(f" Transition effect: {trans_name}")
|
|
752
|
+
if enable_notes and notes:
|
|
753
|
+
print(f" Speaker notes: {len(notes)} page(s)")
|
|
754
|
+
elif enable_notes:
|
|
755
|
+
print(f" Speaker notes: Enabled (no notes files found)")
|
|
756
|
+
else:
|
|
757
|
+
print(f" Speaker notes: Disabled")
|
|
758
|
+
print()
|
|
759
|
+
|
|
760
|
+
animation_cli_overrides = animation_cli_overrides or {}
|
|
761
|
+
|
|
762
|
+
temp_dir = _create_writable_work_dir(output_path)
|
|
763
|
+
|
|
764
|
+
try:
|
|
765
|
+
# Create base PPTX with python-pptx
|
|
766
|
+
prs = Presentation()
|
|
767
|
+
prs.slide_width = width_emu
|
|
768
|
+
prs.slide_height = height_emu
|
|
769
|
+
|
|
770
|
+
blank_layout = prs.slide_layouts[6]
|
|
771
|
+
for _ in svg_files:
|
|
772
|
+
prs.slides.add_slide(blank_layout)
|
|
773
|
+
|
|
774
|
+
base_pptx = temp_dir / 'base.pptx'
|
|
775
|
+
prs.save(str(base_pptx))
|
|
776
|
+
|
|
777
|
+
# Extract PPTX
|
|
778
|
+
extract_dir = temp_dir / 'pptx_content'
|
|
779
|
+
with zipfile.ZipFile(base_pptx, 'r') as zf:
|
|
780
|
+
zf.extractall(extract_dir)
|
|
781
|
+
|
|
782
|
+
media_dir = extract_dir / 'ppt' / 'media'
|
|
783
|
+
media_dir.mkdir(exist_ok=True)
|
|
784
|
+
|
|
785
|
+
prerender_results: dict[int, bool] | None = None
|
|
786
|
+
if not use_native_shapes and use_compat_mode and PNG_RENDERER is not None:
|
|
787
|
+
if workers is None:
|
|
788
|
+
resolved_workers = min(os.cpu_count() or 2, len(svg_files), 8)
|
|
789
|
+
else:
|
|
790
|
+
resolved_workers = max(0, workers)
|
|
791
|
+
if verbose:
|
|
792
|
+
cache_label = str(cache_dir) if cache_dir else 'disabled'
|
|
793
|
+
mode = f'parallel x{resolved_workers}' if resolved_workers > 1 else 'sequential'
|
|
794
|
+
print(f" Pre-rendering PNGs ({mode}, cache: {cache_label})")
|
|
795
|
+
prerender_results = _prerender_legacy_pngs(
|
|
796
|
+
svg_files, media_dir, pixel_width, pixel_height,
|
|
797
|
+
cache_dir, resolved_workers, verbose,
|
|
798
|
+
)
|
|
799
|
+
if verbose:
|
|
800
|
+
print()
|
|
801
|
+
|
|
802
|
+
success_count = 0
|
|
803
|
+
has_any_image = False
|
|
804
|
+
media_cache: dict[tuple[str, str], str] = {}
|
|
805
|
+
image_exts_used: set[str] = set()
|
|
806
|
+
package_exts_used: set[str] = set()
|
|
807
|
+
package_content_overrides: dict[str, str] = {}
|
|
808
|
+
notes_slides_created: set[int] = set()
|
|
809
|
+
narration_slides_created: set[int] = set()
|
|
810
|
+
audio_exts_used: set[str] = set()
|
|
811
|
+
mixed_animation_offset = 0
|
|
812
|
+
conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else None
|
|
813
|
+
|
|
814
|
+
for i, svg_path in enumerate(svg_files, 1):
|
|
815
|
+
slide_num = i
|
|
816
|
+
|
|
817
|
+
try:
|
|
818
|
+
# ---- Native shapes mode ----
|
|
819
|
+
if use_native_shapes:
|
|
820
|
+
slide_cfg = _slide_config(animation_config, svg_path.stem)
|
|
821
|
+
(
|
|
822
|
+
slide_xml,
|
|
823
|
+
media_files_dict,
|
|
824
|
+
rel_entries,
|
|
825
|
+
anim_targets,
|
|
826
|
+
package_files_dict,
|
|
827
|
+
content_type_overrides,
|
|
828
|
+
) = (
|
|
829
|
+
convert_svg_to_slide_shapes(
|
|
830
|
+
svg_path, slide_num=slide_num, verbose=verbose,
|
|
831
|
+
merge_paragraphs=merge_paragraphs,
|
|
832
|
+
image_optimize=image_optimize,
|
|
833
|
+
image_max_dimension=image_max_dimension,
|
|
834
|
+
image_sizing=image_sizing,
|
|
835
|
+
image_scale=image_scale,
|
|
836
|
+
image_quality=image_quality,
|
|
837
|
+
native_objects=native_objects,
|
|
838
|
+
trace_out=conversion_trace,
|
|
839
|
+
)
|
|
840
|
+
)
|
|
841
|
+
slide_transition, slide_transition_duration, slide_auto_advance = (
|
|
842
|
+
_slide_transition_settings(
|
|
843
|
+
slide_cfg,
|
|
844
|
+
transition,
|
|
845
|
+
transition_duration,
|
|
846
|
+
auto_advance,
|
|
847
|
+
animation_cli_overrides,
|
|
848
|
+
)
|
|
849
|
+
)
|
|
850
|
+
(
|
|
851
|
+
slide_animation,
|
|
852
|
+
slide_animation_duration,
|
|
853
|
+
slide_animation_stagger,
|
|
854
|
+
slide_animation_trigger,
|
|
855
|
+
) = _slide_animation_settings(
|
|
856
|
+
slide_cfg,
|
|
857
|
+
animation,
|
|
858
|
+
animation_duration,
|
|
859
|
+
animation_stagger,
|
|
860
|
+
animation_trigger,
|
|
861
|
+
animation_cli_overrides,
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
# Order matters: OOXML schema requires <p:transition>
|
|
865
|
+
# to precede <p:timing> inside <p:sld>. Both use the same
|
|
866
|
+
# </p:sld> string-replace anchor, so transition must be
|
|
867
|
+
# injected first and timing second.
|
|
868
|
+
if slide_transition and ANIMATIONS_AVAILABLE and create_transition_xml:
|
|
869
|
+
transition_xml = '\n' + create_transition_xml(
|
|
870
|
+
effect=slide_transition,
|
|
871
|
+
duration=slide_transition_duration,
|
|
872
|
+
advance_after=slide_auto_advance,
|
|
873
|
+
)
|
|
874
|
+
slide_xml = slide_xml.replace(
|
|
875
|
+
'</p:sld>',
|
|
876
|
+
transition_xml + '\n</p:sld>',
|
|
877
|
+
)
|
|
878
|
+
|
|
879
|
+
if (slide_animation and slide_animation != 'none'
|
|
880
|
+
and create_sequence_timing_xml
|
|
881
|
+
and pick_animation_effect
|
|
882
|
+
and anim_targets):
|
|
883
|
+
seq_targets, mixed_count = _build_sequence_targets(
|
|
884
|
+
anim_targets,
|
|
885
|
+
slide_cfg,
|
|
886
|
+
slide_animation,
|
|
887
|
+
slide_animation_duration,
|
|
888
|
+
slide_animation_stagger,
|
|
889
|
+
mixed_animation_offset,
|
|
890
|
+
)
|
|
891
|
+
if slide_animation in ('mixed', 'auto'):
|
|
892
|
+
mixed_animation_offset += mixed_count
|
|
893
|
+
timing_xml = '\n' + create_sequence_timing_xml(
|
|
894
|
+
seq_targets, duration=slide_animation_duration,
|
|
895
|
+
trigger=slide_animation_trigger,
|
|
896
|
+
)
|
|
897
|
+
slide_xml = slide_xml.replace(
|
|
898
|
+
'</p:sld>',
|
|
899
|
+
timing_xml + '\n</p:sld>',
|
|
900
|
+
)
|
|
901
|
+
|
|
902
|
+
# Write slide XML
|
|
903
|
+
slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
|
|
904
|
+
with open(slide_xml_path, 'w', encoding='utf-8') as f:
|
|
905
|
+
f.write(slide_xml)
|
|
906
|
+
|
|
907
|
+
# Write media files
|
|
908
|
+
media_name_map: dict[str, str] = {}
|
|
909
|
+
for media_name, media_data in media_files_dict.items():
|
|
910
|
+
ext = media_name.rsplit('.', 1)[-1].lower()
|
|
911
|
+
media_hash = hashlib.sha256(media_data).hexdigest()
|
|
912
|
+
cache_key = (ext, media_hash)
|
|
913
|
+
cached_name = media_cache.get(cache_key)
|
|
914
|
+
|
|
915
|
+
if cached_name is None:
|
|
916
|
+
cached_name = f'image_{media_hash[:16]}.{ext}'
|
|
917
|
+
media_cache[cache_key] = cached_name
|
|
918
|
+
with open(media_dir / cached_name, 'wb') as f:
|
|
919
|
+
f.write(media_data)
|
|
920
|
+
|
|
921
|
+
media_name_map[media_name] = cached_name
|
|
922
|
+
|
|
923
|
+
for rel in rel_entries:
|
|
924
|
+
target = rel.get('target', '')
|
|
925
|
+
if not target.startswith('../media/'):
|
|
926
|
+
continue
|
|
927
|
+
media_name = target.split('../media/', 1)[1]
|
|
928
|
+
mapped_name = media_name_map.get(media_name)
|
|
929
|
+
if mapped_name:
|
|
930
|
+
rel['target'] = f'../media/{mapped_name}'
|
|
931
|
+
|
|
932
|
+
# Write non-media OOXML package parts produced by native
|
|
933
|
+
# object converters, e.g. chart XML, chart rels, and
|
|
934
|
+
# embedded workbooks.
|
|
935
|
+
for part_name, part_data in package_files_dict.items():
|
|
936
|
+
package_path = extract_dir / part_name
|
|
937
|
+
package_path.parent.mkdir(parents=True, exist_ok=True)
|
|
938
|
+
with open(package_path, 'wb') as f:
|
|
939
|
+
f.write(part_data)
|
|
940
|
+
suffix = package_path.suffix.lstrip('.').lower()
|
|
941
|
+
if suffix:
|
|
942
|
+
package_exts_used.add(suffix)
|
|
943
|
+
package_content_overrides.update(content_type_overrides)
|
|
944
|
+
|
|
945
|
+
# Build relationships XML
|
|
946
|
+
rels_dir = extract_dir / 'ppt' / 'slides' / '_rels'
|
|
947
|
+
rels_dir.mkdir(exist_ok=True)
|
|
948
|
+
rels_path = rels_dir / f'slide{slide_num}.xml.rels'
|
|
949
|
+
|
|
950
|
+
extra_rels = ''
|
|
951
|
+
for rel in rel_entries:
|
|
952
|
+
extra_rels += (
|
|
953
|
+
f'\n <Relationship Id="{rel["id"]}" '
|
|
954
|
+
f'Type="{rel["type"]}" Target="{rel["target"]}"/>'
|
|
955
|
+
)
|
|
956
|
+
|
|
957
|
+
rels_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
958
|
+
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
959
|
+
<Relationship Id="rId1"
|
|
960
|
+
Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
|
|
961
|
+
Target="../slideLayouts/slideLayout1.xml"/>{extra_rels}
|
|
962
|
+
</Relationships>'''
|
|
963
|
+
with open(rels_path, 'w', encoding='utf-8') as f:
|
|
964
|
+
f.write(rels_xml)
|
|
965
|
+
|
|
966
|
+
# Track image formats for Content_Types
|
|
967
|
+
for media_name in media_name_map.values():
|
|
968
|
+
ext = media_name.rsplit('.', 1)[-1].lower()
|
|
969
|
+
_content_type_for_extension(ext)
|
|
970
|
+
image_exts_used.add(ext)
|
|
971
|
+
has_any_image = True
|
|
972
|
+
|
|
973
|
+
# ---- Legacy SVG embedding mode ----
|
|
974
|
+
else:
|
|
975
|
+
slide_cfg = _slide_config(animation_config, svg_path.stem)
|
|
976
|
+
slide_transition, slide_transition_duration, slide_auto_advance = (
|
|
977
|
+
_slide_transition_settings(
|
|
978
|
+
slide_cfg,
|
|
979
|
+
transition,
|
|
980
|
+
transition_duration,
|
|
981
|
+
auto_advance,
|
|
982
|
+
animation_cli_overrides,
|
|
983
|
+
)
|
|
984
|
+
)
|
|
985
|
+
svg_filename = f'image{i}.svg'
|
|
986
|
+
png_filename = f'image{i}.png'
|
|
987
|
+
png_rid = 'rId2'
|
|
988
|
+
svg_rid = 'rId3' if use_compat_mode else 'rId2'
|
|
989
|
+
|
|
990
|
+
shutil.copy(svg_path, media_dir / svg_filename)
|
|
991
|
+
|
|
992
|
+
slide_has_png = False
|
|
993
|
+
if use_compat_mode:
|
|
994
|
+
if prerender_results is not None:
|
|
995
|
+
png_success = prerender_results.get(i, False)
|
|
996
|
+
else:
|
|
997
|
+
png_path = media_dir / png_filename
|
|
998
|
+
png_success = convert_svg_to_png(
|
|
999
|
+
svg_path, png_path,
|
|
1000
|
+
width=pixel_width, height=pixel_height,
|
|
1001
|
+
)
|
|
1002
|
+
if png_success:
|
|
1003
|
+
slide_has_png = True
|
|
1004
|
+
has_any_image = True
|
|
1005
|
+
image_exts_used.add('png')
|
|
1006
|
+
else:
|
|
1007
|
+
if verbose:
|
|
1008
|
+
print(
|
|
1009
|
+
f" [{i}/{len(svg_files)}] {svg_path.name} - "
|
|
1010
|
+
"PNG generation failed, using pure SVG"
|
|
1011
|
+
)
|
|
1012
|
+
svg_rid = 'rId2'
|
|
1013
|
+
|
|
1014
|
+
slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
|
|
1015
|
+
slide_xml = create_slide_xml_with_svg(
|
|
1016
|
+
slide_num,
|
|
1017
|
+
png_rid=png_rid, svg_rid=svg_rid,
|
|
1018
|
+
width_emu=width_emu, height_emu=height_emu,
|
|
1019
|
+
transition=slide_transition,
|
|
1020
|
+
transition_duration=slide_transition_duration,
|
|
1021
|
+
auto_advance=slide_auto_advance,
|
|
1022
|
+
use_compat_mode=(use_compat_mode and slide_has_png),
|
|
1023
|
+
)
|
|
1024
|
+
with open(slide_xml_path, 'w', encoding='utf-8') as f:
|
|
1025
|
+
f.write(slide_xml)
|
|
1026
|
+
|
|
1027
|
+
rels_dir = extract_dir / 'ppt' / 'slides' / '_rels'
|
|
1028
|
+
rels_dir.mkdir(exist_ok=True)
|
|
1029
|
+
rels_path = rels_dir / f'slide{slide_num}.xml.rels'
|
|
1030
|
+
rels_xml = create_slide_rels_xml(
|
|
1031
|
+
png_rid=png_rid, png_filename=png_filename,
|
|
1032
|
+
svg_rid=svg_rid, svg_filename=svg_filename,
|
|
1033
|
+
use_compat_mode=(use_compat_mode and slide_has_png),
|
|
1034
|
+
)
|
|
1035
|
+
with open(rels_path, 'w', encoding='utf-8') as f:
|
|
1036
|
+
f.write(rels_xml)
|
|
1037
|
+
|
|
1038
|
+
# --- Process notes (shared between native and legacy mode) ---
|
|
1039
|
+
notes_content = ''
|
|
1040
|
+
if enable_notes:
|
|
1041
|
+
svg_stem = svg_path.stem
|
|
1042
|
+
notes_content = notes.get(svg_stem, '') if notes else ''
|
|
1043
|
+
notes_text = markdown_to_plain_text(notes_content) if notes_content else ''
|
|
1044
|
+
if notes_text:
|
|
1045
|
+
_ensure_notes_master(extract_dir)
|
|
1046
|
+
|
|
1047
|
+
notes_slides_dir = extract_dir / 'ppt' / 'notesSlides'
|
|
1048
|
+
notes_slides_dir.mkdir(exist_ok=True)
|
|
1049
|
+
|
|
1050
|
+
notes_xml_path = notes_slides_dir / f'notesSlide{slide_num}.xml'
|
|
1051
|
+
notes_xml = create_notes_slide_xml(slide_num, notes_text)
|
|
1052
|
+
with open(notes_xml_path, 'w', encoding='utf-8') as f:
|
|
1053
|
+
f.write(notes_xml)
|
|
1054
|
+
|
|
1055
|
+
notes_rels_dir = notes_slides_dir / '_rels'
|
|
1056
|
+
notes_rels_dir.mkdir(exist_ok=True)
|
|
1057
|
+
notes_rels_path = notes_rels_dir / f'notesSlide{slide_num}.xml.rels'
|
|
1058
|
+
notes_rels_xml = create_notes_slide_rels_xml(slide_num)
|
|
1059
|
+
with open(notes_rels_path, 'w', encoding='utf-8') as f:
|
|
1060
|
+
f.write(notes_rels_xml)
|
|
1061
|
+
|
|
1062
|
+
_append_relationship(
|
|
1063
|
+
rels_path,
|
|
1064
|
+
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide',
|
|
1065
|
+
f'../notesSlides/notesSlide{slide_num}.xml',
|
|
1066
|
+
)
|
|
1067
|
+
notes_slides_created.add(slide_num)
|
|
1068
|
+
|
|
1069
|
+
# --- Process narration audio (shared between native and legacy mode) ---
|
|
1070
|
+
svg_stem = svg_path.stem
|
|
1071
|
+
audio_path = narration_audio.get(svg_stem) if narration_audio else None
|
|
1072
|
+
if audio_path:
|
|
1073
|
+
slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
|
|
1074
|
+
rels_path = extract_dir / 'ppt' / 'slides' / '_rels' / f'slide{slide_num}.xml.rels'
|
|
1075
|
+
|
|
1076
|
+
ext = audio_path.suffix.lower()
|
|
1077
|
+
media_name = f'narration{slide_num}{ext}'
|
|
1078
|
+
shutil.copy2(audio_path, media_dir / media_name)
|
|
1079
|
+
audio_exts_used.add(ext)
|
|
1080
|
+
|
|
1081
|
+
poster_name = 'narration_poster.png'
|
|
1082
|
+
poster_path = media_dir / poster_name
|
|
1083
|
+
if not poster_path.exists():
|
|
1084
|
+
poster_path.write_bytes(AUDIO_MARKER_PNG_BYTES)
|
|
1085
|
+
has_any_image = True
|
|
1086
|
+
image_exts_used.add('png')
|
|
1087
|
+
|
|
1088
|
+
media_rid = _append_relationship(
|
|
1089
|
+
rels_path,
|
|
1090
|
+
MEDIA_REL_TYPE,
|
|
1091
|
+
f'../media/{media_name}',
|
|
1092
|
+
)
|
|
1093
|
+
audio_rid = _append_relationship(
|
|
1094
|
+
rels_path,
|
|
1095
|
+
AUDIO_REL_TYPE,
|
|
1096
|
+
f'../media/{media_name}',
|
|
1097
|
+
)
|
|
1098
|
+
poster_rid = _append_relationship(
|
|
1099
|
+
rels_path,
|
|
1100
|
+
IMAGE_REL_TYPE,
|
|
1101
|
+
f'../media/{poster_name}',
|
|
1102
|
+
)
|
|
1103
|
+
|
|
1104
|
+
slide_xml = slide_xml_path.read_text(encoding='utf-8')
|
|
1105
|
+
narration_shape_id = next_shape_id(slide_xml)
|
|
1106
|
+
slide_xml = inject_narration(
|
|
1107
|
+
slide_xml,
|
|
1108
|
+
shape_id=narration_shape_id,
|
|
1109
|
+
shape_name=media_name,
|
|
1110
|
+
audio_rid=audio_rid,
|
|
1111
|
+
media_rid=media_rid,
|
|
1112
|
+
poster_rid=poster_rid,
|
|
1113
|
+
)
|
|
1114
|
+
|
|
1115
|
+
if use_narration_timings:
|
|
1116
|
+
duration = probe_audio_duration(audio_path)
|
|
1117
|
+
if duration is None:
|
|
1118
|
+
raise RuntimeError(
|
|
1119
|
+
f"Unable to read narration duration with ffprobe: {audio_path}"
|
|
1120
|
+
)
|
|
1121
|
+
slide_xml = apply_recorded_timing(
|
|
1122
|
+
slide_xml,
|
|
1123
|
+
advance_after=duration + narration_padding,
|
|
1124
|
+
transition_duration=slide_transition_duration,
|
|
1125
|
+
transition_effect=slide_transition or 'fade',
|
|
1126
|
+
)
|
|
1127
|
+
slide_xml_path.write_text(slide_xml, encoding='utf-8')
|
|
1128
|
+
narration_slides_created.add(slide_num)
|
|
1129
|
+
|
|
1130
|
+
if verbose:
|
|
1131
|
+
if use_native_shapes:
|
|
1132
|
+
mode_str = " (Native)"
|
|
1133
|
+
elif use_compat_mode and not use_native_shapes:
|
|
1134
|
+
mode_str = " (PNG+SVG)" if has_any_image else " (SVG)"
|
|
1135
|
+
else:
|
|
1136
|
+
mode_str = " (SVG)"
|
|
1137
|
+
has_notes = slide_num in notes_slides_created
|
|
1138
|
+
notes_str = " +notes" if has_notes else ""
|
|
1139
|
+
narration_str = " +narration" if slide_num in narration_slides_created else ""
|
|
1140
|
+
print(f" [{i}/{len(svg_files)}] {svg_path.name}{mode_str}{notes_str}{narration_str}")
|
|
1141
|
+
|
|
1142
|
+
success_count += 1
|
|
1143
|
+
|
|
1144
|
+
except Exception as e:
|
|
1145
|
+
if verbose:
|
|
1146
|
+
print(f" [{i}/{len(svg_files)}] {svg_path.name} - Error: {e}")
|
|
1147
|
+
if use_native_shapes:
|
|
1148
|
+
raise
|
|
1149
|
+
|
|
1150
|
+
# Update [Content_Types].xml
|
|
1151
|
+
content_types_path = extract_dir / '[Content_Types].xml'
|
|
1152
|
+
with open(content_types_path, 'r', encoding='utf-8') as f:
|
|
1153
|
+
content_types = f.read()
|
|
1154
|
+
|
|
1155
|
+
if not use_native_shapes:
|
|
1156
|
+
content_types = _add_default_content_type(content_types, 'svg', 'image/svg+xml')
|
|
1157
|
+
for ext in sorted(image_exts_used):
|
|
1158
|
+
content_types = _add_default_content_type(
|
|
1159
|
+
content_types,
|
|
1160
|
+
ext,
|
|
1161
|
+
_content_type_for_extension(ext),
|
|
1162
|
+
)
|
|
1163
|
+
if 'xlsx' in package_exts_used:
|
|
1164
|
+
content_types = _add_default_content_type(
|
|
1165
|
+
content_types,
|
|
1166
|
+
'xlsx',
|
|
1167
|
+
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
1168
|
+
)
|
|
1169
|
+
for part_name, content_type in sorted(package_content_overrides.items()):
|
|
1170
|
+
content_types = _add_content_type_override(content_types, part_name, content_type)
|
|
1171
|
+
with open(content_types_path, 'w', encoding='utf-8') as f:
|
|
1172
|
+
f.write(content_types)
|
|
1173
|
+
|
|
1174
|
+
if audio_exts_used:
|
|
1175
|
+
for ext in sorted(audio_exts_used):
|
|
1176
|
+
content_type = AUDIO_CONTENT_TYPES.get(ext)
|
|
1177
|
+
if content_type:
|
|
1178
|
+
content_types = _add_default_content_type(content_types, ext, content_type)
|
|
1179
|
+
if 'Extension="png"' not in content_types:
|
|
1180
|
+
content_types = _add_default_content_type(content_types, 'png', 'image/png')
|
|
1181
|
+
with open(content_types_path, 'w', encoding='utf-8') as f:
|
|
1182
|
+
f.write(content_types)
|
|
1183
|
+
|
|
1184
|
+
# Add notes master / slides content types
|
|
1185
|
+
if enable_notes and notes_slides_created:
|
|
1186
|
+
notes_theme_override = (
|
|
1187
|
+
' <Override PartName="/ppt/theme/theme2.xml" '
|
|
1188
|
+
'ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>'
|
|
1189
|
+
)
|
|
1190
|
+
if notes_theme_override not in content_types:
|
|
1191
|
+
content_types = content_types.replace(
|
|
1192
|
+
'</Types>',
|
|
1193
|
+
notes_theme_override + '\n</Types>',
|
|
1194
|
+
)
|
|
1195
|
+
notes_master_override = (
|
|
1196
|
+
' <Override PartName="/ppt/notesMasters/notesMaster1.xml" '
|
|
1197
|
+
'ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>'
|
|
1198
|
+
)
|
|
1199
|
+
if notes_master_override not in content_types:
|
|
1200
|
+
content_types = content_types.replace(
|
|
1201
|
+
'</Types>',
|
|
1202
|
+
notes_master_override + '\n</Types>',
|
|
1203
|
+
)
|
|
1204
|
+
for i in sorted(notes_slides_created):
|
|
1205
|
+
override = (
|
|
1206
|
+
f' <Override PartName="/ppt/notesSlides/notesSlide{i}.xml" '
|
|
1207
|
+
f'ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>'
|
|
1208
|
+
)
|
|
1209
|
+
if override not in content_types:
|
|
1210
|
+
content_types = content_types.replace('</Types>', override + '\n</Types>')
|
|
1211
|
+
with open(content_types_path, 'w', encoding='utf-8') as f:
|
|
1212
|
+
f.write(content_types)
|
|
1213
|
+
|
|
1214
|
+
rels_problems = _verify_internal_rels_targets(extract_dir)
|
|
1215
|
+
if rels_problems:
|
|
1216
|
+
details = '\n'.join(f' - {p}' for p in rels_problems)
|
|
1217
|
+
raise RuntimeError(
|
|
1218
|
+
'PPTX package contains dangling internal relationship targets; '
|
|
1219
|
+
'PowerPoint will report the file as corrupt:\n' + details
|
|
1220
|
+
)
|
|
1221
|
+
|
|
1222
|
+
# Replace the python-pptx base-template metadata (stale "Steve Canny"
|
|
1223
|
+
# author, 2013 dates, "generated using python-pptx", Slides=0) with
|
|
1224
|
+
# accurate, tool-neutral document properties.
|
|
1225
|
+
pres_format = _presentation_format(width_emu, height_emu)
|
|
1226
|
+
_stamp_docprops(extract_dir, len(svg_files), pres_format, doc_metadata)
|
|
1227
|
+
|
|
1228
|
+
# Repackage PPTX to a temporary file first. The public output path is
|
|
1229
|
+
# replaced only after every slide and relationship has succeeded.
|
|
1230
|
+
temp_output_path = temp_dir / 'result.pptx'
|
|
1231
|
+
with zipfile.ZipFile(temp_output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
1232
|
+
for file_path in extract_dir.rglob('*'):
|
|
1233
|
+
if file_path.is_file():
|
|
1234
|
+
arcname = file_path.relative_to(extract_dir)
|
|
1235
|
+
zf.write(file_path, arcname)
|
|
1236
|
+
shutil.move(str(temp_output_path), str(output_path))
|
|
1237
|
+
permission_warnings = _relax_output_permissions(output_path)
|
|
1238
|
+
|
|
1239
|
+
if conversion_trace_path and conversion_trace is not None:
|
|
1240
|
+
conversion_trace_path.parent.mkdir(parents=True, exist_ok=True)
|
|
1241
|
+
payload = {
|
|
1242
|
+
'output': str(output_path),
|
|
1243
|
+
'slide_count': len(svg_files),
|
|
1244
|
+
'slides': conversion_trace,
|
|
1245
|
+
}
|
|
1246
|
+
conversion_trace_path.write_text(
|
|
1247
|
+
json.dumps(payload, ensure_ascii=False, indent=2),
|
|
1248
|
+
encoding='utf-8',
|
|
1249
|
+
)
|
|
1250
|
+
|
|
1251
|
+
if verbose:
|
|
1252
|
+
print()
|
|
1253
|
+
print(f"[Done] Saved: {output_path}")
|
|
1254
|
+
for warning in permission_warnings:
|
|
1255
|
+
print(f" [warn] {warning}")
|
|
1256
|
+
if conversion_trace_path and conversion_trace is not None:
|
|
1257
|
+
print(f" Trace: {conversion_trace_path}")
|
|
1258
|
+
print(f" Succeeded: {success_count}, Failed: {len(svg_files) - success_count}")
|
|
1259
|
+
if use_compat_mode and has_any_image:
|
|
1260
|
+
print(f" Mode: Office compatibility mode (supports all Office versions)")
|
|
1261
|
+
if renderer_hint:
|
|
1262
|
+
print(f" [Tip] {renderer_hint}")
|
|
1263
|
+
|
|
1264
|
+
return success_count == len(svg_files)
|
|
1265
|
+
|
|
1266
|
+
finally:
|
|
1267
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|