dknowc-dsh 1.0.3 → 1.1.0

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.
Files changed (173) hide show
  1. package/README.md +9 -4
  2. package/package.json +2 -2
  3. package/skills/dknowc-official-doc-writer/SKILL.md +17 -8
  4. package/skills/dknowc-official-doc-writer/reference/sample_search_result.md +48 -0
  5. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +75 -0
  6. package/skills/dknowc-official-doc-writer/reference/search_intro.md +72 -8
  7. package/skills/dknowc-official-doc-writer/scripts/register.mjs +1 -1
  8. package/skills/dknowc-ppt-assistant/README.md +54 -0
  9. package/skills/dknowc-ppt-assistant/SKILL.md +151 -0
  10. package/skills/dknowc-ppt-assistant/THIRD_PARTY_NOTICES.md +36 -0
  11. package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
  12. package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
  13. package/skills/dknowc-ppt-assistant/projects/.gitkeep +0 -0
  14. package/skills/dknowc-ppt-assistant/references/content-pack.md +55 -0
  15. package/skills/dknowc-ppt-assistant/references/material_usage.md +51 -0
  16. package/skills/dknowc-ppt-assistant/references/sample_effect.html +89 -0
  17. package/skills/dknowc-ppt-assistant/references/sample_search_result.md +48 -0
  18. package/skills/dknowc-ppt-assistant/references/search_intro.md +79 -0
  19. package/skills/dknowc-ppt-assistant/references/style-presets.md +126 -0
  20. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +81 -0
  21. package/skills/dknowc-ppt-assistant/references/upstream-docs/svg-pipeline.md +842 -0
  22. package/skills/dknowc-ppt-assistant/references/upstream-example/01_cover.svg +28 -0
  23. package/skills/dknowc-ppt-assistant/references/upstream-example/02_quote.svg +38 -0
  24. package/skills/dknowc-ppt-assistant/references/upstream-example/03_origin.svg +96 -0
  25. package/skills/dknowc-ppt-assistant/references/upstream-example/README.md +15 -0
  26. package/skills/dknowc-ppt-assistant/references/upstream-example/design_spec.md +408 -0
  27. package/skills/dknowc-ppt-assistant/references/upstream-example/spec_lock.md +78 -0
  28. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +279 -0
  29. package/skills/dknowc-ppt-assistant/scripts/check_release.py +106 -0
  30. package/skills/dknowc-ppt-assistant/scripts/compact_svg_coordinates.py +345 -0
  31. package/skills/dknowc-ppt-assistant/scripts/config.py +707 -0
  32. package/skills/dknowc-ppt-assistant/scripts/console_encoding.py +33 -0
  33. package/skills/dknowc-ppt-assistant/scripts/error_helper.py +434 -0
  34. package/skills/dknowc-ppt-assistant/scripts/finalize_svg.py +507 -0
  35. package/skills/dknowc-ppt-assistant/scripts/hyperlink_contract.py +399 -0
  36. package/skills/dknowc-ppt-assistant/scripts/initialize.py +182 -0
  37. package/skills/dknowc-ppt-assistant/scripts/language_tags.py +283 -0
  38. package/skills/dknowc-ppt-assistant/scripts/mcp_direct.py +158 -0
  39. package/skills/dknowc-ppt-assistant/scripts/native_payloads.py +655 -0
  40. package/skills/dknowc-ppt-assistant/scripts/pptx_animation_presets.json +3440 -0
  41. package/skills/dknowc-ppt-assistant/scripts/pptx_animations.py +3965 -0
  42. package/skills/dknowc-ppt-assistant/scripts/pptx_effects.py +143 -0
  43. package/skills/dknowc-ppt-assistant/scripts/pptx_opc_validation.py +346 -0
  44. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/__init__.py +130 -0
  45. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-APACHE-2.0.txt +202 -0
  46. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-OPEN-XML-SDK-MIT.txt +23 -0
  47. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/NOTICE.md +54 -0
  48. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeDefinitions.xml +19898 -0
  49. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeSemantics.json +1217 -0
  50. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/shape_type_values.txt +187 -0
  51. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/errors.py +39 -0
  52. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/formula.py +336 -0
  53. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/loader.py +364 -0
  54. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/models.py +201 -0
  55. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/registry.py +270 -0
  56. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantic_hash.py +456 -0
  57. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantics.py +543 -0
  58. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/xml_safety.py +21 -0
  59. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/__init__.py +21 -0
  60. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/animation_import.py +287 -0
  61. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chart_to_svg.py +2377 -0
  62. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chartex_to_svg.py +422 -0
  63. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/color_resolver.py +894 -0
  64. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/converter.py +1143 -0
  65. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/custgeom_to_svg.py +165 -0
  66. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/effect_to_svg.py +410 -0
  67. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/emu_units.py +258 -0
  68. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/fill_to_svg.py +816 -0
  69. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/formula_import.py +611 -0
  70. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/hyperlinks.py +93 -0
  71. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/import_diagnostics.py +37 -0
  72. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ln_to_svg.py +362 -0
  73. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/normalized_chart_svg.py +1217 -0
  74. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ooxml_loader.py +506 -0
  75. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/pic_to_svg.py +653 -0
  76. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_authoring.py +894 -0
  77. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_registry_to_svg.py +216 -0
  78. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_svg_markup.py +198 -0
  79. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/prstgeom_to_svg.py +162 -0
  80. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/shape_walker.py +556 -0
  81. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/slide_to_svg.py +2002 -0
  82. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/tbl_to_svg.py +1841 -0
  83. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/transition_import.py +201 -0
  84. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/txbody_to_svg.py +1433 -0
  85. package/skills/dknowc-ppt-assistant/scripts/pptx_transitions.py +3153 -0
  86. package/skills/dknowc-ppt-assistant/scripts/preset_shape_svg.py +450 -0
  87. package/skills/dknowc-ppt-assistant/scripts/project_utils.py +645 -0
  88. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +183 -0
  89. package/skills/dknowc-ppt-assistant/scripts/register_template.py +1327 -0
  90. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1048 -0
  91. package/skills/dknowc-ppt-assistant/scripts/resource_paths.py +282 -0
  92. package/skills/dknowc-ppt-assistant/scripts/shape_boolean_svg.py +189 -0
  93. package/skills/dknowc-ppt-assistant/scripts/slide_roster.py +44 -0
  94. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/__init__.py +12 -0
  95. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/align_embed_images.py +672 -0
  96. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/crop_images.py +370 -0
  97. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_icons.py +564 -0
  98. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_images.py +288 -0
  99. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/fix_image_aspect.py +389 -0
  100. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/flatten_tspan.py +948 -0
  101. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/svg_rect_to_path.py +346 -0
  102. package/skills/dknowc-ppt-assistant/scripts/svg_quality/__init__.py +15 -0
  103. package/skills/dknowc-ppt-assistant/scripts/svg_quality/checker.py +7791 -0
  104. package/skills/dknowc-ppt-assistant/scripts/svg_quality/cli.py +193 -0
  105. package/skills/dknowc-ppt-assistant/scripts/svg_quality/svg_contracts.py +1121 -0
  106. package/skills/dknowc-ppt-assistant/scripts/svg_quality/xml_support.py +35 -0
  107. package/skills/dknowc-ppt-assistant/scripts/svg_quality_checker.py +59 -0
  108. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/__init__.py +37 -0
  109. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/animation_config.py +1622 -0
  110. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/canvas_contract.py +226 -0
  111. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/__init__.py +1 -0
  112. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/context.py +291 -0
  113. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/converter.py +1980 -0
  114. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/elements.py +5272 -0
  115. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/hyperlinks.py +162 -0
  116. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/paths.py +847 -0
  117. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/styles.py +752 -0
  118. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/text_properties.py +796 -0
  119. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_colors.py +283 -0
  120. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_fonts.py +330 -0
  121. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/utils.py +3555 -0
  122. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/geometry_properties.py +140 -0
  123. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/__init__.py +356 -0
  124. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_data.py +1449 -0
  125. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_style.py +886 -0
  126. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_xml.py +1495 -0
  127. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chartex.py +272 -0
  128. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/fallback_hash.py +161 -0
  129. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula.py +243 -0
  130. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_ast.py +592 -0
  131. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_compiler.py +96 -0
  132. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_omml.py +1049 -0
  133. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_parser.py +2181 -0
  134. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_profile.py +739 -0
  135. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_run_properties.py +234 -0
  136. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/inline_formula.py +311 -0
  137. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_attributes.py +182 -0
  138. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_common.py +806 -0
  139. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_status.py +190 -0
  140. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/table.py +1113 -0
  141. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/workbook.py +216 -0
  142. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/__init__.py +1 -0
  143. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/builder.py +6273 -0
  144. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/cli.py +2059 -0
  145. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/dimensions.py +189 -0
  146. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/discovery.py +120 -0
  147. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/media.py +160 -0
  148. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/narration.py +696 -0
  149. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/notes.py +336 -0
  150. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/slide_xml.py +138 -0
  151. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_structure.py +3457 -0
  152. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_validation.py +1536 -0
  153. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/semantic_markers.py +240 -0
  154. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/shape_boolean.py +1355 -0
  155. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/text_outline.py +1121 -0
  156. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/tspan_flattener.py +64 -0
  157. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/use_expander.py +577 -0
  158. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx.py +21 -0
  159. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +336 -0
  160. package/skills/dknowc-ppt-assistant/scripts/update_spec.py +404 -0
  161. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +142 -0
  162. package/skills/dknowc-ppt-assistant/workflows/routing.md +38 -0
  163. package/skills/dknowc-trusted-consulting/SKILL.md +21 -5
  164. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +79 -0
  165. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +31 -0
  166. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +76 -0
  167. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +1 -0
  168. package/skills/dknowc-trusted-search/SKILL.md +30 -2
  169. package/skills/dknowc-trusted-search/reference/sample_search_result.md +33 -0
  170. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +450 -0
  171. package/skills/dknowc-trusted-search/reference/search_intro.md +79 -0
  172. package/skills/dknowc-trusted-search/scripts/register_key.mjs +1 -0
  173. package/src/index.js +7 -2
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ SVG Image Embedding Tool
4
+ Converts externally referenced images in SVG files to Base64 inline format.
5
+
6
+ Usage:
7
+ python3 scripts/svg_finalize/embed_images.py <svg_file> [svg_file2] ...
8
+ python3 scripts/svg_finalize/embed_images.py *.svg
9
+
10
+ Examples:
11
+ python3 scripts/svg_finalize/embed_images.py examples/ppt169_demo/svg_output/01_cover.svg
12
+ python3 scripts/svg_finalize/embed_images.py examples/ppt169_demo/svg_output/*.svg
13
+ """
14
+
15
+ import os
16
+ import base64
17
+ import re
18
+ import sys
19
+ import argparse
20
+ from pathlib import Path
21
+
22
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
23
+ if str(_SCRIPTS_DIR) not in sys.path:
24
+ sys.path.insert(0, str(_SCRIPTS_DIR))
25
+
26
+ from console_encoding import configure_utf8_stdio # noqa: E402
27
+
28
+ configure_utf8_stdio()
29
+
30
+
31
+ def get_mime_type(filename: str, file_bytes: bytes | None = None) -> str:
32
+ """Return the MIME type based on file bytes first, then extension."""
33
+ if file_bytes:
34
+ if file_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
35
+ return 'image/png'
36
+ if file_bytes.startswith(b"\xff\xd8\xff"):
37
+ return 'image/jpeg'
38
+ if file_bytes.startswith((b"GIF87a", b"GIF89a")):
39
+ return 'image/gif'
40
+ if file_bytes.startswith(b"RIFF") and file_bytes[8:12] == b"WEBP":
41
+ return 'image/webp'
42
+ if file_bytes.lstrip().startswith(b"<svg"):
43
+ return 'image/svg+xml'
44
+
45
+ ext = filename.lower().split('.')[-1]
46
+ mime_map = {
47
+ 'png': 'image/png',
48
+ 'jpg': 'image/jpeg',
49
+ 'jpeg': 'image/jpeg',
50
+ 'gif': 'image/gif',
51
+ 'webp': 'image/webp',
52
+ 'svg': 'image/svg+xml',
53
+ }
54
+ return mime_map.get(ext, 'application/octet-stream')
55
+
56
+ def get_file_size_str(size_bytes: int) -> str:
57
+ """Convert byte count to a human-readable file size string."""
58
+ if size_bytes < 1024:
59
+ return f"{size_bytes} B"
60
+ elif size_bytes < 1024 * 1024:
61
+ return f"{size_bytes / 1024:.1f} KB"
62
+ else:
63
+ return f"{size_bytes / (1024 * 1024):.1f} MB"
64
+
65
+ def _optimize_image_bytes(img_bytes: bytes, mime_type: str,
66
+ compress: bool = False,
67
+ max_dimension: int | None = None) -> bytes:
68
+ """Optionally compress and/or downscale image bytes.
69
+
70
+ Returns the (possibly optimized) image bytes. Falls back to the
71
+ original bytes if PIL is not available or optimization fails.
72
+ """
73
+ if not compress and not max_dimension:
74
+ return img_bytes
75
+
76
+ try:
77
+ from PIL import Image as PILImage
78
+ import io
79
+ except ImportError:
80
+ return img_bytes
81
+
82
+ try:
83
+ img = PILImage.open(io.BytesIO(img_bytes))
84
+ except Exception:
85
+ return img_bytes
86
+
87
+ # Multi-frame images (animated GIF / WebP / APNG): resize/re-save below
88
+ # keeps frame 0 only, silently flattening the animation. Pass the
89
+ # original bytes through — animations are exempt from compression and
90
+ # the size cap.
91
+ if getattr(img, 'is_animated', False):
92
+ if max_dimension:
93
+ w, h = img.size
94
+ if w > max_dimension or h > max_dimension:
95
+ print(f" [WARN] Animated image kept as-is ({w}x{h} exceeds "
96
+ f"max dimension {max_dimension}px); animations are "
97
+ f"exempt from size limits")
98
+ return img_bytes
99
+
100
+ changed = False
101
+
102
+ # Downscale if exceeding max_dimension
103
+ if max_dimension:
104
+ w, h = img.size
105
+ if w > max_dimension or h > max_dimension:
106
+ ratio = min(max_dimension / w, max_dimension / h)
107
+ new_w, new_h = int(w * ratio), int(h * ratio)
108
+ img = img.resize((new_w, new_h), PILImage.LANCZOS)
109
+ changed = True
110
+
111
+ # Compress
112
+ if compress or changed:
113
+ buf = io.BytesIO()
114
+ if mime_type == 'image/jpeg':
115
+ if img.mode in ('RGBA', 'P'):
116
+ img = img.convert('RGB')
117
+ img.save(buf, format='JPEG', quality=85, optimize=True)
118
+ elif mime_type == 'image/png':
119
+ img.save(buf, format='PNG', optimize=True)
120
+ else:
121
+ # For other formats, just re-save
122
+ fmt = img.format or 'PNG'
123
+ img.save(buf, format=fmt)
124
+
125
+ optimized = buf.getvalue()
126
+ # Only use optimized version if it's actually smaller
127
+ if len(optimized) < len(img_bytes):
128
+ return optimized
129
+
130
+ return img_bytes
131
+
132
+
133
+ def embed_images_in_svg(svg_path: str, dry_run: bool = False,
134
+ compress: bool = False,
135
+ max_dimension: int | None = None) -> tuple[int, int]:
136
+ """
137
+ Convert externally referenced images in an SVG file to Base64 inline format.
138
+
139
+ Args:
140
+ svg_path: SVG file path
141
+ dry_run: If True, only show which images would be processed without modifying the file
142
+ compress: If True, compress images before embedding (JPEG quality=85, PNG optimize)
143
+ max_dimension: If set, downscale images exceeding this dimension on either axis
144
+
145
+ Returns:
146
+ tuple: (number of images processed, file size after embedding)
147
+ """
148
+ svg_dir = os.path.dirname(os.path.abspath(svg_path))
149
+
150
+ with open(svg_path, 'r', encoding='utf-8') as f:
151
+ content = f.read()
152
+
153
+ original_size = len(content.encode('utf-8'))
154
+
155
+ # Match href="xxx.png" or href="xxx.jpg" etc. (exclude those already using data:)
156
+ pattern = r'href="(?!data:)([^"]+\.(png|jpg|jpeg|gif|webp))"'
157
+
158
+ images_found = []
159
+ images_embedded = 0
160
+
161
+ def replace_with_base64(match):
162
+ nonlocal images_embedded
163
+ img_path = match.group(1)
164
+
165
+ # Decode XML/HTML entities (e.g., &amp; -> &)
166
+ import html
167
+ img_path_decoded = html.unescape(img_path)
168
+
169
+ # Handle relative paths
170
+ if not os.path.isabs(img_path_decoded):
171
+ full_path = os.path.join(svg_dir, img_path_decoded)
172
+ else:
173
+ full_path = img_path_decoded
174
+
175
+ if not os.path.exists(full_path):
176
+ print(f" [WARN] Image not found: {img_path}")
177
+ images_found.append((img_path, "NOT FOUND", 0, None))
178
+ return match.group(0)
179
+
180
+ img_size = os.path.getsize(full_path)
181
+
182
+ if dry_run:
183
+ images_found.append((img_path, "WILL EMBED", img_size, None))
184
+ return match.group(0)
185
+
186
+ with open(full_path, 'rb') as img_file:
187
+ img_bytes = img_file.read()
188
+
189
+ mime_type = get_mime_type(img_path, img_bytes)
190
+ optimized_bytes = _optimize_image_bytes(
191
+ img_bytes, mime_type, compress=compress, max_dimension=max_dimension)
192
+ b64_data = base64.b64encode(optimized_bytes).decode('utf-8')
193
+
194
+ images_embedded += 1
195
+ saved = len(img_bytes) - len(optimized_bytes)
196
+ if saved > 0 and (compress or max_dimension):
197
+ pct = saved / len(img_bytes) * 100
198
+ images_found.append((img_path, "EMBEDDED", img_size,
199
+ f"{get_file_size_str(len(img_bytes))} → {get_file_size_str(len(optimized_bytes))}, saved {pct:.0f}%"))
200
+ else:
201
+ images_found.append((img_path, "EMBEDDED", img_size, None))
202
+
203
+ return f'href="data:{mime_type};base64,{b64_data}"'
204
+
205
+ new_content = re.sub(pattern, replace_with_base64, content)
206
+
207
+ new_size = len(new_content.encode('utf-8'))
208
+
209
+ # Print processed images
210
+ if images_found:
211
+ print(f"\n[FILE] {os.path.basename(svg_path)}")
212
+ for img_path, status, size, opt_info in images_found:
213
+ size_str = get_file_size_str(size) if size > 0 else ""
214
+ if status == "EMBEDDED":
215
+ if opt_info:
216
+ print(f" [OK] {img_path} ({opt_info})")
217
+ else:
218
+ print(f" [OK] {img_path} ({size_str})")
219
+ elif status == "WILL EMBED":
220
+ print(f" [PREVIEW] {img_path} ({size_str}) [dry-run]")
221
+ else:
222
+ print(f" [FAIL] {img_path} ({status})")
223
+
224
+ print(f" [SIZE] {get_file_size_str(original_size)} -> {get_file_size_str(new_size)}")
225
+
226
+ if not dry_run and images_embedded > 0:
227
+ with open(svg_path, 'w', encoding='utf-8') as f:
228
+ f.write(new_content)
229
+
230
+ processed_count = len(images_found) if dry_run else images_embedded
231
+ return (processed_count, new_size)
232
+
233
+ def main() -> None:
234
+ """Run the CLI entry point."""
235
+ parser = argparse.ArgumentParser(
236
+ description='Convert externally referenced images in SVG files to Base64 inline format',
237
+ formatter_class=argparse.RawDescriptionHelpFormatter,
238
+ epilog='''
239
+ Examples:
240
+ %(prog)s 01_cover.svg # Process a single file
241
+ %(prog)s *.svg # Process all SVGs in current directory
242
+ %(prog)s --dry-run *.svg # Preview files to be processed
243
+ '''
244
+ )
245
+ parser.add_argument('files', nargs='+', help='SVG files to process')
246
+ parser.add_argument('--dry-run', '-n', action='store_true',
247
+ help='Only show which images would be processed, without modifying files')
248
+ parser.add_argument('--compress', action='store_true',
249
+ help='Compress images before embedding (JPEG quality=85, PNG optimize)')
250
+ parser.add_argument('--max-dimension', type=int, default=None,
251
+ help='Downscale images exceeding this dimension on either axis (e.g., 2560)')
252
+
253
+ args = parser.parse_args()
254
+
255
+ if args.dry_run:
256
+ print("[INFO] Dry-run mode: only preview, no modification\n")
257
+ if args.compress:
258
+ print("[INFO] Compression enabled: JPEG quality=85, PNG optimize")
259
+ if args.max_dimension:
260
+ print(f"[INFO] Max dimension: {args.max_dimension}px")
261
+
262
+ total_images = 0
263
+ total_files = 0
264
+
265
+ for svg_file in args.files:
266
+ if not os.path.exists(svg_file):
267
+ print(f"[ERROR] File not found: {svg_file}")
268
+ continue
269
+
270
+ if not svg_file.endswith('.svg'):
271
+ print(f"[SKIP] Skipping non-SVG file: {svg_file}")
272
+ continue
273
+
274
+ images, _ = embed_images_in_svg(svg_file, dry_run=args.dry_run,
275
+ compress=args.compress,
276
+ max_dimension=args.max_dimension)
277
+ if images > 0:
278
+ total_images += images
279
+ total_files += 1
280
+
281
+ print(f"\n{'=' * 50}")
282
+ if args.dry_run:
283
+ print(f"[PREVIEW] Will process {total_images} images in {total_files} files")
284
+ else:
285
+ print(f"[DONE] Embedded {total_images} images in {total_files} files")
286
+
287
+ if __name__ == '__main__':
288
+ main()
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ SVG Image Aspect Ratio Fix Tool
4
+
5
+ Fixes the dimensions of <image> elements in SVG to match the original image aspect ratio.
6
+ This prevents images from being stretched by PowerPoint SVG rendering paths that do not
7
+ honor preserveAspectRatio consistently.
8
+
9
+ Principle:
10
+ Some PowerPoint SVG rendering paths ignore the preserveAspectRatio attribute and directly
11
+ stretch the image to fill the area specified by width/height.
12
+
13
+ This tool reads the actual image aspect ratio and recalculates the x, y, width, height of
14
+ <image> elements so that images are centered and maintain their original aspect ratio.
15
+
16
+ Usage:
17
+ python3 scripts/svg_finalize/fix_image_aspect.py <svg_file> [svg_file2] ...
18
+ python3 scripts/svg_finalize/fix_image_aspect.py projects/xxx/svg_output/*.svg
19
+
20
+ # Preview mode
21
+ python3 scripts/svg_finalize/fix_image_aspect.py --dry-run projects/xxx/svg_output/*.svg
22
+
23
+ Examples:
24
+ python3 scripts/svg_finalize/fix_image_aspect.py projects/demo/svg_output/slide_06_current_overview.svg
25
+ """
26
+
27
+ import os
28
+ import re
29
+ import sys
30
+ import base64
31
+ import argparse
32
+ from pathlib import Path
33
+ from xml.etree import ElementTree as ET
34
+
35
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
36
+ if str(_SCRIPTS_DIR) not in sys.path:
37
+ sys.path.insert(0, str(_SCRIPTS_DIR))
38
+
39
+ from console_encoding import configure_utf8_stdio # noqa: E402
40
+
41
+ configure_utf8_stdio()
42
+
43
+ # Try to import PIL for getting image dimensions
44
+ try:
45
+ from PIL import Image
46
+ HAS_PIL = True
47
+ except ImportError:
48
+ HAS_PIL = False
49
+ print("[WARN] PIL not installed. Install with: pip install Pillow")
50
+ print(" Will try to use basic method for JPEG/PNG files.")
51
+
52
+
53
+ def get_image_dimensions_pil(image_path: str) -> tuple[int | None, int | None]:
54
+ """Get image dimensions using PIL."""
55
+ try:
56
+ with Image.open(image_path) as img:
57
+ return img.width, img.height
58
+ except Exception as e:
59
+ print(f" [WARN] Cannot read image with PIL: {e}")
60
+ return None, None
61
+
62
+
63
+ def get_image_dimensions_basic(image_path: str) -> tuple[int | None, int | None]:
64
+ """Get image dimensions using basic parsing without PIL."""
65
+ try:
66
+ with open(image_path, 'rb') as f:
67
+ data = f.read(64) # Read header information
68
+
69
+ # PNG
70
+ if data[:8] == b'\x89PNG\r\n\x1a\n':
71
+ w = int.from_bytes(data[16:20], 'big')
72
+ h = int.from_bytes(data[20:24], 'big')
73
+ return w, h
74
+
75
+ # JPEG
76
+ if data[:2] == b'\xff\xd8':
77
+ # Need to read full file to parse JPEG
78
+ with open(image_path, 'rb') as f:
79
+ f.seek(2)
80
+ while True:
81
+ marker = f.read(2)
82
+ if not marker or len(marker) < 2:
83
+ break
84
+ if marker[0] != 0xff:
85
+ break
86
+ m = marker[1]
87
+ # SOF0, SOF2 markers contain dimensions
88
+ if m in (0xC0, 0xC2):
89
+ f.read(3) # Skip length and precision
90
+ h = int.from_bytes(f.read(2), 'big')
91
+ w = int.from_bytes(f.read(2), 'big')
92
+ return w, h
93
+ elif m == 0xD9: # EOI
94
+ break
95
+ elif m == 0xD8: # SOI
96
+ continue
97
+ elif 0xD0 <= m <= 0xD7: # RST
98
+ continue
99
+ else:
100
+ length = int.from_bytes(f.read(2), 'big')
101
+ f.seek(length - 2, 1)
102
+
103
+ return None, None
104
+ except Exception as e:
105
+ print(f" [WARN] Cannot read image dimensions: {e}")
106
+ return None, None
107
+
108
+
109
+ def get_image_dimensions_from_base64(data_uri: str) -> tuple[int | None, int | None]:
110
+ """Get image dimensions from a Base64 data URI."""
111
+ import io
112
+ try:
113
+ # Parse data URI
114
+ match = re.match(r'data:image/(\w+);base64,(.+)', data_uri)
115
+ if not match:
116
+ return None, None
117
+
118
+ img_format = match.group(1)
119
+ b64_data = match.group(2)
120
+ img_bytes = base64.b64decode(b64_data)
121
+
122
+ if HAS_PIL:
123
+ with Image.open(io.BytesIO(img_bytes)) as img:
124
+ return img.width, img.height
125
+ else:
126
+ # Use basic method
127
+ if img_bytes[:8] == b'\x89PNG\r\n\x1a\n':
128
+ w = int.from_bytes(img_bytes[16:20], 'big')
129
+ h = int.from_bytes(img_bytes[20:24], 'big')
130
+ return w, h
131
+
132
+ return None, None
133
+ except Exception as e:
134
+ print(f" [WARN] Cannot parse base64 image: {e}")
135
+ return None, None
136
+
137
+
138
+ def get_image_dimensions(href: str, svg_dir: str) -> tuple[int | None, int | None]:
139
+ """Get image dimensions for either inline or external images."""
140
+ # Handle data URI
141
+ if href.startswith('data:'):
142
+ return get_image_dimensions_from_base64(href)
143
+
144
+ # Handle external files
145
+ if not os.path.isabs(href):
146
+ full_path = os.path.join(svg_dir, href)
147
+ else:
148
+ full_path = href
149
+
150
+ if not os.path.exists(full_path):
151
+ print(f" [WARN] Image not found: {href}")
152
+ return None, None
153
+
154
+ if HAS_PIL:
155
+ return get_image_dimensions_pil(full_path)
156
+ else:
157
+ return get_image_dimensions_basic(full_path)
158
+
159
+
160
+ def calculate_fitted_dimensions(
161
+ img_width: int,
162
+ img_height: int,
163
+ box_width: float,
164
+ box_height: float,
165
+ mode: str = 'meet',
166
+ ) -> tuple[float, float, float, float]:
167
+ """
168
+ Calculate the fitted dimensions for an image within a bounding box.
169
+
170
+ Args:
171
+ img_width, img_height: Original image dimensions
172
+ box_width, box_height: Container box dimensions
173
+ mode: 'meet' preserves aspect ratio and fully displays image (may have whitespace)
174
+ 'slice' preserves aspect ratio and fully fills container (may crop)
175
+
176
+ Returns:
177
+ (new_width, new_height, offset_x, offset_y)
178
+ """
179
+ img_ratio = img_width / img_height
180
+ box_ratio = box_width / box_height
181
+
182
+ if mode == 'meet':
183
+ # Fully display image, may have whitespace
184
+ if img_ratio > box_ratio:
185
+ # Image is wider, fit by width
186
+ new_width = box_width
187
+ new_height = box_width / img_ratio
188
+ else:
189
+ # Image is taller, fit by height
190
+ new_height = box_height
191
+ new_width = box_height * img_ratio
192
+ else: # slice
193
+ # Fully fill container, may crop
194
+ if img_ratio > box_ratio:
195
+ # Image is wider, fit by height
196
+ new_height = box_height
197
+ new_width = box_height * img_ratio
198
+ else:
199
+ # Image is taller, fit by width
200
+ new_width = box_width
201
+ new_height = box_width / img_ratio
202
+
203
+ # Center offset
204
+ offset_x = (box_width - new_width) / 2
205
+ offset_y = (box_height - new_height) / 2
206
+
207
+ return new_width, new_height, offset_x, offset_y
208
+
209
+
210
+ def fix_image_aspect_in_svg(svg_path: str, dry_run: bool = False, verbose: bool = True) -> int:
211
+ """
212
+ Fix image aspect ratios in an SVG file.
213
+
214
+ Args:
215
+ svg_path: SVG file path
216
+ dry_run: Whether to only preview without modifying
217
+ verbose: Whether to output detailed information
218
+
219
+ Returns:
220
+ Number of images fixed
221
+ """
222
+ svg_dir = os.path.dirname(os.path.abspath(svg_path))
223
+
224
+ with open(svg_path, 'r', encoding='utf-8') as f:
225
+ content = f.read()
226
+
227
+ # Register SVG namespaces
228
+ namespaces = {
229
+ '': 'http://www.w3.org/2000/svg',
230
+ 'xlink': 'http://www.w3.org/1999/xlink',
231
+ 'svg': 'http://www.w3.org/2000/svg',
232
+ 'sodipodi': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
233
+ 'inkscape': 'http://www.inkscape.org/namespaces/inkscape',
234
+ }
235
+
236
+ for prefix, uri in namespaces.items():
237
+ if prefix:
238
+ ET.register_namespace(prefix, uri)
239
+ else:
240
+ ET.register_namespace('', uri)
241
+
242
+ try:
243
+ tree = ET.parse(svg_path)
244
+ root = tree.getroot()
245
+ except ET.ParseError as e:
246
+ print(f" [ERROR] Cannot parse SVG: {e}")
247
+ return 0
248
+
249
+ # Find all image elements
250
+ fixed_count = 0
251
+
252
+ # Check image elements with and without namespace
253
+ for ns_prefix in ['', '{http://www.w3.org/2000/svg}']:
254
+ for image_elem in root.iter(f'{ns_prefix}image'):
255
+ # Get href attribute (supports xlink:href and href)
256
+ href = image_elem.get('{http://www.w3.org/1999/xlink}href')
257
+ if href is None:
258
+ href = image_elem.get('href')
259
+ if href is None:
260
+ continue
261
+
262
+ # Get current dimensions and position
263
+ try:
264
+ x = float(image_elem.get('x', 0))
265
+ y = float(image_elem.get('y', 0))
266
+ width = float(image_elem.get('width', 0))
267
+ height = float(image_elem.get('height', 0))
268
+ except (ValueError, TypeError):
269
+ continue
270
+
271
+ if width <= 0 or height <= 0:
272
+ continue
273
+
274
+ # Get preserveAspectRatio
275
+ par = image_elem.get('preserveAspectRatio', 'xMidYMid meet')
276
+
277
+ # Parse preserveAspectRatio
278
+ # Format: <align> [<meetOrSlice>]
279
+ # e.g.: xMidYMid meet, xMidYMid slice, none
280
+ par_parts = par.split()
281
+ align = par_parts[0] if par_parts else 'xMidYMid'
282
+ meet_or_slice = par_parts[1] if len(par_parts) > 1 else 'meet'
283
+
284
+ if align == 'none':
285
+ # If none, no fix needed
286
+ continue
287
+
288
+ # Get original image dimensions
289
+ img_width, img_height = get_image_dimensions(href, svg_dir)
290
+ if img_width is None or img_height is None:
291
+ continue
292
+
293
+ # Calculate fitted dimensions
294
+ mode = 'slice' if meet_or_slice == 'slice' else 'meet'
295
+ new_width, new_height, offset_x, offset_y = calculate_fitted_dimensions(
296
+ img_width, img_height, width, height, mode
297
+ )
298
+
299
+ # Check if modification is needed
300
+ tolerance = 0.5 # Allowed tolerance
301
+ if (abs(new_width - width) < tolerance and
302
+ abs(new_height - height) < tolerance):
303
+ # Dimensions are already correct, no modification needed
304
+ continue
305
+
306
+ if verbose:
307
+ img_name = os.path.basename(href.split('?')[0][:50] if not href.startswith('data:') else '[base64]')
308
+ print(f" [FIX] {img_name}")
309
+ print(f" Original image: {img_width}x{img_height} (ratio: {img_width/img_height:.3f})")
310
+ print(f" Original box: {width}x{height} @ ({x}, {y})")
311
+ print(f" New box: {new_width:.1f}x{new_height:.1f} @ ({x + offset_x:.1f}, {y + offset_y:.1f})")
312
+
313
+ if not dry_run:
314
+ # Update attributes
315
+ image_elem.set('x', f'{x + offset_x:.1f}')
316
+ image_elem.set('y', f'{y + offset_y:.1f}')
317
+ image_elem.set('width', f'{new_width:.1f}')
318
+ image_elem.set('height', f'{new_height:.1f}')
319
+ # Remove preserveAspectRatio since dimensions are now correct
320
+ if 'preserveAspectRatio' in image_elem.attrib:
321
+ del image_elem.attrib['preserveAspectRatio']
322
+
323
+ fixed_count += 1
324
+
325
+ if not dry_run and fixed_count > 0:
326
+ # Save modifications
327
+ tree.write(svg_path, encoding='unicode', xml_declaration=True)
328
+
329
+ return fixed_count
330
+
331
+
332
+ def main() -> None:
333
+ """Run the CLI entry point."""
334
+ parser = argparse.ArgumentParser(
335
+ description='Normalize SVG image boxes for PowerPoint SVG rendering diagnostics',
336
+ formatter_class=argparse.RawDescriptionHelpFormatter,
337
+ epilog='''
338
+ Examples:
339
+ %(prog)s slide_01.svg # Process a single file
340
+ %(prog)s *.svg # Process all SVGs in current directory
341
+ %(prog)s --dry-run *.svg # Preview files to be processed
342
+ %(prog)s projects/xxx/svg_output/*.svg # Process project directory
343
+ '''
344
+ )
345
+ parser.add_argument('files', nargs='+', help='SVG files to process')
346
+ parser.add_argument('--dry-run', '-n', action='store_true',
347
+ help='Only show which images would be fixed, without modifying files')
348
+ parser.add_argument('--quiet', '-q', action='store_true',
349
+ help='Quiet mode, reduce output')
350
+
351
+ args = parser.parse_args()
352
+
353
+ if args.dry_run:
354
+ print("[INFO] Preview mode: only showing what would be modified, no files will be changed\n")
355
+
356
+ total_fixed = 0
357
+ total_files = 0
358
+
359
+ for svg_file in args.files:
360
+ if not os.path.exists(svg_file):
361
+ if not args.quiet:
362
+ print(f"[ERROR] File not found: {svg_file}")
363
+ continue
364
+
365
+ if not svg_file.endswith('.svg'):
366
+ if not args.quiet:
367
+ print(f"[SKIP] Skipping non-SVG file: {svg_file}")
368
+ continue
369
+
370
+ if not args.quiet:
371
+ print(f"\n[FILE] {os.path.basename(svg_file)}")
372
+
373
+ fixed = fix_image_aspect_in_svg(svg_file, dry_run=args.dry_run, verbose=not args.quiet)
374
+
375
+ if fixed > 0:
376
+ total_fixed += fixed
377
+ total_files += 1
378
+ elif not args.quiet:
379
+ print(" No fix needed")
380
+
381
+ print(f"\n{'=' * 50}")
382
+ if args.dry_run:
383
+ print(f"[PREVIEW] Will fix {total_fixed} image(s) in {total_files} file(s)")
384
+ else:
385
+ print(f"[DONE] Fixed {total_fixed} image(s) in {total_files} file(s)")
386
+
387
+
388
+ if __name__ == '__main__':
389
+ main()