@hfyjq/crannia 1.1.1 → 1.2.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 (306) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +48 -45
  3. package/README.md +1 -1
  4. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  5. package/THIRD-PARTY-PYTHON-linux.md +174 -0
  6. package/THIRD-PARTY-PYTHON.md +176 -162
  7. package/THIRD-PARTY.md +323 -316
  8. package/apps/desktop/quotes.txt +56 -56
  9. package/bus/core.py +677 -671
  10. package/bus/loaders/channel_loader.py +64 -64
  11. package/bus/loaders/provider_loader.py +4 -7
  12. package/bus/loaders/skill_loader.py +46 -27
  13. package/bus/loaders/skill_md.py +9 -9
  14. package/bus/mcp_disabled.py +4 -6
  15. package/bus/quarantine.py +10 -13
  16. package/bus/registry.py +2315 -2284
  17. package/bus/skill_state.py +124 -124
  18. package/channels/cli_channel/handler.py +3 -3
  19. package/channels/cli_channel/manifest.yaml +5 -5
  20. package/channels/dingtalk_channel/handler.py +32 -32
  21. package/channels/dingtalk_channel/manifest.yaml +12 -12
  22. package/channels/feishu_channel/handler.py +33 -33
  23. package/channels/feishu_channel/manifest.yaml +12 -12
  24. package/channels/qq_bot_channel/__init__.py +1 -1
  25. package/channels/qq_bot_channel/handler.py +24 -24
  26. package/channels/qq_bot_channel/manifest.yaml +4 -4
  27. package/channels/telegram_channel/__init__.py +1 -1
  28. package/channels/telegram_channel/handler.py +21 -21
  29. package/channels/telegram_channel/manifest.yaml +4 -4
  30. package/channels/telegram_channel/media.py +231 -231
  31. package/channels/textfmt.py +58 -58
  32. package/channels/wechat_channel/__init__.py +1 -1
  33. package/channels/wechat_channel/converter.py +1 -1
  34. package/channels/wechat_channel/handler.py +8 -8
  35. package/channels/wechat_channel/manifest.yaml +5 -5
  36. package/channels/wechat_channel/media.py +178 -178
  37. package/core/activity.py +753 -709
  38. package/core/agent_loop.py +7673 -7523
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +36 -26
  41. package/core/approval_timeout.py +256 -228
  42. package/core/artifacts.py +3 -3
  43. package/core/attachment_gc.py +21 -0
  44. package/core/auto_review.py +2 -2
  45. package/core/browser/cdp.py +5 -2
  46. package/core/browser/discover.py +55 -19
  47. package/core/browser/session.py +4 -4
  48. package/core/cache_break_detector.py +97 -0
  49. package/core/cache_breakpoints.py +103 -0
  50. package/core/cache_policies.py +255 -0
  51. package/core/cancellation.py +3 -3
  52. package/core/channel_configs.py +3 -3
  53. package/core/channel_turns.py +13 -13
  54. package/core/child_approval.py +2 -3
  55. package/core/code_intel.py +11 -11
  56. package/core/command_policy.py +13 -7
  57. package/core/computer/annotate.py +231 -11
  58. package/core/computer/capture.py +140 -1
  59. package/core/computer/guard.py +7 -4
  60. package/core/computer/input.py +452 -26
  61. package/core/computer/session.py +563 -381
  62. package/core/computer/tools.py +2170 -928
  63. package/core/computer/uia.py +100 -1
  64. package/core/computer/watch.py +1 -1
  65. package/core/computer/win32.py +302 -7
  66. package/core/config_requirements.py +205 -205
  67. package/core/cron/runner.py +4 -4
  68. package/core/daily_log.py +2 -2
  69. package/core/dedup.py +2 -2
  70. package/core/egress_channels.py +326 -0
  71. package/core/egress_gate.py +96 -8
  72. package/core/egress_preapproved.py +59 -3
  73. package/core/endpoint.py +141 -141
  74. package/core/events.py +17 -8
  75. package/core/extension.py +2 -2
  76. package/core/file_history.py +15 -15
  77. package/core/file_tools.py +3 -3
  78. package/core/github_config.py +1 -1
  79. package/core/group_digest.py +3 -4
  80. package/core/group_minutes.py +5 -5
  81. package/core/group_reply.py +24 -0
  82. package/core/groups.py +5 -9
  83. package/core/hooks.py +15 -15
  84. package/core/i18n.py +2 -2
  85. package/core/ice/canary.py +3 -3
  86. package/core/ice/net_heuristics.py +2 -2
  87. package/core/im_routing.py +3 -3
  88. package/core/image_input.py +183 -43
  89. package/core/inbound.py +3 -3
  90. package/core/jobs.py +6 -6
  91. package/core/last_good.py +150 -150
  92. package/core/leaf_md.py +3 -3
  93. package/core/llm_errors.py +37 -28
  94. package/core/mail_config.py +2 -2
  95. package/core/memory/compressor.py +8 -8
  96. package/core/memory/manager.py +30 -45
  97. package/core/memory/session_memory.py +1 -2
  98. package/core/memory/short_term.py +4 -4
  99. package/core/memory_extract.py +1 -1
  100. package/core/memory_organize.py +8 -8
  101. package/core/memory_store.py +7 -9
  102. package/core/memory_transfer.py +2 -2
  103. package/core/model_capabilities.py +2 -2
  104. package/core/model_configs.py +219 -68
  105. package/core/model_profiles.py +333 -0
  106. package/core/modes.py +12 -11
  107. package/core/net_proxy.py +3 -3
  108. package/core/pipeline/scheduler.py +48 -43
  109. package/core/pipeline/stage.py +3 -0
  110. package/core/pipeline/stages/agent_loop.py +36 -15
  111. package/core/pipeline/stages/group_reply.py +22 -20
  112. package/core/pipeline/stages/post_process.py +7 -7
  113. package/core/pipeline/stages/pre_process.py +369 -77
  114. package/core/prompt_assembler.py +13 -4
  115. package/core/recycle.py +227 -16
  116. package/core/response_language.py +1 -1
  117. package/core/retention.py +2 -2
  118. package/core/rg.py +4 -3
  119. package/core/security.py +26 -8
  120. package/core/services.py +8 -8
  121. package/core/session_model.py +3 -5
  122. package/core/session_pool.py +35 -5
  123. package/core/session_recap.py +40 -3
  124. package/core/session_workspace.py +2 -3
  125. package/core/settings_baseline.py +2 -2
  126. package/core/settings_transfer.py +25 -1
  127. package/core/shell.py +52 -20
  128. package/core/side_call.py +3 -3
  129. package/core/skill_config.py +164 -0
  130. package/core/skill_factory.py +2 -2
  131. package/core/skill_guidance.py +2 -4
  132. package/core/skill_index.py +3 -4
  133. package/core/skill_settings.py +1 -1
  134. package/core/skill_sources.py +7 -7
  135. package/core/ssh_config.py +129 -0
  136. package/core/state_registry.py +67 -5
  137. package/core/subagent.py +28 -5
  138. package/core/subagent_defs.py +3 -3
  139. package/core/summarizer.py +4 -5
  140. package/core/tasks_notify.py +6 -6
  141. package/core/tiers.py +2 -2
  142. package/core/todos.py +1 -1
  143. package/core/token_calibrator.py +1 -4
  144. package/core/tool_outcome.py +108 -108
  145. package/core/touched_files.py +1 -1
  146. package/core/trace.py +12 -3
  147. package/core/unlock.py +4 -4
  148. package/core/update_tui.py +184 -158
  149. package/core/updater.py +5 -3
  150. package/core/version.py +14 -14
  151. package/core/vision_budget.py +235 -0
  152. package/core/web_cache.py +152 -152
  153. package/core/web_request.py +474 -0
  154. package/core/window_estimate.py +1 -1
  155. package/core/workspace.py +56 -26
  156. package/crannia_tray.py +278 -278
  157. package/licenses/GPL-3.0.txt +619 -619
  158. package/licenses/LGPL-2.1.txt +502 -502
  159. package/licenses/LGPL-3.0.txt +165 -165
  160. package/licenses/MIT-chat-on-wechat.txt +18 -18
  161. package/licenses/MIT-deepseek-harness.txt +21 -21
  162. package/licenses/Molio-LICENSE.txt +44 -44
  163. package/locales/en.json +1876 -1762
  164. package/main.py +154 -154
  165. package/mcpx/client.py +12 -1
  166. package/mcpx/manager.py +530 -522
  167. package/mcpx/servers/web_search.py +5 -13
  168. package/package.json +15 -23
  169. package/providers/anthropic/client.py +35 -33
  170. package/providers/base.py +13 -13
  171. package/providers/cache_policies.json +294 -0
  172. package/providers/cost_table.json +3779 -3779
  173. package/providers/lmstudio/client.py +2 -2
  174. package/providers/model_capabilities.json +6665 -6665
  175. package/providers/model_profiles.json +629 -0
  176. package/providers/ollama/client.py +2 -2
  177. package/providers/openai_compat.py +37 -16
  178. package/providers/openrouter/client.py +2 -2
  179. package/providers/qwen/__init__.py +1 -1
  180. package/providers/qwen/client.py +2 -2
  181. package/providers/qwen/manifest.yaml +16 -16
  182. package/providers/rate_limiter.py +2 -2
  183. package/providers/siliconflow/client.py +2 -2
  184. package/providers/validation.py +171 -171
  185. package/providers/vision_profiles.json +89 -0
  186. package/providers/window_table.json +8909 -8909
  187. package/requirements.txt +59 -51
  188. package/sbom-linux-x64.json +4580 -0
  189. package/sbom.json +4600 -4413
  190. package/skills/diagram/SKILL.md +47 -0
  191. package/skills/diagram/__init__.py +1 -0
  192. package/skills/diagram/handler.py +294 -0
  193. package/skills/diagram/layout.py +174 -0
  194. package/skills/diagram/manifest.yaml +106 -0
  195. package/skills/diagram/mermaid.py +170 -0
  196. package/skills/diagram/svg.py +223 -0
  197. package/skills/entertainment/SKILL.md +35 -35
  198. package/skills/entertainment/__init__.py +1 -1
  199. package/skills/entertainment/handler.py +91 -91
  200. package/skills/entertainment/manifest.yaml +26 -26
  201. package/skills/file_parser/GUIDANCE.md +10 -10
  202. package/skills/file_parser/handler.py +33 -11
  203. package/skills/github/SKILL.md +32 -32
  204. package/skills/github/__init__.py +1 -1
  205. package/skills/mail_parser/SKILL.md +68 -68
  206. package/skills/mail_parser/__init__.py +1 -1
  207. package/skills/mail_parser/handler.py +1 -1
  208. package/skills/media_gen/GUIDANCE.md +19 -19
  209. package/skills/media_gen/SKILL.md +43 -43
  210. package/skills/media_gen/__init__.py +1 -1
  211. package/skills/media_gen/handler.py +1 -1
  212. package/skills/media_gen/manifest.yaml +93 -93
  213. package/skills/netops/SKILL.md +45 -0
  214. package/skills/netops/__init__.py +1 -0
  215. package/skills/netops/handler.py +418 -0
  216. package/skills/netops/manifest.yaml +118 -0
  217. package/skills/office_parser/_excel_io.py +3 -3
  218. package/skills/office_parser/handler.py +2 -2
  219. package/skills/office_parser/ppt_tools.py +1 -1
  220. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  221. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  222. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  223. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  224. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  225. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  226. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  227. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  228. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  229. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  230. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  231. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  232. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  233. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
  234. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  235. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  236. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  237. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  238. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  239. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  240. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  241. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  242. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  243. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  244. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  245. package/skills/office_parser/references/layout_library.md +816 -816
  246. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  247. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  248. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  249. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  250. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  251. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  252. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  253. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  254. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  255. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  256. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  257. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  258. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  259. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  260. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  261. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  262. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  263. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  264. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  265. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  266. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  267. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  268. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  269. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  270. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  271. package/skills/office_parser/references/spec_lock.md +235 -235
  272. package/skills/office_parser/soffice.py +68 -68
  273. package/skills/office_parser/word_tools.py +3 -3
  274. package/skills/ssh/SKILL.md +81 -0
  275. package/skills/ssh/__init__.py +1 -0
  276. package/skills/ssh/handler.py +609 -0
  277. package/skills/ssh/manifest.yaml +182 -0
  278. package/tui/crannia.cmd +134 -134
  279. package/tui/crannia.sh +82 -0
  280. package/tui/crannia_tui/__init__.py +1 -1
  281. package/tui/crannia_tui/app.py +240 -17
  282. package/tui/crannia_tui/app.tcss +21 -0
  283. package/tui/crannia_tui/clipboard.py +78 -10
  284. package/tui/crannia_tui/commands.py +37 -0
  285. package/tui/crannia_tui/events.py +6 -0
  286. package/tui/crannia_tui/i18n.py +164 -164
  287. package/tui/crannia_tui/locales/en.json +32 -7
  288. package/tui/crannia_tui/paths.py +4 -1
  289. package/tui/crannia_tui/profile.py +178 -169
  290. package/tui/crannia_tui/settings.py +134 -134
  291. package/tui/crannia_tui/setup.py +44 -5
  292. package/tui/crannia_tui/ui.py +156 -16
  293. package/tui/crannia_tui/update.py +393 -389
  294. package/vendor/ripgrep/COPYING.txt +3 -3
  295. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  296. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  297. package/vendor/ripgrep/README.md +30 -14
  298. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  299. package/vendor/ripgrep/linux-x64/rg +0 -0
  300. package/vendor/ripgrep/package-source.json +15 -16
  301. package/web/__main__.py +12 -15
  302. package/web/server.py +8481 -8594
  303. package/web/static/img/channel-telegram.svg +1 -1
  304. package/web/static/img/channel-wechat.svg +1 -1
  305. package/web/templates/logs.html +49 -49
  306. package/web/templates/models.html +46 -46
@@ -1,818 +1,818 @@
1
- import os
2
- import sys
3
- import re
4
- import argparse
5
- from pathlib import Path
6
- from xml.etree import ElementTree as ET
7
-
8
- _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
9
- if str(_SCRIPTS_DIR) not in sys.path:
10
- sys.path.insert(0, str(_SCRIPTS_DIR))
11
-
12
- from console_encoding import configure_utf8_stdio # noqa: E402
13
-
14
- configure_utf8_stdio()
15
-
16
-
17
- SVG_NS = "http://www.w3.org/2000/svg"
18
- NSMAP = {"svg": SVG_NS}
19
-
20
- # Ensure pretty element names without ns0 prefix on write
21
- ET.register_namespace("", SVG_NS)
22
-
23
-
24
- TEXT_STYLE_ATTRS = {
25
- # common text styling
26
- "font-family",
27
- "font-size",
28
- "font-weight",
29
- "font-style",
30
- "font-variant",
31
- "font-stretch",
32
- "letter-spacing",
33
- "word-spacing",
34
- "kerning",
35
- "text-anchor",
36
- "text-decoration",
37
- "dominant-baseline",
38
- "writing-mode",
39
- "direction",
40
- # color/paint
41
- "fill",
42
- "fill-opacity",
43
- "stroke",
44
- "stroke-width",
45
- "stroke-opacity",
46
- "opacity",
47
- "paint-order",
48
- # transforms/filters
49
- "transform",
50
- "clip-path",
51
- "filter",
52
- }
53
-
54
-
55
- num_re = re.compile(r"^[\s,]*([+-]?(?:\d+\.?\d*|\d*\.\d+))")
56
-
57
-
58
- def parse_first_number(val: str | None) -> float | None:
59
- """Parse the first numeric token from an SVG attribute value."""
60
- if val is None:
61
- return None
62
- m = num_re.match(val)
63
- if not m:
64
- return None
65
- try:
66
- return float(m.group(1))
67
- except ValueError:
68
- return None
69
-
70
-
71
- def format_number(n: float | None) -> str | None:
72
- """Format a float for compact SVG attribute output."""
73
- if n is None:
74
- return None
75
- if abs(n - round(n)) < 1e-6:
76
- return str(int(round(n)))
77
- # Trim trailing zeros
78
- s = f"{n:.6f}".rstrip("0").rstrip(".")
79
- return s
80
-
81
-
82
- def parse_style(style_str: str | None) -> dict[str, str]:
83
- """Parse an inline SVG style string into a mapping."""
84
- out: dict[str, str] = {}
85
- if not style_str:
86
- return out
87
- # split by ; and then :
88
- for chunk in style_str.split(";"):
89
- if not chunk.strip():
90
- continue
91
- if ":" in chunk:
92
- k, v = chunk.split(":", 1)
93
- out[k.strip()] = v.strip()
94
- return out
95
-
96
-
97
- def style_to_string(style_map: dict[str, str]) -> str:
98
- """Serialize a style mapping back into an inline SVG style string."""
99
- if not style_map:
100
- return ""
101
- return ";".join(f"{k}:{v}" for k, v in style_map.items())
102
-
103
-
104
- def merge_styles(parent_style: str | None, child_style: str | None) -> str:
105
- """Merge parent and child inline styles, preferring child values."""
106
- p = parse_style(parent_style)
107
- c = parse_style(child_style)
108
- p.update(c) # child overrides
109
- return style_to_string(p)
110
-
111
-
112
- def get_attr(elem: ET.Element | None, name: str, default: str | None = None) -> str | None:
113
- """Read an attribute from an element with a default fallback."""
114
- return elem.get(name) if elem is not None and name in elem.attrib else default
115
-
116
-
117
- def compute_line_positions(
118
- text_el: ET.Element,
119
- tspan_el: ET.Element,
120
- cur_x: float | None,
121
- cur_y: float | None,
122
- ) -> tuple[float | None, float | None]:
123
- """
124
- Compute absolute x,y for a tspan based on parent <text> current baseline and tspan's x/y/dx/dy.
125
- Returns (new_x, new_y).
126
- """
127
- del text_el
128
- # Prefer explicit x/y on tspan
129
- t_x_attr = get_attr(tspan_el, "x")
130
- t_y_attr = get_attr(tspan_el, "y")
131
- t_dx_attr = get_attr(tspan_el, "dx")
132
- t_dy_attr = get_attr(tspan_el, "dy")
133
-
134
- if t_x_attr is not None:
135
- nx = parse_first_number(t_x_attr)
136
- elif t_dx_attr is not None:
137
- dx = parse_first_number(t_dx_attr) or 0.0
138
- nx = (cur_x or 0.0) + dx
139
- else:
140
- nx = cur_x
141
-
142
- if t_y_attr is not None:
143
- ny = parse_first_number(t_y_attr)
144
- elif t_dy_attr is not None:
145
- dy = parse_first_number(t_dy_attr) or 0.0
146
- ny = (cur_y or 0.0) + dy
147
- else:
148
- ny = cur_y
149
-
150
- return nx, ny
151
-
152
-
153
- def collect_text_content(el: ET.Element) -> str:
154
- """Collect all text content from an element subtree."""
155
- # Gather all text within the element (flatten nested tspans if any)
156
- parts = []
157
- for s in el.itertext():
158
- if s:
159
- parts.append(s)
160
- return "".join(parts)
161
-
162
-
163
- def copy_text_attrs(
164
- src_el: ET.Element,
165
- dst_el: ET.Element,
166
- exclude: set[str] | None = None,
167
- ) -> None:
168
- """Copy shared text styling attributes between SVG text elements."""
169
- exclude = exclude or set()
170
- # Copy style string first
171
- if "style" in src_el.attrib and "style" not in exclude:
172
- dst_el.set("style", src_el.attrib["style"])
173
- for k in TEXT_STYLE_ATTRS:
174
- if k in exclude:
175
- continue
176
- v = src_el.get(k)
177
- if v is not None:
178
- dst_el.set(k, v)
179
- # xml:space preservation
180
- xml_space = src_el.get("{http://www.w3.org/XML/1998/namespace}space")
181
- if xml_space is not None and "{http://www.w3.org/XML/1998/namespace}space" not in exclude:
182
- dst_el.set("{http://www.w3.org/XML/1998/namespace}space", xml_space)
183
-
184
-
185
- PARAGRAPH_MARK_ATTR = "data-paragraph-line-height"
186
- PARAGRAPH_SPACE_BEFORE_ATTR = "data-paragraph-space-before"
187
- # Marks a line-break tspan as a SOFT break inside the current paragraph
188
- # (SVG used dy to simulate text wrapping; the downstream converter should
189
- # merge its runs into the previous <a:p> rather than start a new one).
190
- PARAGRAPH_SOFT_BREAK_ATTR = "data-paragraph-soft-break"
191
-
192
- # Tolerance for detecting "base line-height" vs "paragraph gap": dy values
193
- # within ±DY_TOLERANCE_PX of each other are considered the same line-height.
194
- DY_TOLERANCE_PX = 0.5
195
- # Cap on dy / base ratio. Anything beyond this (e.g. a 5x gap) is rejected
196
- # as a real section break that shouldn't merge into one text frame.
197
- MAX_DY_MULTIPLIER = 3.0
198
- LIST_MARKER_RE = re.compile(
199
- r"^\s*(?:[•·・]\s*|[-–—*]\s+|\d+[.)、]\s+|[((]\d+[))]\s*)\S+"
200
- )
201
-
202
-
203
- def _starts_with_list_marker(line_group: list[ET.Element]) -> bool:
204
- """Return True when a visual line starts with an ordered/unordered marker."""
205
- text = "".join(collect_text_content(tspan) for tspan in line_group)
206
- return bool(LIST_MARKER_RE.match(text))
207
-
208
-
209
- def _tspan_has_positional_descendant(tspan: ET.Element) -> bool:
210
- """Return True if any nested tspan inside this one carries x/y/dy."""
211
- for child in list(tspan):
212
- if child.tag != f"{{{SVG_NS}}}tspan":
213
- continue
214
- for k in ("x", "y", "dy"):
215
- if child.get(k) is not None:
216
- return True
217
- if _tspan_has_positional_descendant(child):
218
- return True
219
- return False
220
-
221
-
222
- def _build_paragraph_child_view(
223
- text_el: ET.Element,
224
- is_svg_tag,
225
- ) -> tuple[list[ET.Element], ET.Element | None] | None:
226
- """Return direct tspan children plus an optional synthetic leading line.
227
-
228
- The synthetic line lets paragraph classification accept common SVG
229
- authoring where the first visual line is direct text under <text>. This
230
- helper does not mutate the tree; _emit_mergeable_paragraph commits the
231
- synthetic line only after all paragraph checks pass.
232
- """
233
- direct_children = list(text_el)
234
- direct_tspans = [c for c in direct_children if is_svg_tag(c, "tspan")]
235
- if len(direct_tspans) != len(direct_children):
236
- return None
237
-
238
- raw_lead = text_el.text or ""
239
- synthetic_first: ET.Element | None = None
240
- if raw_lead.strip():
241
- base_x_raw = get_attr(text_el, "x")
242
- if base_x_raw is None:
243
- return None
244
- if any((child.tail or "").strip() for child in direct_tspans):
245
- return None
246
- synthetic_first = ET.Element(f"{{{SVG_NS}}}tspan")
247
- synthetic_first.set("x", base_x_raw)
248
- synthetic_first.text = raw_lead.lstrip()
249
-
250
- view = ([synthetic_first] if synthetic_first is not None else []) + direct_tspans
251
- return view, synthetic_first
252
-
253
-
254
- def _get_font_size_px(elem: ET.Element) -> float | None:
255
- """Read font-size from an attribute or inline style."""
256
- size = parse_first_number(get_attr(elem, "font-size"))
257
- if size is not None:
258
- return size
259
- style_size = parse_style(get_attr(elem, "style")).get("font-size")
260
- return parse_first_number(style_size)
261
-
262
-
263
- def _classify_paragraph_block(
264
- text_el: ET.Element,
265
- is_svg_tag,
266
- is_new_line_tspan,
267
- ) -> tuple[float, list[float], list[bool], list[list[ET.Element]], ET.Element | None] | None:
268
- """Detect a mergeable paragraph block.
269
-
270
- Returns ``(base_line_height_px, extra_space_before_px_per_line,
271
- is_soft_break_per_line, line_groups, synthetic_first_line)`` if the children
272
- form a mergeable paragraph. Each list has one entry per direct-child tspan
273
- (line), including a synthetic first line when the source used leading text:
274
-
275
- - extra_space_before_px_per_line[i]: extra px above base line-height,
276
- used as <a:spcBef> on the downstream <a:p>. First entry is 0.
277
- - is_soft_break_per_line[i]: True if this line should merge into the
278
- previous <a:p> (SVG dy was simulating word-wrap); False if it starts
279
- a fresh <a:p>. First entry is always False (paragraph head).
280
-
281
- Conditions (all must hold):
282
- - No direct text under <text>, except simple leading text that can be
283
- promoted into a synthetic first-line <tspan>.
284
- - Every direct child is a <tspan>.
285
- - Every logical line starts with a new-line tspan.
286
- - Direct-child inline formatting tspans without x/y/dy are allowed only
287
- after a line starts; they are normalized into the previous line.
288
- - First line-break tspan has dy == 0 (or no dy).
289
- - All subsequent line-break tspans use positive dy (no <y>).
290
- - dy values cluster around a single minimum "base line-height";
291
- any larger dy must be ≤ MAX_DY_MULTIPLIER × base. Anything larger
292
- is treated as a section break and rejected.
293
- - Every line-break tspan that sets x repeats the parent <text>'s x.
294
- - No nested tspan inside any line carries x/y/dy.
295
- """
296
- base_x = parse_first_number(get_attr(text_el, "x"))
297
- child_view = _build_paragraph_child_view(text_el, is_svg_tag)
298
- if child_view is None:
299
- return None
300
- direct_tspans, synthetic_first = child_view
301
-
302
- if len(direct_tspans) < 2:
303
- return None
304
-
305
- line_groups: list[list[ET.Element]] = []
306
- for tspan in direct_tspans:
307
- if is_new_line_tspan(tspan):
308
- line_groups.append([tspan])
309
- else:
310
- if not line_groups:
311
- return None
312
- if _tspan_has_positional_descendant(tspan):
313
- return None
314
- line_groups[-1].append(tspan)
315
-
316
- if len(line_groups) < 2:
317
- return None
318
-
319
- # First pass: validate per-line structural rules and collect dy values.
320
- dy_values: list[float] = [] # one per line (0 for first)
321
- for idx, group in enumerate(line_groups):
322
- tspan = group[0]
323
-
324
- t_y = get_attr(tspan, "y")
325
- if t_y is not None:
326
- return None
327
-
328
- t_x_raw = get_attr(tspan, "x")
329
- if t_x_raw is not None:
330
- t_x = parse_first_number(t_x_raw)
331
- if base_x is None or t_x is None or abs(t_x - base_x) > 1e-6:
332
- return None
333
-
334
- t_dy_raw = get_attr(tspan, "dy")
335
- t_dy = parse_first_number(t_dy_raw) if t_dy_raw is not None else None
336
-
337
- if idx == 0:
338
- if t_dy is not None and abs(t_dy) > 1e-6:
339
- return None
340
- dy_values.append(0.0)
341
- else:
342
- if t_dy is None or t_dy <= 0:
343
- return None
344
- dy_values.append(t_dy)
345
-
346
- if _tspan_has_positional_descendant(tspan):
347
- return None
348
-
349
- # Second pass: pick the base line-height as the minimum positive dy and
350
- # express each line's dy as base + extra space-before.
351
- positive_dys = [d for d in dy_values[1:] if d > 0]
352
- if not positive_dys:
353
- return None
354
- base = min(positive_dys)
355
- font_size = _get_font_size_px(text_el)
356
- if font_size is not None and base > font_size * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX:
357
- return None
358
-
359
- extras: list[float] = [0.0] # first line never has space-before
360
- soft_breaks: list[bool] = [False] # first line starts a paragraph
361
- for idx, d in enumerate(dy_values[1:], start=1):
362
- if d + DY_TOLERANCE_PX < base:
363
- return None # below base — line overlap, not a paragraph
364
- if d > base * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX:
365
- return None # gap too large — treat as section break
366
- extra = d - base
367
- if extra < 0:
368
- extra = 0.0
369
- # dy at the base line-height = soft break (SVG was simulating wrap);
370
- # dy strictly greater than base = hard paragraph break. List markers
371
- # also start a fresh paragraph so bullet/ordered items do not merge
372
- # into the previous item when exported to PowerPoint.
373
- is_soft = (
374
- abs(extra) <= DY_TOLERANCE_PX
375
- and not _starts_with_list_marker(line_groups[idx])
376
- )
377
- extras.append(0.0 if is_soft else extra)
378
- soft_breaks.append(is_soft)
379
-
380
- return base, extras, soft_breaks, line_groups, synthetic_first
381
-
382
-
383
- def _emit_mergeable_paragraph(
384
- text_el: ET.Element,
385
- base_dy: float,
386
- extras: list[float],
387
- soft_breaks: list[bool],
388
- line_groups: list[list[ET.Element]],
389
- synthetic_first: ET.Element | None = None,
390
- ) -> None:
391
- """Rewrite text_el in place so it stays a single <text> with paragraph rows.
392
-
393
- The base line-height goes on the parent <text> via PARAGRAPH_MARK_ATTR.
394
- Each direct-child tspan is normalized: x/y/dy stripped; inline-run
395
- styling and nested tspans are preserved. Per-tspan attrs:
396
- - PARAGRAPH_SOFT_BREAK_ATTR="1" on tspans that should be appended to
397
- the previous <a:p> downstream (SVG used dy to simulate wrap)
398
- - PARAGRAPH_SPACE_BEFORE_ATTR on tspans that open a new paragraph
399
- with an extra gap (omitted when 0)
400
- """
401
- text_el.set(PARAGRAPH_MARK_ATTR, format_number(base_dy))
402
- if synthetic_first is not None:
403
- text_el.text = None
404
- text_el.insert(0, synthetic_first)
405
-
406
- # Normalize authoring variants before the downstream converter reads the
407
- # paragraph: a line-break tspan may be followed by direct-child inline
408
- # formatting tspans. Move those inline runs under the line-break tspan so
409
- # every direct child of <text> is one logical visual line.
410
- normalized_lines: list[ET.Element] = []
411
- for group in line_groups:
412
- line = group[0]
413
- for inline_tspan in group[1:]:
414
- try:
415
- text_el.remove(inline_tspan)
416
- except ValueError:
417
- pass
418
- if inline_tspan.tail and not inline_tspan.tail.strip():
419
- inline_tspan.tail = None
420
- line.append(inline_tspan)
421
- normalized_lines.append(line)
422
-
423
- for child in list(text_el):
424
- if child not in normalized_lines:
425
- text_el.remove(child)
426
-
427
- extras_iter = iter(extras)
428
- soft_iter = iter(soft_breaks)
429
- for tspan in normalized_lines:
430
- for k in ("x", "y", "dy"):
431
- if k in tspan.attrib:
432
- del tspan.attrib[k]
433
- try:
434
- extra = next(extras_iter)
435
- soft = next(soft_iter)
436
- except StopIteration:
437
- extra = 0.0
438
- soft = False
439
- if soft:
440
- tspan.set(PARAGRAPH_SOFT_BREAK_ATTR, "1")
441
- elif extra > 1e-6:
442
- tspan.set(PARAGRAPH_SPACE_BEFORE_ATTR, format_number(extra))
443
-
444
-
445
- def flatten_text_with_tspans(
446
- tree: ET.ElementTree,
447
- merge_paragraphs: bool = False,
448
- ) -> bool:
449
- """Flatten multi-line tspan text into independent text nodes when needed.
450
-
451
- When `merge_paragraphs` is True, mergeable paragraph blocks (same x,
452
- dy clustered around one base line-height) are kept as a single <text>
453
- so downstream conversion emits one editable PowerPoint text frame
454
- with multiple <a:p>. Default False preserves the original behavior:
455
- every line-break tspan becomes its own <text>, matching the SVG's
456
- pixel-fidelity contract.
457
- """
458
- root = tree.getroot()
459
- parent_map = {c: p for p in root.iter() for c in p}
460
- changed = False
461
-
462
- def is_svg_tag(el: ET.Element, name: str) -> bool:
463
- return el.tag == f"{{{SVG_NS}}}{name}"
464
-
465
- def is_new_line_tspan(tspan: ET.Element) -> bool:
466
- """Determine whether a tspan represents a new line (has its own y or non-zero dy)."""
467
- t_dy_attr = get_attr(tspan, "dy")
468
- t_y_attr = get_attr(tspan, "y")
469
- t_x_attr = get_attr(tspan, "x")
470
- dy_val = parse_first_number(t_dy_attr) if t_dy_attr is not None else None
471
- # Has its own y attribute, or has non-zero dy, or has its own x attribute (indicating a new line)
472
- if t_y_attr is not None:
473
- return True
474
- if dy_val is not None and dy_val != 0:
475
- return True
476
- # If tspan has an x attribute and there are preceding sibling tspans, treat it as a new line
477
- if t_x_attr is not None:
478
- return True
479
- return False
480
-
481
- # Collect candidates first to avoid modifying while iterating
482
- candidates = []
483
- for el in root.iter():
484
- if is_svg_tag(el, "text"):
485
- has_tspan_child = any(is_svg_tag(c, "tspan") for c in list(el))
486
- if has_tspan_child:
487
- candidates.append(el)
488
-
489
- for text_el in candidates:
490
- parent = parent_map.get(text_el)
491
- if parent is None:
492
- continue
493
-
494
- # First check whether any tspan needs flattening (dy != 0 or has its own y attribute)
495
- needs_flatten = False
496
- for child in list(text_el):
497
- if not is_svg_tag(child, "tspan"):
498
- continue
499
- if is_new_line_tspan(child):
500
- needs_flatten = True
501
- break
502
-
503
- # If no tspan needs a line break, skip the entire text element
504
- if not needs_flatten:
505
- continue
506
-
507
- # Paragraph fast-path (opt-in via merge_paragraphs=True): if the
508
- # children form a mergeable paragraph (same x, dy clustered around
509
- # one base line-height with optional paragraph gaps, no nested
510
- # positional tspans), keep as one <text> and let the downstream
511
- # converter emit multiple <a:p> runs. When disabled, every tspan
512
- # gets its own independent <text> so the SVG's exact line layout
513
- # is preserved in PowerPoint.
514
- if merge_paragraphs:
515
- paragraph = _classify_paragraph_block(text_el, is_svg_tag, is_new_line_tspan)
516
- if paragraph is not None:
517
- base_dy, extras, soft_breaks, line_groups, synthetic_first = paragraph
518
- _emit_mergeable_paragraph(
519
- text_el,
520
- base_dy,
521
- extras,
522
- soft_breaks,
523
- line_groups,
524
- synthetic_first=synthetic_first,
525
- )
526
- changed = True
527
- continue
528
-
529
- base_x = parse_first_number(get_attr(text_el, "x")) or 0.0
530
- base_y = parse_first_number(get_attr(text_el, "y")) or 0.0
531
- cur_x, cur_y = base_x, base_y
532
-
533
- new_texts = []
534
-
535
- # Collect tspan elements belonging to the same line
536
- current_line_tspans = []
537
- current_line_lead_text = None
538
-
539
- # Leading text directly under <text>
540
- lead_text = (text_el.text or "").strip()
541
- if lead_text:
542
- current_line_lead_text = lead_text
543
-
544
- for idx, child in enumerate(list(text_el)):
545
- if not is_svg_tag(child, "tspan"):
546
- continue
547
-
548
- content = collect_text_content(child)
549
-
550
- # Check whether this tspan starts a new line
551
- if is_new_line_tspan(child):
552
- # Save previously accumulated same-line tspans first
553
- if current_line_tspans or current_line_lead_text:
554
- ne = _create_text_element_from_line(
555
- text_el, current_line_lead_text, current_line_tspans, cur_x, cur_y
556
- )
557
- new_texts.append(ne)
558
- current_line_tspans = []
559
- current_line_lead_text = None
560
-
561
- # Update position
562
- nx, ny = compute_line_positions(text_el, child, cur_x, cur_y)
563
- cur_x, cur_y = nx, ny
564
-
565
- # If content is not empty, add to the current line
566
- if content.strip():
567
- current_line_tspans.append(child)
568
-
569
- # Process the last line
570
- if current_line_tspans or current_line_lead_text:
571
- ne = _create_text_element_from_line(
572
- text_el, current_line_lead_text, current_line_tspans, cur_x, cur_y
573
- )
574
- new_texts.append(ne)
575
-
576
- if new_texts:
577
- # Replace original <text> with the list of new <text> nodes
578
- try:
579
- idx = list(parent).index(text_el)
580
- except ValueError:
581
- idx = None
582
-
583
- # Insert in place to preserve drawing order
584
- for i, ne in enumerate(new_texts):
585
- if idx is not None:
586
- parent.insert(idx + i, ne)
587
- else:
588
- parent.append(ne)
589
-
590
- # Remove the original <text>
591
- parent.remove(text_el)
592
- changed = True
593
-
594
- return changed
595
-
596
-
597
- def _has_tspan_children(elem: ET.Element) -> bool:
598
- """Return True if elem contains any nested <tspan> children (inline runs)."""
599
- return any(c.tag == f"{{{SVG_NS}}}tspan" for c in list(elem))
600
-
601
-
602
- def _copy_inline_tspan(src: ET.Element, strip_line_attrs: bool) -> ET.Element:
603
- """Deep-copy a tspan as an inline run, preserving nested tspan structure, head text, and tail text.
604
-
605
- When strip_line_attrs is True, x/y/dy on the copied tspan are dropped because the
606
- enclosing <text> now positions the line. dx is preserved (safe inline kerning).
607
- Nested tspans are copied recursively without stripping (they are already inline-only).
608
- """
609
- new = ET.Element(f"{{{SVG_NS}}}tspan")
610
- for k, v in src.attrib.items():
611
- if strip_line_attrs and k in ("x", "y", "dy"):
612
- continue
613
- new.set(k, v)
614
- new.text = src.text
615
- for child in list(src):
616
- if child.tag == f"{{{SVG_NS}}}tspan":
617
- new.append(_copy_inline_tspan(child, strip_line_attrs=False))
618
- new.tail = src.tail
619
- return new
620
-
621
-
622
- def _create_text_element_from_line(
623
- text_el: ET.Element,
624
- lead_text: str | None,
625
- tspans: list[ET.Element],
626
- x: float | None,
627
- y: float | None,
628
- ) -> ET.Element:
629
- """
630
- Create a text element from a line's content (may contain leading text and multiple tspans).
631
- If there is only one tspan with no nested tspan children and no leading text, the line
632
- collapses to a plain <text>...</text>. Otherwise the tspan structure (including any
633
- nested inline tspans) is preserved so per-run formatting survives the flatten step.
634
- """
635
- ne = ET.Element(f"{{{SVG_NS}}}text")
636
-
637
- # Copy attrs from parent <text>
638
- copy_text_attrs(text_el, ne, exclude={"x", "y"})
639
- ne.set("x", format_number(x))
640
- ne.set("y", format_number(y))
641
-
642
- # Transform
643
- p_tf = text_el.get("transform")
644
- if p_tf:
645
- ne.set("transform", p_tf)
646
-
647
- # Compact path: a single tspan with no nested inline runs collapses to <text>text</text>
648
- if not lead_text and len(tspans) == 1 and not _has_tspan_children(tspans[0]):
649
- tspan = tspans[0]
650
- content = collect_text_content(tspan)
651
-
652
- # Merge style
653
- merged_style = merge_styles(text_el.get("style"), tspan.get("style"))
654
- if merged_style:
655
- ne.set("style", merged_style)
656
-
657
- # Override specific attributes from tspan
658
- for attr in TEXT_STYLE_ATTRS:
659
- cv = tspan.get(attr)
660
- if cv is not None:
661
- ne.set(attr, cv)
662
-
663
- # Combine transform
664
- c_tf = tspan.get("transform")
665
- if p_tf and c_tf:
666
- ne.set("transform", f"{p_tf} {c_tf}")
667
- elif c_tf:
668
- ne.set("transform", c_tf)
669
-
670
- ne.text = content
671
- else:
672
- # Preserve tspan structure, including nested inline tspans and tail text
673
- if lead_text:
674
- ne.text = lead_text
675
-
676
- for tspan in tspans:
677
- ne.append(_copy_inline_tspan(tspan, strip_line_attrs=True))
678
-
679
- return ne
680
-
681
-
682
- def process_svg_file(
683
- src_path: str,
684
- dst_path: str,
685
- merge_paragraphs: bool = False,
686
- ) -> bool:
687
- """Flatten eligible tspan lines in one SVG file."""
688
- try:
689
- tree = ET.parse(src_path)
690
- except ET.ParseError as e:
691
- print(f"[WARN] Failed to parse {src_path}: {e}")
692
- return False
693
-
694
- changed = flatten_text_with_tspans(tree, merge_paragraphs=merge_paragraphs)
695
-
696
- # Ensure destination directory exists
697
- os.makedirs(os.path.dirname(dst_path), exist_ok=True)
698
-
699
- # Write out XML without XML declaration to mimic input style
700
- tree.write(dst_path, encoding="utf-8", xml_declaration=False, method="xml")
701
- return changed
702
-
703
-
704
- def _compute_default_out_base(inp: str) -> str:
705
- """Compute default output path for directory or file input."""
706
- if os.path.isdir(inp):
707
- # Default: if input ends with svg_output, use sibling svg_output_flattext;
708
- # otherwise append _flattext to the directory name at the same level.
709
- head, tail = os.path.split(os.path.normpath(inp))
710
- if tail == "svg_output":
711
- return os.path.join(head, "svg_output_flattext")
712
- return inp.rstrip("/\\") + "_flattext"
713
- else:
714
- base, ext = os.path.splitext(inp)
715
- return base + "_flattext" + ext
716
-
717
-
718
- def _interactive_get_paths() -> tuple[str | None, str | None]:
719
- """
720
- Interactive mode: prompt the user for input path (SVG file or directory)
721
- and optional output path. Returns (inp, out_base) or (None, None) if cancelled.
722
- """
723
- print("[Interactive mode] No arguments provided; running interactively.")
724
- print("Please enter the path to process (SVG file or directory containing SVGs).")
725
- print("Enter q to quit.\n")
726
-
727
- while True:
728
- raw = input("Input path (file/dir): ").strip()
729
- if raw.lower() in {"q", "quit", "exit"} or raw == "":
730
- return None, None
731
- inp = os.path.expanduser(raw)
732
- if os.path.exists(inp):
733
- break
734
- print("Path does not exist. Please re-enter or enter q to quit.")
735
-
736
- default_out = _compute_default_out_base(inp)
737
- if os.path.isdir(inp):
738
- prompt = f"Output directory [default: {default_out}]: "
739
- else:
740
- prompt = f"Output file [default: {default_out}]: "
741
-
742
- raw_out = input(prompt).strip()
743
- out_base = os.path.expanduser(raw_out) if raw_out else default_out
744
-
745
- return inp, out_base
746
-
747
-
748
- def main() -> None:
749
- """Run the CLI entry point."""
750
- # CLI parsing with optional interactive mode
751
- parser = argparse.ArgumentParser(
752
- description="Flatten <tspan> lines into multiple <text> nodes for better compatibility.",
753
- add_help=True,
754
- )
755
- parser.add_argument("input", nargs="?", help="Input path: SVG file or directory")
756
- parser.add_argument("output", nargs="?", help="Optional output file/dir")
757
- parser.add_argument(
758
- "-i",
759
- "--interactive",
760
- action="store_true",
761
- help="Run in interactive prompt mode to input paths",
762
- )
763
- parser.add_argument(
764
- "--merge-paragraphs",
765
- action="store_true",
766
- default=False,
767
- help=(
768
- "Opt-in: merge mergeable paragraph blocks (same x, dy clustered "
769
- "around one base line-height) into a single <text> annotated for "
770
- "downstream multi-<a:p> conversion. Default off — every line-break "
771
- "tspan becomes its own <text>, preserving SVG pixel fidelity."
772
- ),
773
- )
774
-
775
- args = parser.parse_args()
776
-
777
- if args.interactive or not args.input:
778
- inp, out_base = _interactive_get_paths()
779
- if not inp:
780
- print("Cancelled. Usage: python3 scripts/svg_finalize/flatten_tspan.py <input_dir_or_svg> [output_dir]")
781
- sys.exit(0)
782
- else:
783
- inp = args.input
784
- out_base = args.output
785
-
786
- if os.path.isdir(inp):
787
- # If output base not provided, create a sibling folder named svg_output_flattext for svg_output
788
- if out_base is None:
789
- out_base = _compute_default_out_base(inp)
790
-
791
- total = 0
792
- changed_count = 0
793
- out_base_abs = os.path.abspath(out_base)
794
- for root, dirs, files in os.walk(inp):
795
- # Avoid recursing into the output directory when it lives under input
796
- dirs[:] = [d for d in dirs if os.path.abspath(os.path.join(root, d)) != out_base_abs]
797
- rel_root = os.path.relpath(root, inp)
798
- for f in files:
799
- if not f.lower().endswith(".svg"):
800
- continue
801
- src = os.path.join(root, f)
802
- dst = os.path.join(out_base, rel_root, f) if rel_root != "." else os.path.join(out_base, f)
803
- total += 1
804
- changed = process_svg_file(src, dst, merge_paragraphs=args.merge_paragraphs)
805
- if changed:
806
- changed_count += 1
807
- print(f"Processed {total} SVG(s). With <tspan> flattened: {changed_count}.")
808
- print(f"Output written to: {out_base}")
809
- else:
810
- src = inp
811
- if out_base is None:
812
- out_base = _compute_default_out_base(src)
813
- changed = process_svg_file(src, out_base, merge_paragraphs=args.merge_paragraphs)
814
- print(f"Written: {out_base} (flattened: {changed})")
815
-
816
-
817
- if __name__ == "__main__":
818
- main()
1
+ import os
2
+ import sys
3
+ import re
4
+ import argparse
5
+ from pathlib import Path
6
+ from xml.etree import ElementTree as ET
7
+
8
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
9
+ if str(_SCRIPTS_DIR) not in sys.path:
10
+ sys.path.insert(0, str(_SCRIPTS_DIR))
11
+
12
+ from console_encoding import configure_utf8_stdio # noqa: E402
13
+
14
+ configure_utf8_stdio()
15
+
16
+
17
+ SVG_NS = "http://www.w3.org/2000/svg"
18
+ NSMAP = {"svg": SVG_NS}
19
+
20
+ # Ensure pretty element names without ns0 prefix on write
21
+ ET.register_namespace("", SVG_NS)
22
+
23
+
24
+ TEXT_STYLE_ATTRS = {
25
+ # common text styling
26
+ "font-family",
27
+ "font-size",
28
+ "font-weight",
29
+ "font-style",
30
+ "font-variant",
31
+ "font-stretch",
32
+ "letter-spacing",
33
+ "word-spacing",
34
+ "kerning",
35
+ "text-anchor",
36
+ "text-decoration",
37
+ "dominant-baseline",
38
+ "writing-mode",
39
+ "direction",
40
+ # color/paint
41
+ "fill",
42
+ "fill-opacity",
43
+ "stroke",
44
+ "stroke-width",
45
+ "stroke-opacity",
46
+ "opacity",
47
+ "paint-order",
48
+ # transforms/filters
49
+ "transform",
50
+ "clip-path",
51
+ "filter",
52
+ }
53
+
54
+
55
+ num_re = re.compile(r"^[\s,]*([+-]?(?:\d+\.?\d*|\d*\.\d+))")
56
+
57
+
58
+ def parse_first_number(val: str | None) -> float | None:
59
+ """Parse the first numeric token from an SVG attribute value."""
60
+ if val is None:
61
+ return None
62
+ m = num_re.match(val)
63
+ if not m:
64
+ return None
65
+ try:
66
+ return float(m.group(1))
67
+ except ValueError:
68
+ return None
69
+
70
+
71
+ def format_number(n: float | None) -> str | None:
72
+ """Format a float for compact SVG attribute output."""
73
+ if n is None:
74
+ return None
75
+ if abs(n - round(n)) < 1e-6:
76
+ return str(int(round(n)))
77
+ # Trim trailing zeros
78
+ s = f"{n:.6f}".rstrip("0").rstrip(".")
79
+ return s
80
+
81
+
82
+ def parse_style(style_str: str | None) -> dict[str, str]:
83
+ """Parse an inline SVG style string into a mapping."""
84
+ out: dict[str, str] = {}
85
+ if not style_str:
86
+ return out
87
+ # split by ; and then :
88
+ for chunk in style_str.split(";"):
89
+ if not chunk.strip():
90
+ continue
91
+ if ":" in chunk:
92
+ k, v = chunk.split(":", 1)
93
+ out[k.strip()] = v.strip()
94
+ return out
95
+
96
+
97
+ def style_to_string(style_map: dict[str, str]) -> str:
98
+ """Serialize a style mapping back into an inline SVG style string."""
99
+ if not style_map:
100
+ return ""
101
+ return ";".join(f"{k}:{v}" for k, v in style_map.items())
102
+
103
+
104
+ def merge_styles(parent_style: str | None, child_style: str | None) -> str:
105
+ """Merge parent and child inline styles, preferring child values."""
106
+ p = parse_style(parent_style)
107
+ c = parse_style(child_style)
108
+ p.update(c) # child overrides
109
+ return style_to_string(p)
110
+
111
+
112
+ def get_attr(elem: ET.Element | None, name: str, default: str | None = None) -> str | None:
113
+ """Read an attribute from an element with a default fallback."""
114
+ return elem.get(name) if elem is not None and name in elem.attrib else default
115
+
116
+
117
+ def compute_line_positions(
118
+ text_el: ET.Element,
119
+ tspan_el: ET.Element,
120
+ cur_x: float | None,
121
+ cur_y: float | None,
122
+ ) -> tuple[float | None, float | None]:
123
+ """
124
+ Compute absolute x,y for a tspan based on parent <text> current baseline and tspan's x/y/dx/dy.
125
+ Returns (new_x, new_y).
126
+ """
127
+ del text_el
128
+ # Prefer explicit x/y on tspan
129
+ t_x_attr = get_attr(tspan_el, "x")
130
+ t_y_attr = get_attr(tspan_el, "y")
131
+ t_dx_attr = get_attr(tspan_el, "dx")
132
+ t_dy_attr = get_attr(tspan_el, "dy")
133
+
134
+ if t_x_attr is not None:
135
+ nx = parse_first_number(t_x_attr)
136
+ elif t_dx_attr is not None:
137
+ dx = parse_first_number(t_dx_attr) or 0.0
138
+ nx = (cur_x or 0.0) + dx
139
+ else:
140
+ nx = cur_x
141
+
142
+ if t_y_attr is not None:
143
+ ny = parse_first_number(t_y_attr)
144
+ elif t_dy_attr is not None:
145
+ dy = parse_first_number(t_dy_attr) or 0.0
146
+ ny = (cur_y or 0.0) + dy
147
+ else:
148
+ ny = cur_y
149
+
150
+ return nx, ny
151
+
152
+
153
+ def collect_text_content(el: ET.Element) -> str:
154
+ """Collect all text content from an element subtree."""
155
+ # Gather all text within the element (flatten nested tspans if any)
156
+ parts = []
157
+ for s in el.itertext():
158
+ if s:
159
+ parts.append(s)
160
+ return "".join(parts)
161
+
162
+
163
+ def copy_text_attrs(
164
+ src_el: ET.Element,
165
+ dst_el: ET.Element,
166
+ exclude: set[str] | None = None,
167
+ ) -> None:
168
+ """Copy shared text styling attributes between SVG text elements."""
169
+ exclude = exclude or set()
170
+ # Copy style string first
171
+ if "style" in src_el.attrib and "style" not in exclude:
172
+ dst_el.set("style", src_el.attrib["style"])
173
+ for k in TEXT_STYLE_ATTRS:
174
+ if k in exclude:
175
+ continue
176
+ v = src_el.get(k)
177
+ if v is not None:
178
+ dst_el.set(k, v)
179
+ # xml:space preservation
180
+ xml_space = src_el.get("{http://www.w3.org/XML/1998/namespace}space")
181
+ if xml_space is not None and "{http://www.w3.org/XML/1998/namespace}space" not in exclude:
182
+ dst_el.set("{http://www.w3.org/XML/1998/namespace}space", xml_space)
183
+
184
+
185
+ PARAGRAPH_MARK_ATTR = "data-paragraph-line-height"
186
+ PARAGRAPH_SPACE_BEFORE_ATTR = "data-paragraph-space-before"
187
+ # Marks a line-break tspan as a SOFT break inside the current paragraph
188
+ # (SVG used dy to simulate text wrapping; the downstream converter should
189
+ # merge its runs into the previous <a:p> rather than start a new one).
190
+ PARAGRAPH_SOFT_BREAK_ATTR = "data-paragraph-soft-break"
191
+
192
+ # Tolerance for detecting "base line-height" vs "paragraph gap": dy values
193
+ # within ±DY_TOLERANCE_PX of each other are considered the same line-height.
194
+ DY_TOLERANCE_PX = 0.5
195
+ # Cap on dy / base ratio. Anything beyond this (e.g. a 5x gap) is rejected
196
+ # as a real section break that shouldn't merge into one text frame.
197
+ MAX_DY_MULTIPLIER = 3.0
198
+ LIST_MARKER_RE = re.compile(
199
+ r"^\s*(?:[•·・]\s*|[-–—*]\s+|\d+[.)、]\s+|[((]\d+[))]\s*)\S+"
200
+ )
201
+
202
+
203
+ def _starts_with_list_marker(line_group: list[ET.Element]) -> bool:
204
+ """Return True when a visual line starts with an ordered/unordered marker."""
205
+ text = "".join(collect_text_content(tspan) for tspan in line_group)
206
+ return bool(LIST_MARKER_RE.match(text))
207
+
208
+
209
+ def _tspan_has_positional_descendant(tspan: ET.Element) -> bool:
210
+ """Return True if any nested tspan inside this one carries x/y/dy."""
211
+ for child in list(tspan):
212
+ if child.tag != f"{{{SVG_NS}}}tspan":
213
+ continue
214
+ for k in ("x", "y", "dy"):
215
+ if child.get(k) is not None:
216
+ return True
217
+ if _tspan_has_positional_descendant(child):
218
+ return True
219
+ return False
220
+
221
+
222
+ def _build_paragraph_child_view(
223
+ text_el: ET.Element,
224
+ is_svg_tag,
225
+ ) -> tuple[list[ET.Element], ET.Element | None] | None:
226
+ """Return direct tspan children plus an optional synthetic leading line.
227
+
228
+ The synthetic line lets paragraph classification accept common SVG
229
+ authoring where the first visual line is direct text under <text>. This
230
+ helper does not mutate the tree; _emit_mergeable_paragraph commits the
231
+ synthetic line only after all paragraph checks pass.
232
+ """
233
+ direct_children = list(text_el)
234
+ direct_tspans = [c for c in direct_children if is_svg_tag(c, "tspan")]
235
+ if len(direct_tspans) != len(direct_children):
236
+ return None
237
+
238
+ raw_lead = text_el.text or ""
239
+ synthetic_first: ET.Element | None = None
240
+ if raw_lead.strip():
241
+ base_x_raw = get_attr(text_el, "x")
242
+ if base_x_raw is None:
243
+ return None
244
+ if any((child.tail or "").strip() for child in direct_tspans):
245
+ return None
246
+ synthetic_first = ET.Element(f"{{{SVG_NS}}}tspan")
247
+ synthetic_first.set("x", base_x_raw)
248
+ synthetic_first.text = raw_lead.lstrip()
249
+
250
+ view = ([synthetic_first] if synthetic_first is not None else []) + direct_tspans
251
+ return view, synthetic_first
252
+
253
+
254
+ def _get_font_size_px(elem: ET.Element) -> float | None:
255
+ """Read font-size from an attribute or inline style."""
256
+ size = parse_first_number(get_attr(elem, "font-size"))
257
+ if size is not None:
258
+ return size
259
+ style_size = parse_style(get_attr(elem, "style")).get("font-size")
260
+ return parse_first_number(style_size)
261
+
262
+
263
+ def _classify_paragraph_block(
264
+ text_el: ET.Element,
265
+ is_svg_tag,
266
+ is_new_line_tspan,
267
+ ) -> tuple[float, list[float], list[bool], list[list[ET.Element]], ET.Element | None] | None:
268
+ """Detect a mergeable paragraph block.
269
+
270
+ Returns ``(base_line_height_px, extra_space_before_px_per_line,
271
+ is_soft_break_per_line, line_groups, synthetic_first_line)`` if the children
272
+ form a mergeable paragraph. Each list has one entry per direct-child tspan
273
+ (line), including a synthetic first line when the source used leading text:
274
+
275
+ - extra_space_before_px_per_line[i]: extra px above base line-height,
276
+ used as <a:spcBef> on the downstream <a:p>. First entry is 0.
277
+ - is_soft_break_per_line[i]: True if this line should merge into the
278
+ previous <a:p> (SVG dy was simulating word-wrap); False if it starts
279
+ a fresh <a:p>. First entry is always False (paragraph head).
280
+
281
+ Conditions (all must hold):
282
+ - No direct text under <text>, except simple leading text that can be
283
+ promoted into a synthetic first-line <tspan>.
284
+ - Every direct child is a <tspan>.
285
+ - Every logical line starts with a new-line tspan.
286
+ - Direct-child inline formatting tspans without x/y/dy are allowed only
287
+ after a line starts; they are normalized into the previous line.
288
+ - First line-break tspan has dy == 0 (or no dy).
289
+ - All subsequent line-break tspans use positive dy (no <y>).
290
+ - dy values cluster around a single minimum "base line-height";
291
+ any larger dy must be ≤ MAX_DY_MULTIPLIER × base. Anything larger
292
+ is treated as a section break and rejected.
293
+ - Every line-break tspan that sets x repeats the parent <text>'s x.
294
+ - No nested tspan inside any line carries x/y/dy.
295
+ """
296
+ base_x = parse_first_number(get_attr(text_el, "x"))
297
+ child_view = _build_paragraph_child_view(text_el, is_svg_tag)
298
+ if child_view is None:
299
+ return None
300
+ direct_tspans, synthetic_first = child_view
301
+
302
+ if len(direct_tspans) < 2:
303
+ return None
304
+
305
+ line_groups: list[list[ET.Element]] = []
306
+ for tspan in direct_tspans:
307
+ if is_new_line_tspan(tspan):
308
+ line_groups.append([tspan])
309
+ else:
310
+ if not line_groups:
311
+ return None
312
+ if _tspan_has_positional_descendant(tspan):
313
+ return None
314
+ line_groups[-1].append(tspan)
315
+
316
+ if len(line_groups) < 2:
317
+ return None
318
+
319
+ # First pass: validate per-line structural rules and collect dy values.
320
+ dy_values: list[float] = [] # one per line (0 for first)
321
+ for idx, group in enumerate(line_groups):
322
+ tspan = group[0]
323
+
324
+ t_y = get_attr(tspan, "y")
325
+ if t_y is not None:
326
+ return None
327
+
328
+ t_x_raw = get_attr(tspan, "x")
329
+ if t_x_raw is not None:
330
+ t_x = parse_first_number(t_x_raw)
331
+ if base_x is None or t_x is None or abs(t_x - base_x) > 1e-6:
332
+ return None
333
+
334
+ t_dy_raw = get_attr(tspan, "dy")
335
+ t_dy = parse_first_number(t_dy_raw) if t_dy_raw is not None else None
336
+
337
+ if idx == 0:
338
+ if t_dy is not None and abs(t_dy) > 1e-6:
339
+ return None
340
+ dy_values.append(0.0)
341
+ else:
342
+ if t_dy is None or t_dy <= 0:
343
+ return None
344
+ dy_values.append(t_dy)
345
+
346
+ if _tspan_has_positional_descendant(tspan):
347
+ return None
348
+
349
+ # Second pass: pick the base line-height as the minimum positive dy and
350
+ # express each line's dy as base + extra space-before.
351
+ positive_dys = [d for d in dy_values[1:] if d > 0]
352
+ if not positive_dys:
353
+ return None
354
+ base = min(positive_dys)
355
+ font_size = _get_font_size_px(text_el)
356
+ if font_size is not None and base > font_size * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX:
357
+ return None
358
+
359
+ extras: list[float] = [0.0] # first line never has space-before
360
+ soft_breaks: list[bool] = [False] # first line starts a paragraph
361
+ for idx, d in enumerate(dy_values[1:], start=1):
362
+ if d + DY_TOLERANCE_PX < base:
363
+ return None # below base — line overlap, not a paragraph
364
+ if d > base * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX:
365
+ return None # gap too large — treat as section break
366
+ extra = d - base
367
+ if extra < 0:
368
+ extra = 0.0
369
+ # dy at the base line-height = soft break (SVG was simulating wrap);
370
+ # dy strictly greater than base = hard paragraph break. List markers
371
+ # also start a fresh paragraph so bullet/ordered items do not merge
372
+ # into the previous item when exported to PowerPoint.
373
+ is_soft = (
374
+ abs(extra) <= DY_TOLERANCE_PX
375
+ and not _starts_with_list_marker(line_groups[idx])
376
+ )
377
+ extras.append(0.0 if is_soft else extra)
378
+ soft_breaks.append(is_soft)
379
+
380
+ return base, extras, soft_breaks, line_groups, synthetic_first
381
+
382
+
383
+ def _emit_mergeable_paragraph(
384
+ text_el: ET.Element,
385
+ base_dy: float,
386
+ extras: list[float],
387
+ soft_breaks: list[bool],
388
+ line_groups: list[list[ET.Element]],
389
+ synthetic_first: ET.Element | None = None,
390
+ ) -> None:
391
+ """Rewrite text_el in place so it stays a single <text> with paragraph rows.
392
+
393
+ The base line-height goes on the parent <text> via PARAGRAPH_MARK_ATTR.
394
+ Each direct-child tspan is normalized: x/y/dy stripped; inline-run
395
+ styling and nested tspans are preserved. Per-tspan attrs:
396
+ - PARAGRAPH_SOFT_BREAK_ATTR="1" on tspans that should be appended to
397
+ the previous <a:p> downstream (SVG used dy to simulate wrap)
398
+ - PARAGRAPH_SPACE_BEFORE_ATTR on tspans that open a new paragraph
399
+ with an extra gap (omitted when 0)
400
+ """
401
+ text_el.set(PARAGRAPH_MARK_ATTR, format_number(base_dy))
402
+ if synthetic_first is not None:
403
+ text_el.text = None
404
+ text_el.insert(0, synthetic_first)
405
+
406
+ # Normalize authoring variants before the downstream converter reads the
407
+ # paragraph: a line-break tspan may be followed by direct-child inline
408
+ # formatting tspans. Move those inline runs under the line-break tspan so
409
+ # every direct child of <text> is one logical visual line.
410
+ normalized_lines: list[ET.Element] = []
411
+ for group in line_groups:
412
+ line = group[0]
413
+ for inline_tspan in group[1:]:
414
+ try:
415
+ text_el.remove(inline_tspan)
416
+ except ValueError:
417
+ pass
418
+ if inline_tspan.tail and not inline_tspan.tail.strip():
419
+ inline_tspan.tail = None
420
+ line.append(inline_tspan)
421
+ normalized_lines.append(line)
422
+
423
+ for child in list(text_el):
424
+ if child not in normalized_lines:
425
+ text_el.remove(child)
426
+
427
+ extras_iter = iter(extras)
428
+ soft_iter = iter(soft_breaks)
429
+ for tspan in normalized_lines:
430
+ for k in ("x", "y", "dy"):
431
+ if k in tspan.attrib:
432
+ del tspan.attrib[k]
433
+ try:
434
+ extra = next(extras_iter)
435
+ soft = next(soft_iter)
436
+ except StopIteration:
437
+ extra = 0.0
438
+ soft = False
439
+ if soft:
440
+ tspan.set(PARAGRAPH_SOFT_BREAK_ATTR, "1")
441
+ elif extra > 1e-6:
442
+ tspan.set(PARAGRAPH_SPACE_BEFORE_ATTR, format_number(extra))
443
+
444
+
445
+ def flatten_text_with_tspans(
446
+ tree: ET.ElementTree,
447
+ merge_paragraphs: bool = False,
448
+ ) -> bool:
449
+ """Flatten multi-line tspan text into independent text nodes when needed.
450
+
451
+ When `merge_paragraphs` is True, mergeable paragraph blocks (same x,
452
+ dy clustered around one base line-height) are kept as a single <text>
453
+ so downstream conversion emits one editable PowerPoint text frame
454
+ with multiple <a:p>. Default False preserves the original behavior:
455
+ every line-break tspan becomes its own <text>, matching the SVG's
456
+ pixel-fidelity contract.
457
+ """
458
+ root = tree.getroot()
459
+ parent_map = {c: p for p in root.iter() for c in p}
460
+ changed = False
461
+
462
+ def is_svg_tag(el: ET.Element, name: str) -> bool:
463
+ return el.tag == f"{{{SVG_NS}}}{name}"
464
+
465
+ def is_new_line_tspan(tspan: ET.Element) -> bool:
466
+ """Determine whether a tspan represents a new line (has its own y or non-zero dy)."""
467
+ t_dy_attr = get_attr(tspan, "dy")
468
+ t_y_attr = get_attr(tspan, "y")
469
+ t_x_attr = get_attr(tspan, "x")
470
+ dy_val = parse_first_number(t_dy_attr) if t_dy_attr is not None else None
471
+ # Has its own y attribute, or has non-zero dy, or has its own x attribute (indicating a new line)
472
+ if t_y_attr is not None:
473
+ return True
474
+ if dy_val is not None and dy_val != 0:
475
+ return True
476
+ # If tspan has an x attribute and there are preceding sibling tspans, treat it as a new line
477
+ if t_x_attr is not None:
478
+ return True
479
+ return False
480
+
481
+ # Collect candidates first to avoid modifying while iterating
482
+ candidates = []
483
+ for el in root.iter():
484
+ if is_svg_tag(el, "text"):
485
+ has_tspan_child = any(is_svg_tag(c, "tspan") for c in list(el))
486
+ if has_tspan_child:
487
+ candidates.append(el)
488
+
489
+ for text_el in candidates:
490
+ parent = parent_map.get(text_el)
491
+ if parent is None:
492
+ continue
493
+
494
+ # First check whether any tspan needs flattening (dy != 0 or has its own y attribute)
495
+ needs_flatten = False
496
+ for child in list(text_el):
497
+ if not is_svg_tag(child, "tspan"):
498
+ continue
499
+ if is_new_line_tspan(child):
500
+ needs_flatten = True
501
+ break
502
+
503
+ # If no tspan needs a line break, skip the entire text element
504
+ if not needs_flatten:
505
+ continue
506
+
507
+ # Paragraph fast-path (opt-in via merge_paragraphs=True): if the
508
+ # children form a mergeable paragraph (same x, dy clustered around
509
+ # one base line-height with optional paragraph gaps, no nested
510
+ # positional tspans), keep as one <text> and let the downstream
511
+ # converter emit multiple <a:p> runs. When disabled, every tspan
512
+ # gets its own independent <text> so the SVG's exact line layout
513
+ # is preserved in PowerPoint.
514
+ if merge_paragraphs:
515
+ paragraph = _classify_paragraph_block(text_el, is_svg_tag, is_new_line_tspan)
516
+ if paragraph is not None:
517
+ base_dy, extras, soft_breaks, line_groups, synthetic_first = paragraph
518
+ _emit_mergeable_paragraph(
519
+ text_el,
520
+ base_dy,
521
+ extras,
522
+ soft_breaks,
523
+ line_groups,
524
+ synthetic_first=synthetic_first,
525
+ )
526
+ changed = True
527
+ continue
528
+
529
+ base_x = parse_first_number(get_attr(text_el, "x")) or 0.0
530
+ base_y = parse_first_number(get_attr(text_el, "y")) or 0.0
531
+ cur_x, cur_y = base_x, base_y
532
+
533
+ new_texts = []
534
+
535
+ # Collect tspan elements belonging to the same line
536
+ current_line_tspans = []
537
+ current_line_lead_text = None
538
+
539
+ # Leading text directly under <text>
540
+ lead_text = (text_el.text or "").strip()
541
+ if lead_text:
542
+ current_line_lead_text = lead_text
543
+
544
+ for idx, child in enumerate(list(text_el)):
545
+ if not is_svg_tag(child, "tspan"):
546
+ continue
547
+
548
+ content = collect_text_content(child)
549
+
550
+ # Check whether this tspan starts a new line
551
+ if is_new_line_tspan(child):
552
+ # Save previously accumulated same-line tspans first
553
+ if current_line_tspans or current_line_lead_text:
554
+ ne = _create_text_element_from_line(
555
+ text_el, current_line_lead_text, current_line_tspans, cur_x, cur_y
556
+ )
557
+ new_texts.append(ne)
558
+ current_line_tspans = []
559
+ current_line_lead_text = None
560
+
561
+ # Update position
562
+ nx, ny = compute_line_positions(text_el, child, cur_x, cur_y)
563
+ cur_x, cur_y = nx, ny
564
+
565
+ # If content is not empty, add to the current line
566
+ if content.strip():
567
+ current_line_tspans.append(child)
568
+
569
+ # Process the last line
570
+ if current_line_tspans or current_line_lead_text:
571
+ ne = _create_text_element_from_line(
572
+ text_el, current_line_lead_text, current_line_tspans, cur_x, cur_y
573
+ )
574
+ new_texts.append(ne)
575
+
576
+ if new_texts:
577
+ # Replace original <text> with the list of new <text> nodes
578
+ try:
579
+ idx = list(parent).index(text_el)
580
+ except ValueError:
581
+ idx = None
582
+
583
+ # Insert in place to preserve drawing order
584
+ for i, ne in enumerate(new_texts):
585
+ if idx is not None:
586
+ parent.insert(idx + i, ne)
587
+ else:
588
+ parent.append(ne)
589
+
590
+ # Remove the original <text>
591
+ parent.remove(text_el)
592
+ changed = True
593
+
594
+ return changed
595
+
596
+
597
+ def _has_tspan_children(elem: ET.Element) -> bool:
598
+ """Return True if elem contains any nested <tspan> children (inline runs)."""
599
+ return any(c.tag == f"{{{SVG_NS}}}tspan" for c in list(elem))
600
+
601
+
602
+ def _copy_inline_tspan(src: ET.Element, strip_line_attrs: bool) -> ET.Element:
603
+ """Deep-copy a tspan as an inline run, preserving nested tspan structure, head text, and tail text.
604
+
605
+ When strip_line_attrs is True, x/y/dy on the copied tspan are dropped because the
606
+ enclosing <text> now positions the line. dx is preserved (safe inline kerning).
607
+ Nested tspans are copied recursively without stripping (they are already inline-only).
608
+ """
609
+ new = ET.Element(f"{{{SVG_NS}}}tspan")
610
+ for k, v in src.attrib.items():
611
+ if strip_line_attrs and k in ("x", "y", "dy"):
612
+ continue
613
+ new.set(k, v)
614
+ new.text = src.text
615
+ for child in list(src):
616
+ if child.tag == f"{{{SVG_NS}}}tspan":
617
+ new.append(_copy_inline_tspan(child, strip_line_attrs=False))
618
+ new.tail = src.tail
619
+ return new
620
+
621
+
622
+ def _create_text_element_from_line(
623
+ text_el: ET.Element,
624
+ lead_text: str | None,
625
+ tspans: list[ET.Element],
626
+ x: float | None,
627
+ y: float | None,
628
+ ) -> ET.Element:
629
+ """
630
+ Create a text element from a line's content (may contain leading text and multiple tspans).
631
+ If there is only one tspan with no nested tspan children and no leading text, the line
632
+ collapses to a plain <text>...</text>. Otherwise the tspan structure (including any
633
+ nested inline tspans) is preserved so per-run formatting survives the flatten step.
634
+ """
635
+ ne = ET.Element(f"{{{SVG_NS}}}text")
636
+
637
+ # Copy attrs from parent <text>
638
+ copy_text_attrs(text_el, ne, exclude={"x", "y"})
639
+ ne.set("x", format_number(x))
640
+ ne.set("y", format_number(y))
641
+
642
+ # Transform
643
+ p_tf = text_el.get("transform")
644
+ if p_tf:
645
+ ne.set("transform", p_tf)
646
+
647
+ # Compact path: a single tspan with no nested inline runs collapses to <text>text</text>
648
+ if not lead_text and len(tspans) == 1 and not _has_tspan_children(tspans[0]):
649
+ tspan = tspans[0]
650
+ content = collect_text_content(tspan)
651
+
652
+ # Merge style
653
+ merged_style = merge_styles(text_el.get("style"), tspan.get("style"))
654
+ if merged_style:
655
+ ne.set("style", merged_style)
656
+
657
+ # Override specific attributes from tspan
658
+ for attr in TEXT_STYLE_ATTRS:
659
+ cv = tspan.get(attr)
660
+ if cv is not None:
661
+ ne.set(attr, cv)
662
+
663
+ # Combine transform
664
+ c_tf = tspan.get("transform")
665
+ if p_tf and c_tf:
666
+ ne.set("transform", f"{p_tf} {c_tf}")
667
+ elif c_tf:
668
+ ne.set("transform", c_tf)
669
+
670
+ ne.text = content
671
+ else:
672
+ # Preserve tspan structure, including nested inline tspans and tail text
673
+ if lead_text:
674
+ ne.text = lead_text
675
+
676
+ for tspan in tspans:
677
+ ne.append(_copy_inline_tspan(tspan, strip_line_attrs=True))
678
+
679
+ return ne
680
+
681
+
682
+ def process_svg_file(
683
+ src_path: str,
684
+ dst_path: str,
685
+ merge_paragraphs: bool = False,
686
+ ) -> bool:
687
+ """Flatten eligible tspan lines in one SVG file."""
688
+ try:
689
+ tree = ET.parse(src_path)
690
+ except ET.ParseError as e:
691
+ print(f"[WARN] Failed to parse {src_path}: {e}")
692
+ return False
693
+
694
+ changed = flatten_text_with_tspans(tree, merge_paragraphs=merge_paragraphs)
695
+
696
+ # Ensure destination directory exists
697
+ os.makedirs(os.path.dirname(dst_path), exist_ok=True)
698
+
699
+ # Write out XML without XML declaration to mimic input style
700
+ tree.write(dst_path, encoding="utf-8", xml_declaration=False, method="xml")
701
+ return changed
702
+
703
+
704
+ def _compute_default_out_base(inp: str) -> str:
705
+ """Compute default output path for directory or file input."""
706
+ if os.path.isdir(inp):
707
+ # Default: if input ends with svg_output, use sibling svg_output_flattext;
708
+ # otherwise append _flattext to the directory name at the same level.
709
+ head, tail = os.path.split(os.path.normpath(inp))
710
+ if tail == "svg_output":
711
+ return os.path.join(head, "svg_output_flattext")
712
+ return inp.rstrip("/\\") + "_flattext"
713
+ else:
714
+ base, ext = os.path.splitext(inp)
715
+ return base + "_flattext" + ext
716
+
717
+
718
+ def _interactive_get_paths() -> tuple[str | None, str | None]:
719
+ """
720
+ Interactive mode: prompt the user for input path (SVG file or directory)
721
+ and optional output path. Returns (inp, out_base) or (None, None) if cancelled.
722
+ """
723
+ print("[Interactive mode] No arguments provided; running interactively.")
724
+ print("Please enter the path to process (SVG file or directory containing SVGs).")
725
+ print("Enter q to quit.\n")
726
+
727
+ while True:
728
+ raw = input("Input path (file/dir): ").strip()
729
+ if raw.lower() in {"q", "quit", "exit"} or raw == "":
730
+ return None, None
731
+ inp = os.path.expanduser(raw)
732
+ if os.path.exists(inp):
733
+ break
734
+ print("Path does not exist. Please re-enter or enter q to quit.")
735
+
736
+ default_out = _compute_default_out_base(inp)
737
+ if os.path.isdir(inp):
738
+ prompt = f"Output directory [default: {default_out}]: "
739
+ else:
740
+ prompt = f"Output file [default: {default_out}]: "
741
+
742
+ raw_out = input(prompt).strip()
743
+ out_base = os.path.expanduser(raw_out) if raw_out else default_out
744
+
745
+ return inp, out_base
746
+
747
+
748
+ def main() -> None:
749
+ """Run the CLI entry point."""
750
+ # CLI parsing with optional interactive mode
751
+ parser = argparse.ArgumentParser(
752
+ description="Flatten <tspan> lines into multiple <text> nodes for better compatibility.",
753
+ add_help=True,
754
+ )
755
+ parser.add_argument("input", nargs="?", help="Input path: SVG file or directory")
756
+ parser.add_argument("output", nargs="?", help="Optional output file/dir")
757
+ parser.add_argument(
758
+ "-i",
759
+ "--interactive",
760
+ action="store_true",
761
+ help="Run in interactive prompt mode to input paths",
762
+ )
763
+ parser.add_argument(
764
+ "--merge-paragraphs",
765
+ action="store_true",
766
+ default=False,
767
+ help=(
768
+ "Opt-in: merge mergeable paragraph blocks (same x, dy clustered "
769
+ "around one base line-height) into a single <text> annotated for "
770
+ "downstream multi-<a:p> conversion. Default off — every line-break "
771
+ "tspan becomes its own <text>, preserving SVG pixel fidelity."
772
+ ),
773
+ )
774
+
775
+ args = parser.parse_args()
776
+
777
+ if args.interactive or not args.input:
778
+ inp, out_base = _interactive_get_paths()
779
+ if not inp:
780
+ print("Cancelled. Usage: python3 scripts/svg_finalize/flatten_tspan.py <input_dir_or_svg> [output_dir]")
781
+ sys.exit(0)
782
+ else:
783
+ inp = args.input
784
+ out_base = args.output
785
+
786
+ if os.path.isdir(inp):
787
+ # If output base not provided, create a sibling folder named svg_output_flattext for svg_output
788
+ if out_base is None:
789
+ out_base = _compute_default_out_base(inp)
790
+
791
+ total = 0
792
+ changed_count = 0
793
+ out_base_abs = os.path.abspath(out_base)
794
+ for root, dirs, files in os.walk(inp):
795
+ # Avoid recursing into the output directory when it lives under input
796
+ dirs[:] = [d for d in dirs if os.path.abspath(os.path.join(root, d)) != out_base_abs]
797
+ rel_root = os.path.relpath(root, inp)
798
+ for f in files:
799
+ if not f.lower().endswith(".svg"):
800
+ continue
801
+ src = os.path.join(root, f)
802
+ dst = os.path.join(out_base, rel_root, f) if rel_root != "." else os.path.join(out_base, f)
803
+ total += 1
804
+ changed = process_svg_file(src, dst, merge_paragraphs=args.merge_paragraphs)
805
+ if changed:
806
+ changed_count += 1
807
+ print(f"Processed {total} SVG(s). With <tspan> flattened: {changed_count}.")
808
+ print(f"Output written to: {out_base}")
809
+ else:
810
+ src = inp
811
+ if out_base is None:
812
+ out_base = _compute_default_out_base(src)
813
+ changed = process_svg_file(src, out_base, merge_paragraphs=args.merge_paragraphs)
814
+ print(f"Written: {out_base} (flattened: {changed})")
815
+
816
+
817
+ if __name__ == "__main__":
818
+ main()