wezard 2.9.0 → 3.0.2

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 (477) hide show
  1. package/CLAUDE.md +43 -21
  2. package/README.md +37 -50
  3. package/cli/wezard.sh +59 -20
  4. package/config.example.jsonc +5 -8
  5. package/dist/cli/audit.js +11 -13
  6. package/dist/cli/audit.js.map +1 -1
  7. package/dist/cli/codex-hook.js +20 -17
  8. package/dist/cli/codex-hook.js.map +1 -1
  9. package/dist/cli/ext.js +271 -0
  10. package/dist/cli/ext.js.map +1 -0
  11. package/dist/cli/init.js +44 -13
  12. package/dist/cli/init.js.map +1 -1
  13. package/dist/cli/skills.js +113 -0
  14. package/dist/cli/skills.js.map +1 -0
  15. package/dist/cli/sync.js +3 -2
  16. package/dist/cli/sync.js.map +1 -1
  17. package/dist/cli/wx.js +7 -6
  18. package/dist/cli/wx.js.map +1 -1
  19. package/dist/daemon/aibot-media.js +28 -20
  20. package/dist/daemon/aibot-media.js.map +1 -1
  21. package/dist/daemon/apprentice.js +75 -0
  22. package/dist/daemon/apprentice.js.map +1 -0
  23. package/dist/daemon/approval.js +75 -33
  24. package/dist/daemon/approval.js.map +1 -1
  25. package/dist/daemon/channel-context.js +7 -0
  26. package/dist/daemon/channel-context.js.map +1 -1
  27. package/dist/daemon/channel-onboarding.js +61 -0
  28. package/dist/daemon/channel-onboarding.js.map +1 -0
  29. package/dist/daemon/channel-posts.js +93 -0
  30. package/dist/daemon/channel-posts.js.map +1 -0
  31. package/dist/daemon/channel-rebind.js +100 -0
  32. package/dist/daemon/channel-rebind.js.map +1 -0
  33. package/dist/daemon/channel-store.js.map +1 -1
  34. package/dist/daemon/channel.js +273 -409
  35. package/dist/daemon/channel.js.map +1 -1
  36. package/dist/daemon/chat-name.js +24 -161
  37. package/dist/daemon/chat-name.js.map +1 -1
  38. package/dist/daemon/claim.js +1 -45
  39. package/dist/daemon/claim.js.map +1 -1
  40. package/dist/daemon/classes.js +416 -0
  41. package/dist/daemon/classes.js.map +1 -0
  42. package/dist/daemon/config-api.js +6 -30
  43. package/dist/daemon/config-api.js.map +1 -1
  44. package/dist/daemon/control-socket.js +93 -0
  45. package/dist/daemon/control-socket.js.map +1 -0
  46. package/dist/daemon/danger-scrub.js +315 -0
  47. package/dist/daemon/danger-scrub.js.map +1 -0
  48. package/dist/daemon/danger.js +146 -16
  49. package/dist/daemon/danger.js.map +1 -1
  50. package/dist/daemon/detail.js +50 -22
  51. package/dist/daemon/detail.js.map +1 -1
  52. package/dist/daemon/exec-surface.js +108 -0
  53. package/dist/daemon/exec-surface.js.map +1 -0
  54. package/dist/daemon/external.js +595 -0
  55. package/dist/daemon/external.js.map +1 -0
  56. package/dist/daemon/handoff.js +51 -50
  57. package/dist/daemon/handoff.js.map +1 -1
  58. package/dist/daemon/http.js +119 -31
  59. package/dist/daemon/http.js.map +1 -1
  60. package/dist/daemon/idle-reap.js +30 -0
  61. package/dist/daemon/idle-reap.js.map +1 -0
  62. package/dist/daemon/inbound.js +436 -207
  63. package/dist/daemon/inbound.js.map +1 -1
  64. package/dist/daemon/index.js +3353 -2760
  65. package/dist/daemon/index.js.map +1 -1
  66. package/dist/daemon/last-response.js +51 -25
  67. package/dist/daemon/last-response.js.map +1 -1
  68. package/dist/daemon/legacy-panes.js +67 -0
  69. package/dist/daemon/legacy-panes.js.map +1 -0
  70. package/dist/daemon/mcp-http.js.map +1 -1
  71. package/dist/daemon/me-room.js +137 -0
  72. package/dist/daemon/me-room.js.map +1 -0
  73. package/dist/daemon/media.js +14 -0
  74. package/dist/daemon/media.js.map +1 -1
  75. package/dist/daemon/memory-steward.js +1 -1
  76. package/dist/daemon/memory-steward.js.map +1 -1
  77. package/dist/daemon/message-format.js +15 -2
  78. package/dist/daemon/message-format.js.map +1 -1
  79. package/dist/daemon/mirror-bridge.js +583 -488
  80. package/dist/daemon/mirror-bridge.js.map +1 -1
  81. package/dist/daemon/mirror-store.js +24 -0
  82. package/dist/daemon/mirror-store.js.map +1 -1
  83. package/dist/daemon/notices.js +5 -6
  84. package/dist/daemon/notices.js.map +1 -1
  85. package/dist/daemon/onboarding.js +459 -0
  86. package/dist/daemon/onboarding.js.map +1 -0
  87. package/dist/daemon/outbound.js +21 -11
  88. package/dist/daemon/outbound.js.map +1 -1
  89. package/dist/daemon/peers.js +39 -231
  90. package/dist/daemon/peers.js.map +1 -1
  91. package/dist/daemon/plan-http.js +2 -3
  92. package/dist/daemon/plan-http.js.map +1 -1
  93. package/dist/daemon/plans.js.map +1 -1
  94. package/dist/daemon/reach.js +1 -5
  95. package/dist/daemon/reach.js.map +1 -1
  96. package/dist/daemon/room-auto-adhoc.js +18 -0
  97. package/dist/daemon/room-auto-adhoc.js.map +1 -0
  98. package/dist/daemon/room-bind.js +297 -0
  99. package/dist/daemon/room-bind.js.map +1 -0
  100. package/dist/daemon/room-facts.js +35 -0
  101. package/dist/daemon/room-facts.js.map +1 -0
  102. package/dist/daemon/room-hub.js +569 -0
  103. package/dist/daemon/room-hub.js.map +1 -0
  104. package/dist/daemon/room-overdue.js +160 -0
  105. package/dist/daemon/room-overdue.js.map +1 -0
  106. package/dist/daemon/room-prune.js +74 -0
  107. package/dist/daemon/room-prune.js.map +1 -0
  108. package/dist/daemon/room-spawn.js +20 -0
  109. package/dist/daemon/room-spawn.js.map +1 -0
  110. package/dist/daemon/room-watchdog.js +175 -0
  111. package/dist/daemon/room-watchdog.js.map +1 -0
  112. package/dist/daemon/rooms.js +204 -0
  113. package/dist/daemon/rooms.js.map +1 -0
  114. package/dist/daemon/route.js +7 -18
  115. package/dist/daemon/route.js.map +1 -1
  116. package/dist/daemon/session-scan.js +1 -1
  117. package/dist/daemon/session-scan.js.map +1 -1
  118. package/dist/daemon/short-id-log.js +43 -0
  119. package/dist/daemon/short-id-log.js.map +1 -0
  120. package/dist/daemon/spawn-tmux.js +60 -45
  121. package/dist/daemon/spawn-tmux.js.map +1 -1
  122. package/dist/daemon/steward-guard.js +3 -3
  123. package/dist/daemon/steward-guard.js.map +1 -1
  124. package/dist/daemon/steward-model.js +17 -3
  125. package/dist/daemon/steward-model.js.map +1 -1
  126. package/dist/daemon/steward-repair.js +171 -0
  127. package/dist/daemon/steward-repair.js.map +1 -0
  128. package/dist/daemon/steward.js +171 -0
  129. package/dist/daemon/steward.js.map +1 -0
  130. package/dist/daemon/tasks.js +4 -14
  131. package/dist/daemon/tasks.js.map +1 -1
  132. package/dist/daemon/tool-face.js +31 -0
  133. package/dist/daemon/tool-face.js.map +1 -0
  134. package/dist/daemon/turn-opening.js +30 -0
  135. package/dist/daemon/turn-opening.js.map +1 -0
  136. package/dist/daemon/wake-tail.js +55 -0
  137. package/dist/daemon/wake-tail.js.map +1 -0
  138. package/dist/daemon/weixin-cmd.js +10 -14
  139. package/dist/daemon/weixin-cmd.js.map +1 -1
  140. package/dist/daemon/wezard-session.js +6 -2
  141. package/dist/daemon/wezard-session.js.map +1 -1
  142. package/dist/daemon/wizard-memory.js +4 -10
  143. package/dist/daemon/wizard-memory.js.map +1 -1
  144. package/dist/daemon/wizard-names.js +0 -22
  145. package/dist/daemon/wizard-names.js.map +1 -1
  146. package/dist/daemon/wizard.js +683 -159
  147. package/dist/daemon/wizard.js.map +1 -1
  148. package/dist/daemon/ws.js +1 -1
  149. package/dist/daemon/ws.js.map +1 -1
  150. package/dist/mcp/output.js +30 -7
  151. package/dist/mcp/output.js.map +1 -1
  152. package/dist/mcp/relay.js +152 -0
  153. package/dist/mcp/relay.js.map +1 -0
  154. package/dist/mcp/tools.js +318 -265
  155. package/dist/mcp/tools.js.map +1 -1
  156. package/dist/shared/allow-rules.js +1 -7
  157. package/dist/shared/allow-rules.js.map +1 -1
  158. package/dist/shared/charter-rearm.js +179 -0
  159. package/dist/shared/charter-rearm.js.map +1 -0
  160. package/dist/shared/chat-http.js +412 -480
  161. package/dist/shared/chat-http.js.map +1 -1
  162. package/dist/shared/chat-record.js +55 -0
  163. package/dist/shared/chat-record.js.map +1 -0
  164. package/dist/shared/chat-render.js +7 -4
  165. package/dist/shared/chat-render.js.map +1 -1
  166. package/dist/shared/chat-view.js +2 -41
  167. package/dist/shared/chat-view.js.map +1 -1
  168. package/dist/shared/cli-backends.js +13 -5
  169. package/dist/shared/cli-backends.js.map +1 -1
  170. package/dist/shared/cli-local-status.js +28 -0
  171. package/dist/shared/cli-local-status.js.map +1 -0
  172. package/dist/shared/cli-socket.js +14 -0
  173. package/dist/shared/cli-socket.js.map +1 -0
  174. package/dist/shared/codex-hooks.js +5 -2
  175. package/dist/shared/codex-hooks.js.map +1 -1
  176. package/dist/shared/config.js +90 -66
  177. package/dist/shared/config.js.map +1 -1
  178. package/dist/shared/daemon-addr.js +23 -0
  179. package/dist/shared/daemon-addr.js.map +1 -0
  180. package/dist/shared/daemon-client.js +41 -0
  181. package/dist/shared/daemon-client.js.map +1 -0
  182. package/dist/shared/daemon-token.js +2 -2
  183. package/dist/shared/daemon-token.js.map +1 -1
  184. package/dist/shared/detail-render.js +98 -21
  185. package/dist/shared/detail-render.js.map +1 -1
  186. package/dist/shared/detail-store.js.map +1 -1
  187. package/dist/shared/external.js +402 -0
  188. package/dist/shared/external.js.map +1 -0
  189. package/dist/shared/group-members.js +35 -0
  190. package/dist/shared/group-members.js.map +1 -0
  191. package/dist/shared/inject-view.js +143 -0
  192. package/dist/shared/inject-view.js.map +1 -0
  193. package/dist/shared/instance-id.js +21 -0
  194. package/dist/shared/instance-id.js.map +1 -0
  195. package/dist/shared/legacy-routes.js +199 -0
  196. package/dist/shared/legacy-routes.js.map +1 -0
  197. package/dist/shared/mem-guard.js +32 -0
  198. package/dist/shared/mem-guard.js.map +1 -0
  199. package/dist/shared/message-footer.js +11 -3
  200. package/dist/shared/message-footer.js.map +1 -1
  201. package/dist/shared/model-tiers.js +39 -1
  202. package/dist/shared/model-tiers.js.map +1 -1
  203. package/dist/shared/ports.js +56 -0
  204. package/dist/shared/ports.js.map +1 -0
  205. package/dist/shared/reminder.js +30 -38
  206. package/dist/shared/reminder.js.map +1 -1
  207. package/dist/shared/role-render.js +210 -210
  208. package/dist/shared/role-render.js.map +1 -1
  209. package/dist/shared/role-view.js +65 -300
  210. package/dist/shared/role-view.js.map +1 -1
  211. package/dist/shared/room-label.js +13 -0
  212. package/dist/shared/room-label.js.map +1 -0
  213. package/dist/shared/room-migrate.js +404 -0
  214. package/dist/shared/room-migrate.js.map +1 -0
  215. package/dist/shared/room-overdue.js +153 -0
  216. package/dist/shared/room-overdue.js.map +1 -0
  217. package/dist/shared/room-search.js +102 -0
  218. package/dist/shared/room-search.js.map +1 -0
  219. package/dist/shared/room-view.js +275 -0
  220. package/dist/shared/room-view.js.map +1 -0
  221. package/dist/shared/room.js +827 -0
  222. package/dist/shared/room.js.map +1 -0
  223. package/dist/shared/session-hooks.js +20 -8
  224. package/dist/shared/session-hooks.js.map +1 -1
  225. package/dist/shared/session-label.js +82 -84
  226. package/dist/shared/session-label.js.map +1 -1
  227. package/dist/shared/session-mcp.js +36 -40
  228. package/dist/shared/session-mcp.js.map +1 -1
  229. package/dist/shared/session-skills.js +8 -0
  230. package/dist/shared/session-skills.js.map +1 -1
  231. package/dist/shared/skill-sync.js +229 -0
  232. package/dist/shared/skill-sync.js.map +1 -0
  233. package/dist/shared/smarts.js +24 -0
  234. package/dist/shared/smarts.js.map +1 -0
  235. package/dist/shared/stream-page.js +22 -0
  236. package/dist/shared/stream-page.js.map +1 -0
  237. package/dist/shared/task-file.js +0 -5
  238. package/dist/shared/task-file.js.map +1 -1
  239. package/dist/shared/task-template.js +1 -1
  240. package/dist/shared/task-template.js.map +1 -1
  241. package/dist/shared/tool-hints.js +20 -11
  242. package/dist/shared/tool-hints.js.map +1 -1
  243. package/dist/shared/workspace-trust.js +8 -0
  244. package/dist/shared/workspace-trust.js.map +1 -1
  245. package/dist/shared/world.js +101 -166
  246. package/dist/shared/world.js.map +1 -1
  247. package/dist/svr/facts-store.js +26 -0
  248. package/dist/svr/facts-store.js.map +1 -0
  249. package/dist/svr/index.js +114 -16
  250. package/dist/svr/index.js.map +1 -1
  251. package/hooks/pre-tool-use.sh +14 -10
  252. package/hooks/stop.sh +28 -0
  253. package/launchd/com.wezard.svr.plist.template +2 -0
  254. package/package.json +9 -2
  255. package/scripts/install.sh +23 -0
  256. package/skills/LICENSE.wecom-unified.txt +21 -0
  257. package/skills/wecom-unified/SKILL.md +151 -0
  258. package/skills/wecom-unified/assets/templates/broadside/DESIGN.preset.md +172 -0
  259. package/skills/wecom-unified/assets/templates/broadside/shell/content.jsx +31 -0
  260. package/skills/wecom-unified/assets/templates/broadside/slides/01_cover.slide +48 -0
  261. package/skills/wecom-unified/assets/templates/broadside/slides/02_section.slide +58 -0
  262. package/skills/wecom-unified/assets/templates/broadside/slides/03_cards.slide +53 -0
  263. package/skills/wecom-unified/assets/templates/broadside/slides/04_image.slide +64 -0
  264. package/skills/wecom-unified/assets/templates/cartesian/DESIGN.preset.md +139 -0
  265. package/skills/wecom-unified/assets/templates/cartesian/shell/content.jsx +28 -0
  266. package/skills/wecom-unified/assets/templates/cartesian/slides/01_cover.slide +44 -0
  267. package/skills/wecom-unified/assets/templates/cartesian/slides/02_compare.slide +79 -0
  268. package/skills/wecom-unified/assets/templates/cartesian/slides/03_table.slide +79 -0
  269. package/skills/wecom-unified/assets/templates/cobalt-grid/DESIGN.preset.md +118 -0
  270. package/skills/wecom-unified/assets/templates/cobalt-grid/shell/content.jsx +24 -0
  271. package/skills/wecom-unified/assets/templates/cobalt-grid/slides/01_cover.slide +61 -0
  272. package/skills/wecom-unified/assets/templates/cobalt-grid/slides/02_structure.slide +85 -0
  273. package/skills/wecom-unified/assets/templates/cobalt-grid/slides/03_data.slide +60 -0
  274. package/skills/wecom-unified/assets/templates/editorial-forest/DESIGN.preset.md +135 -0
  275. package/skills/wecom-unified/assets/templates/editorial-forest/shell/content.jsx +19 -0
  276. package/skills/wecom-unified/assets/templates/editorial-forest/slides/01_cover.slide +29 -0
  277. package/skills/wecom-unified/assets/templates/editorial-forest/slides/02_cards.slide +60 -0
  278. package/skills/wecom-unified/assets/templates/editorial-forest/slides/03_data.slide +49 -0
  279. package/skills/wecom-unified/assets/templates/editorial-forest/slides/04_image.slide +46 -0
  280. package/skills/wecom-unified/assets/templates/emerald-editorial/DESIGN.preset.md +119 -0
  281. package/skills/wecom-unified/assets/templates/emerald-editorial/shell/content.jsx +18 -0
  282. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/01_cover.slide +36 -0
  283. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/02_section.slide +39 -0
  284. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/03_data.slide +79 -0
  285. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/04_steps.slide +53 -0
  286. package/skills/wecom-unified/assets/templates/grove/DESIGN.preset.md +159 -0
  287. package/skills/wecom-unified/assets/templates/grove/shell/content.jsx +18 -0
  288. package/skills/wecom-unified/assets/templates/grove/shell/content_light.jsx +18 -0
  289. package/skills/wecom-unified/assets/templates/grove/slides/01_cover.slide +26 -0
  290. package/skills/wecom-unified/assets/templates/grove/slides/02_compare.slide +92 -0
  291. package/skills/wecom-unified/assets/templates/grove/slides/03_table.slide +68 -0
  292. package/skills/wecom-unified/assets/templates/index.json +280 -0
  293. package/skills/wecom-unified/assets/templates/long-table/DESIGN.preset.md +135 -0
  294. package/skills/wecom-unified/assets/templates/long-table/shell/content.jsx +36 -0
  295. package/skills/wecom-unified/assets/templates/long-table/slides/01_cover.slide +71 -0
  296. package/skills/wecom-unified/assets/templates/long-table/slides/02_cards.slide +72 -0
  297. package/skills/wecom-unified/assets/templates/long-table/slides/03_timeline.slide +81 -0
  298. package/skills/wecom-unified/assets/templates/long-table/slides/04_image.slide +60 -0
  299. package/skills/wecom-unified/assets/templates/sakura-chroma/DESIGN.preset.md +121 -0
  300. package/skills/wecom-unified/assets/templates/sakura-chroma/shell/content.jsx +13 -0
  301. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/01_cover.slide +54 -0
  302. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/02_products.slide +134 -0
  303. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/03_section.slide +30 -0
  304. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/04_schedule.slide +65 -0
  305. package/skills/wecom-unified/assets/templates/signal/DESIGN.preset.md +121 -0
  306. package/skills/wecom-unified/assets/templates/signal/shell/content.jsx +18 -0
  307. package/skills/wecom-unified/assets/templates/signal/shell/content_dark.jsx +23 -0
  308. package/skills/wecom-unified/assets/templates/signal/slides/01_cover.slide +48 -0
  309. package/skills/wecom-unified/assets/templates/signal/slides/02_cards.slide +67 -0
  310. package/skills/wecom-unified/assets/templates/signal/slides/03_data.slide +68 -0
  311. package/skills/wecom-unified/references/wecomcli-calendar-agenda.md +227 -0
  312. package/skills/wecom-unified/references/wecomcli-calendar-cancel.md +108 -0
  313. package/skills/wecom-unified/references/wecomcli-calendar-create.md +238 -0
  314. package/skills/wecom-unified/references/wecomcli-calendar-freebusy.md +207 -0
  315. package/skills/wecom-unified/references/wecomcli-calendar-meeting-room.md +170 -0
  316. package/skills/wecom-unified/references/wecomcli-calendar-search.md +209 -0
  317. package/skills/wecom-unified/references/wecomcli-calendar-update.md +272 -0
  318. package/skills/wecom-unified/references/wecomcli-calendar.md +296 -0
  319. package/skills/wecom-unified/references/wecomcli-contact.md +48 -0
  320. package/skills/wecom-unified/references/wecomcli-disk.md +380 -0
  321. package/skills/wecom-unified/references/wecomcli-doc-contents-append.md +20 -0
  322. package/skills/wecom-unified/references/wecomcli-doc-contents-overwrite.md +27 -0
  323. package/skills/wecom-unified/references/wecomcli-doc-create.md +162 -0
  324. package/skills/wecom-unified/references/wecomcli-doc-manage-doc-members-update.md +24 -0
  325. package/skills/wecom-unified/references/wecomcli-doc-manage-doc-names-update.md +20 -0
  326. package/skills/wecom-unified/references/wecomcli-doc-manage-doc-rules-update.md +22 -0
  327. package/skills/wecom-unified/references/wecomcli-doc-manage.md +127 -0
  328. package/skills/wecom-unified/references/wecomcli-doc.md +135 -0
  329. package/skills/wecom-unified/references/wecomcli-email-forward-mail.md +131 -0
  330. package/skills/wecom-unified/references/wecomcli-email-get-mail.md +187 -0
  331. package/skills/wecom-unified/references/wecomcli-email-reply-mail.md +138 -0
  332. package/skills/wecom-unified/references/wecomcli-email-search-mail.md +114 -0
  333. package/skills/wecom-unified/references/wecomcli-email-security.md +52 -0
  334. package/skills/wecom-unified/references/wecomcli-email-send-mail.md +186 -0
  335. package/skills/wecom-unified/references/wecomcli-email-send-schedule.md +83 -0
  336. package/skills/wecom-unified/references/wecomcli-email.md +206 -0
  337. package/skills/wecom-unified/references/wecomcli-media.md +89 -0
  338. package/skills/wecom-unified/references/wecomcli-meeting-cancel.md +113 -0
  339. package/skills/wecom-unified/references/wecomcli-meeting-create.md +167 -0
  340. package/skills/wecom-unified/references/wecomcli-meeting-list.md +228 -0
  341. package/skills/wecom-unified/references/wecomcli-meeting-original-get.md +101 -0
  342. package/skills/wecom-unified/references/wecomcli-meeting-search.md +176 -0
  343. package/skills/wecom-unified/references/wecomcli-meeting-update.md +217 -0
  344. package/skills/wecom-unified/references/wecomcli-meeting.md +366 -0
  345. package/skills/wecom-unified/references/wecomcli-message.md +190 -0
  346. package/skills/wecom-unified/references/wecomcli-pptx-component-animation.md +62 -0
  347. package/skills/wecom-unified/references/wecomcli-pptx-component-box.md +102 -0
  348. package/skills/wecom-unified/references/wecomcli-pptx-component-chart.md +261 -0
  349. package/skills/wecom-unified/references/wecomcli-pptx-component-codeblock.md +70 -0
  350. package/skills/wecom-unified/references/wecomcli-pptx-component-diagram.md +54 -0
  351. package/skills/wecom-unified/references/wecomcli-pptx-component-faicon.md +71 -0
  352. package/skills/wecom-unified/references/wecomcli-pptx-component-hyperlink.md +55 -0
  353. package/skills/wecom-unified/references/wecomcli-pptx-component-image.md +107 -0
  354. package/skills/wecom-unified/references/wecomcli-pptx-component-math.md +65 -0
  355. package/skills/wecom-unified/references/wecomcli-pptx-component-qrcode.md +22 -0
  356. package/skills/wecom-unified/references/wecomcli-pptx-component-slide.md +74 -0
  357. package/skills/wecom-unified/references/wecomcli-pptx-component-svg.md +95 -0
  358. package/skills/wecom-unified/references/wecomcli-pptx-component-table.md +72 -0
  359. package/skills/wecom-unified/references/wecomcli-pptx-component-text.md +96 -0
  360. package/skills/wecom-unified/references/wecomcli-pptx-content-contract.md +73 -0
  361. package/skills/wecom-unified/references/wecomcli-pptx-create-from-material.md +67 -0
  362. package/skills/wecom-unified/references/wecomcli-pptx-create-from-scratch.md +178 -0
  363. package/skills/wecom-unified/references/wecomcli-pptx-create-from-template.md +123 -0
  364. package/skills/wecom-unified/references/wecomcli-pptx-design-principle.md +65 -0
  365. package/skills/wecom-unified/references/wecomcli-pptx-government-contract.md +40 -0
  366. package/skills/wecom-unified/references/wecomcli-pptx-human-alignment.md +140 -0
  367. package/skills/wecom-unified/references/wecomcli-pptx-pptx-api.md +161 -0
  368. package/skills/wecom-unified/references/wecomcli-pptx-pptx-edit.md +37 -0
  369. package/skills/wecom-unified/references/wecomcli-pptx-story-principle.md +184 -0
  370. package/skills/wecom-unified/references/wecomcli-pptx-templates-README.md +165 -0
  371. package/skills/wecom-unified/references/wecomcli-pptx-templates-anti-ai-slop.md +52 -0
  372. package/skills/wecom-unified/references/wecomcli-pptx.md +158 -0
  373. package/skills/wecom-unified/references/wecomcli-sheet-conditional-formatting.md +203 -0
  374. package/skills/wecom-unified/references/wecomcli-sheet-filter.md +179 -0
  375. package/skills/wecom-unified/references/wecomcli-sheet-float-image.md +235 -0
  376. package/skills/wecom-unified/references/wecomcli-sheet-formulas.md +71 -0
  377. package/skills/wecom-unified/references/wecomcli-sheet-history.md +118 -0
  378. package/skills/wecom-unified/references/wecomcli-sheet-protection.md +170 -0
  379. package/skills/wecom-unified/references/wecomcli-sheet-range-operations.md +306 -0
  380. package/skills/wecom-unified/references/wecomcli-sheet-read-data.md +151 -0
  381. package/skills/wecom-unified/references/wecomcli-sheet-search-replace.md +121 -0
  382. package/skills/wecom-unified/references/wecomcli-sheet-structure-operations.md +394 -0
  383. package/skills/wecom-unified/references/wecomcli-sheet-style.md +246 -0
  384. package/skills/wecom-unified/references/wecomcli-sheet-table-style.md +199 -0
  385. package/skills/wecom-unified/references/wecomcli-sheet-validation.md +217 -0
  386. package/skills/wecom-unified/references/wecomcli-sheet-visual-standards.md +166 -0
  387. package/skills/wecom-unified/references/wecomcli-sheet-workbook.md +264 -0
  388. package/skills/wecom-unified/references/wecomcli-sheet-write-cells.md +320 -0
  389. package/skills/wecom-unified/references/wecomcli-sheet-xlsx-process.md +324 -0
  390. package/skills/wecom-unified/references/wecomcli-sheet.md +96 -0
  391. package/skills/wecom-unified/references/wecomcli-smartpage-data-driven-pages.md +50 -0
  392. package/skills/wecom-unified/references/wecomcli-smartpage-edit.md +526 -0
  393. package/skills/wecom-unified/references/wecomcli-smartpage-formula-arraylist.md +369 -0
  394. package/skills/wecom-unified/references/wecomcli-smartpage-formula-datetime.md +283 -0
  395. package/skills/wecom-unified/references/wecomcli-smartpage-formula-logic.md +247 -0
  396. package/skills/wecom-unified/references/wecomcli-smartpage-formula-math.md +362 -0
  397. package/skills/wecom-unified/references/wecomcli-smartpage-formula-operators.md +246 -0
  398. package/skills/wecom-unified/references/wecomcli-smartpage-formula-pageblock.md +76 -0
  399. package/skills/wecom-unified/references/wecomcli-smartpage-formula-reference.md +192 -0
  400. package/skills/wecom-unified/references/wecomcli-smartpage-formula-templates.md +410 -0
  401. package/skills/wecom-unified/references/wecomcli-smartpage-formula-text.md +377 -0
  402. package/skills/wecom-unified/references/wecomcli-smartpage-formula-user.md +22 -0
  403. package/skills/wecom-unified/references/wecomcli-smartpage-mdx-syntax.md +739 -0
  404. package/skills/wecom-unified/references/wecomcli-smartpage.md +179 -0
  405. package/skills/wecom-unified/references/wecomcli-smartsheet-chart-types.md +95 -0
  406. package/skills/wecom-unified/references/wecomcli-smartsheet-common.md +160 -0
  407. package/skills/wecom-unified/references/wecomcli-smartsheet-edit.md +609 -0
  408. package/skills/wecom-unified/references/wecomcli-smartsheet-field-types.md +438 -0
  409. package/skills/wecom-unified/references/wecomcli-smartsheet-formula.md +845 -0
  410. package/skills/wecom-unified/references/wecomcli-smartsheet-read.md +411 -0
  411. package/skills/wecom-unified/references/wecomcli-smartsheet-record-values.md +218 -0
  412. package/skills/wecom-unified/references/wecomcli-smartsheet-template-ai_efficiency.md +709 -0
  413. package/skills/wecom-unified/references/wecomcli-smartsheet-template-connect_to_app.md +380 -0
  414. package/skills/wecom-unified/references/wecomcli-smartsheet-template-financial_accounting.md +369 -0
  415. package/skills/wecom-unified/references/wecomcli-smartsheet-template-hr_and_administration.md +475 -0
  416. package/skills/wecom-unified/references/wecomcli-smartsheet-template-ledger_records.md +156 -0
  417. package/skills/wecom-unified/references/wecomcli-smartsheet-template-manufacturing.md +395 -0
  418. package/skills/wecom-unified/references/wecomcli-smartsheet-template-marketing.md +186 -0
  419. package/skills/wecom-unified/references/wecomcli-smartsheet-template-office_essentials.md +299 -0
  420. package/skills/wecom-unified/references/wecomcli-smartsheet-template-personal_efficiency.md +70 -0
  421. package/skills/wecom-unified/references/wecomcli-smartsheet-template-procurement_logistics.md +325 -0
  422. package/skills/wecom-unified/references/wecomcli-smartsheet-template-project_management.md +564 -0
  423. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_customer.md +222 -0
  424. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_ops.md +105 -0
  425. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_project.md +109 -0
  426. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_research.md +92 -0
  427. package/skills/wecom-unified/references/wecomcli-smartsheet-template-sales_and_operations.md +446 -0
  428. package/skills/wecom-unified/references/wecomcli-smartsheet-template-store_management.md +431 -0
  429. package/skills/wecom-unified/references/wecomcli-smartsheet-template-team_tasks.md +274 -0
  430. package/skills/wecom-unified/references/wecomcli-smartsheet-template-wechat_customer.md +384 -0
  431. package/skills/wecom-unified/references/wecomcli-smartsheet-template-work_report.md +100 -0
  432. package/skills/wecom-unified/references/wecomcli-smartsheet-templates.md +53 -0
  433. package/skills/wecom-unified/references/wecomcli-smartsheet-view-types.md +373 -0
  434. package/skills/wecom-unified/references/wecomcli-smartsheet-webhook-examples.md +176 -0
  435. package/skills/wecom-unified/references/wecomcli-smartsheet-webhook.md +186 -0
  436. package/skills/wecom-unified/references/wecomcli-smartsheet.md +147 -0
  437. package/skills/wecom-unified/references/wecomcli-todo-create.md +137 -0
  438. package/skills/wecom-unified/references/wecomcli-todo-delete.md +63 -0
  439. package/skills/wecom-unified/references/wecomcli-todo-finish.md +72 -0
  440. package/skills/wecom-unified/references/wecomcli-todo-get.md +69 -0
  441. package/skills/wecom-unified/references/wecomcli-todo-list.md +136 -0
  442. package/skills/wecom-unified/references/wecomcli-todo-update.md +112 -0
  443. package/skills/wecom-unified/references/wecomcli-todo.md +68 -0
  444. package/skills/wecom-unified/scripts/build_docx.py +1274 -0
  445. package/skills/wecom-unified/scripts/build_page.py +2449 -0
  446. package/skills/wecom-unified/scripts/collect.py +868 -0
  447. package/skills/wecom-unified/scripts/doc_image_extractor.py +498 -0
  448. package/skills/wecom-unified/scripts/pptx2image.py +268 -0
  449. package/skills/wecom-unified/scripts/recalc.py +403 -0
  450. package/systemd/wezard-svr.service.template +2 -0
  451. package/systemd/wezard.service.template +6 -0
  452. package/web/chat.css +70 -273
  453. package/web/chat.js +2269 -2190
  454. package/dist/daemon/bot-mux.js +0 -161
  455. package/dist/daemon/bot-mux.js.map +0 -1
  456. package/dist/daemon/chat-log.js +0 -130
  457. package/dist/daemon/chat-log.js.map +0 -1
  458. package/dist/daemon/dispatch.js +0 -6
  459. package/dist/daemon/dispatch.js.map +0 -1
  460. package/dist/daemon/idle-nudge.js +0 -90
  461. package/dist/daemon/idle-nudge.js.map +0 -1
  462. package/dist/daemon/message-events.js +0 -1155
  463. package/dist/daemon/message-events.js.map +0 -1
  464. package/dist/daemon/pending-items.js +0 -160
  465. package/dist/daemon/pending-items.js.map +0 -1
  466. package/dist/daemon/router.js +0 -742
  467. package/dist/daemon/router.js.map +0 -1
  468. package/dist/daemon/tips.js +0 -25
  469. package/dist/daemon/tips.js.map +0 -1
  470. package/dist/daemon/wedoc.js +0 -210
  471. package/dist/daemon/wedoc.js.map +0 -1
  472. package/dist/shared/role-search.js +0 -100
  473. package/dist/shared/role-search.js.map +0 -1
  474. package/dist/shared/startup-notice.js +0 -21
  475. package/dist/shared/startup-notice.js.map +0 -1
  476. package/dist/shared/turn-state.js +0 -27
  477. package/dist/shared/turn-state.js.map +0 -1
@@ -0,0 +1,2449 @@
1
+ #!/usr/bin/env python3
2
+ """Assemble slide pages from a fixed shell.
3
+
4
+ init: python3 build_page.py init --set signal [--map colors.json] (copy shells + template pages + preset into cwd, recoloured)
5
+ template: python3 build_page.py template <user.pptx> then template --docid <docid> (shells built FROM a user's PPT template)
6
+ buildall: python3 build_page.py buildall (build every NN_body.jsx, then contrast + images, one command)
7
+
8
+ Older single-step commands: so the header, footer, rules and page padding never drift.
9
+
10
+ build: python3 build_page.py build --shell 00_shell.jsx --body 05_body.jsx --vars 05_vars.json [--manifest images.json] --out 05_market.jsx
11
+ check: python3 build_page.py check --shell 00_shell.jsx 03_x.jsx 04_y.jsx ...
12
+ recolor: python3 build_page.py recolor --map colors.json --out-dir local/ shell/content.jsx slides/*.slide (swap a set's palette)
13
+ contrast: python3 build_page.py contrast 01_cover.jsx 02_x.jsx ... (text vs. the surface it sits on)
14
+ fit: python3 build_page.py fit 01_cover.jsx 02_x.jsx ... (does the text fit its box; absolute text landing on other text; Slide must be 1280x720)
15
+ imgfit: python3 build_page.py imgfit --slot 576x434 --actual 1024x1024 --src <url> [--bg #DCEBFD] (prints the Image JSX)
16
+ images: python3 build_page.py images --manifest images.json 04_x.jsx ... (written size vs. real aspect ratio)
17
+
18
+ The shell is a copy of templates/<slug>/shell/content.jsx. Placeholders look like 〔标题〕; 〔B区内容〕 is
19
+ where the page body goes. Values are inserted as-is, so they may contain <br /> or <span> markup. Pass "" to leave a
20
+ placeholder empty on purpose. `check` verifies that every page is the shell with only the placeholders filled in.
21
+ """
22
+ import argparse, json, re, sys
23
+
24
+ BODY = '〔B区内容〕'
25
+ PH = re.compile(r'〔[^〔〕]*〕')
26
+
27
+ def build(a):
28
+ shell = open(a.shell, encoding='utf-8').read()
29
+ body = open(a.body, encoding='utf-8').read().strip('\n')
30
+ values = json.load(open(a.vars, encoding='utf-8')) if a.vars else {}
31
+ values = {(k[1:-1] if k.startswith('〔') and k.endswith('〕') else k): v for k, v in values.items()} # "〔标题〕" keys too
32
+ if BODY not in shell and body.strip(): sys.exit(f'shell has no {BODY} marker: {a.shell} -- this page type takes no body: leave its body file empty')
33
+ missing = []
34
+ def fill(m):
35
+ key = m.group(0)[1:-1]
36
+ if m.group(0) == BODY: return m.group(0)
37
+ if key in values: return str(values[key])
38
+ missing.append(key); return m.group(0)
39
+ page = PH.sub(fill, shell)
40
+ if missing:
41
+ allkeys = [k[1:-1] for k in dict.fromkeys(PH.findall(shell)) if k != BODY]
42
+ ready = json.dumps({k: '' for k in allkeys}, ensure_ascii=False, indent=1)
43
+ shellname = a.shell.replace('\\', '/').rsplit('/', 1)[-1]
44
+ sys.exit('missing values for: ' + ', '.join(sorted(set(missing))) +
45
+ f'\nthese are placeholders that the shell {shellname} needs -- its header, page number, footer'
46
+ '\nand lead-in question live in the shell, not in the body, so every page needs its own vars file.'
47
+ f'\nadd them to {a.vars or "--vars"} (use "" to leave one empty). Full set of keys for this shell:\n'
48
+ + ready)
49
+ if BODY in page:
50
+ indent = re.search(r'^([ \t]*)' + re.escape(BODY), page, re.M).group(1)
51
+ page = page.replace(indent + BODY, '\n'.join(indent + ln if ln.strip() else ln for ln in body.split('\n')), 1)
52
+ if 'tpl_assets/' in page: # art of a user template: urls come from `template --docid`
53
+ import os
54
+ up = os.path.join(os.path.dirname(os.path.abspath(a.shell)), 'tpl_urls.json')
55
+ for rel, url in (json.load(open(up, encoding='utf-8')).items() if os.path.exists(up) else []):
56
+ page = page.replace(f'"{rel}"', f'"{url}"')
57
+ if 'tpl_assets/' in page:
58
+ sys.exit('template art not uploaded yet (' + ', '.join(sorted(set(re.findall(r'tpl_assets/[\w.\-]+', page)))) +
59
+ ') -> run `template --docid <docid>` once after the document exists, then rerun buildall')
60
+ if '<Image' in page:
61
+ if not a.manifest: sys.exit('page contains <Image>: pass --manifest images.json (real sizes recorded in Step6) so the picture cannot be squashed')
62
+ issues = _image_issues(page, json.load(open(a.manifest, encoding='utf-8')))
63
+ if issues: sys.exit('image would be squashed, page not written:\n ' + '\n '.join(issues) + '\nrun imgfit with the real size and paste its output into the body')
64
+ open(a.out, 'w', encoding='utf-8').write(page if page.endswith('\n') else page + '\n')
65
+ print(f'ok {a.out}')
66
+
67
+ def shell_regex(shell):
68
+ parts, pos = [], 0
69
+ for m in PH.finditer(shell):
70
+ parts.append(re.escape(shell[pos:m.start()]))
71
+ parts.append(r'[\s\S]*?' if m.group(0) == BODY else r'(?:(?!</?Box|</?Slide|<Image|<Chart|<Table|<svg)[\s\S])*?')
72
+ pos = m.end()
73
+ parts.append(re.escape(shell[pos:]))
74
+ rx = ''.join(parts)
75
+ return re.compile(r'\s*' + re.sub(r'(\\\s|\\\n|\\ )+', r'\\s*', rx) + r'\s*')
76
+
77
+ def check(a):
78
+ shell = open(a.shell, encoding='utf-8').read().strip()
79
+ rx, bad = shell_regex(shell), 0
80
+ for p in a.pages:
81
+ src = open(p, encoding='utf-8').read()
82
+ if rx.fullmatch(src): print(f'OK {p}'); continue
83
+ bad += 1; print(f'DRIFT {p}')
84
+ fixed = [ln.strip() for ln in PH.sub('\0', shell).split('\n') if ln.strip() and '\0' not in ln]
85
+ gone = [ln for ln in fixed if ln not in src]
86
+ for ln in gone[:6]: print(' shell line not found verbatim: ' + ln[:110])
87
+ if not gone: print(' every fixed line is present, but order or placeholder lines differ from the shell')
88
+ sys.exit(1 if bad else 0)
89
+
90
+ HEX = re.compile(r"#([0-9A-Fa-f]{6})\b")
91
+ def _lum(h):
92
+ c = [int(h[i:i+2], 16) / 255 for i in (0, 2, 4)]
93
+ c = [x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4 for x in c]
94
+ return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
95
+ def _ratio(a, b):
96
+ la, lb = sorted((_lum(a), _lum(b)), reverse=True); return (la + 0.05) / (lb + 0.05)
97
+
98
+ _TAG = re.compile(r"<(/?)(Slide|Box|Text|span)\b((?:[^<>]|=>)*?)(/?)>", re.S)
99
+
100
+ def _contrast_hits(src):
101
+ """Every text/surface pair in one page source that is under its threshold, as
102
+ (line, text hex, surface hex, font size, ratio, needed, 'FAIL' | 'warn')."""
103
+ stack, size, hits = ['FFFFFF'], [16], []
104
+ for m in _TAG.finditer(src):
105
+ close, name, attrs, selfc = m.group(1), m.group(2), m.group(3), m.group(4)
106
+ if close:
107
+ if name in ('Slide', 'Box') and len(stack) > 1: stack.pop()
108
+ if name in ('Text', 'span') and len(size) > 1: size.pop()
109
+ continue
110
+ bg = re.search(r"background(?:Color)?:\s*'#([0-9A-Fa-f]{6})'", attrs)
111
+ fs = re.search(r"fontSize:\s*(\d+)", attrs); col = re.search(r"(?<![A-Za-z])color:\s*'#([0-9A-Fa-f]{6})'", attrs)
112
+ if name in ('Slide', 'Box'):
113
+ grad = re.search(r"gradient|backgroundImage|url\(", attrs)
114
+ if not selfc: stack.append(None if grad else (bg.group(1) if bg else stack[-1]))
115
+ continue
116
+ cur = int(fs.group(1)) if fs else size[-1]
117
+ if not selfc: size.append(cur)
118
+ if col and 'backgroundClip' not in attrs and stack[-1] and cur < 150:
119
+ r = _ratio(col.group(1), stack[-1]); need = 3.0 if cur >= 24 else 4.5
120
+ if r < need: hits.append((src.count('\n', 0, m.start()) + 1, col.group(1), stack[-1], cur, r, need, 'FAIL' if r < 3.0 else 'warn'))
121
+ return hits
122
+
123
+ _DIGIT_HEX = re.compile(r"#(\d{6})\b")
124
+
125
+ def _hexsafe(h):
126
+ """The nearest colour whose hex code contains a letter. The WeCom exporter turns an all-digit value such as
127
+ #184785 or #244972 into pure red (FF0000) in the .pptx, so no colour may be written with six decimal digits."""
128
+ h = h.lstrip('#').upper()
129
+ if not h.isdigit(): return h
130
+ for d in range(1, 16):
131
+ for i in range(3):
132
+ v = int(h[2 * i:2 * i + 2], 16)
133
+ for cand in (v + d, v - d):
134
+ if 0 <= cand <= 255 and not f'{cand:02X}'.isdigit(): return h[:2 * i] + f'{cand:02X}' + h[2 * i + 2:]
135
+ return h
136
+
137
+ def _digit_hits(src):
138
+ return [(src.count('\n', 0, m.start()) + 1, m.group(1)) for m in _DIGIT_HEX.finditer(src)]
139
+
140
+ _SVG_OPEN = re.compile(r"<svg\b([^>]*)>")
141
+
142
+ def _svg_hits(src):
143
+ """SVGs whose PNG fallback the WeCom exporter would flatten onto white. The exporter stores every <svg> twice,
144
+ as the vector plus a rasterised PNG, and the PNG loses all transparency; Keynote, Quick Look and the preview
145
+ viewers read that PNG. So the first drawn child must be an opaque <rect> covering the whole viewBox in the
146
+ colour of the surface under it, the svg's own style may not carry opacity, and no paint may be rgba()."""
147
+ hits = []
148
+ for m in _SVG_OPEN.finditer(src):
149
+ ln = src.count('\n', 0, m.start()) + 1; attrs = m.group(1)
150
+ end = src.find('</svg>', m.end()); body = src[m.end():end if end > 0 else len(src)]
151
+ vb = re.search(r"viewBox=['\"]0 0 ([\d.]+) ([\d.]+)['\"]", attrs)
152
+ w = vb.group(1) if vb else (re.search(r"\bwidth=\{?['\"]?([\d.]+)", attrs) or [None, None])[1]
153
+ h = vb.group(2) if vb else (re.search(r"\bheight=\{?['\"]?([\d.]+)", attrs) or [None, None])[1]
154
+ if re.search(r"\bopacity:\s*[\d.]+", attrs):
155
+ hits.append((ln, "svg style carries opacity -> drop it and premix the colours with the surface (the exporter's PNG fallback ignores it)"))
156
+ if 'rgba(' in body:
157
+ hits.append((ln, "rgba() inside <svg> is not a valid SVG paint -> write a hex colour plus fillOpacity / strokeOpacity "
158
+ "(does not blank the graphic, but the PNG fallback may drop the colour)"))
159
+ for am in re.finditer(r'&', body):
160
+ aln = src.count('\n', 0, m.end() + am.start()) + 1
161
+ hits.append((aln, "'&' inside <svg> -> on export it becomes a bare '&', the svg turns into malformed XML and the WHOLE "
162
+ "graphic renders blank. Rewrite as 与 / and / ·. &amp;, &#38; and '\\u0026' all export to the same "
163
+ "bare '&' and do NOT help; '&' outside <svg> (e.g. in <Text>) is fine."))
164
+ if w:
165
+ for tm in re.finditer(r"<text\b([^>]*)>([^<{}]+)</text>", body):
166
+ ta, tb = tm.group(1), tm.group(2).strip()
167
+ mx = re.search(r"\bx=['\"{]?(-?[\d.]+)", ta)
168
+ if not tb or not mx:
169
+ continue
170
+ mfs = re.search(r"font-?[Ss]ize=['\"{]?([\d.]+)", ta)
171
+ x, fs = float(mx.group(1)), float(mfs.group(1)) if mfs else 16.0
172
+ # CJK full width, half width 0.55em
173
+ tw = sum(1.0 if ord(c) > 0x2E80 else 0.55 for c in tb) * fs
174
+ anchor = (re.search(r"text-?[Aa]nchor=['\"](\w+)", ta) or [None, 'start'])[1]
175
+ x0, x1 = (x - tw / 2, x + tw / 2) if anchor == 'middle' else \
176
+ ((x - tw, x) if anchor == 'end' else (x, x + tw))
177
+ tln = src.count('\n', 0, m.end() + tm.start()) + 1
178
+ if x1 > float(w) + 0.5:
179
+ hits.append((tln, f"svg text runs to {x1:.0f}, past the viewBox width {w} -> it gets hard-clipped. "
180
+ f"Move it left, shorten it, or widen the viewBox: {tb[:34]!r}"))
181
+ elif x0 < -0.5:
182
+ hits.append((tln, f"svg text starts at {x0:.0f}, left of the viewBox -> it gets hard-clipped: {tb[:34]!r}"))
183
+ inner = re.sub(r"<defs>.*?</defs>", '', body, flags=re.S)
184
+ first = re.search(r"<([A-Za-z]+)\b([^>]*)>", inner); ok = False
185
+ if first and first.group(1) == 'rect':
186
+ ra = first.group(2)
187
+ rw = re.search(r"\bwidth=['\"{]?([\d.]+%?)", ra); rh = re.search(r"\bheight=['\"{]?([\d.]+%?)", ra)
188
+ fill = re.search(r"\bfill=['\"]#[0-9A-Fa-f]{6}['\"]", ra)
189
+ cov = lambda v, need: v is not None and (v.group(1) == '100%' or need is None or float(v.group(1)) >= float(need))
190
+ ok = bool(fill) and cov(rw, w) and cov(rh, h) and 'opacity' not in ra.lower()
191
+ if not ok:
192
+ hits.append((ln, f"svg has no opaque backing rect -> its first drawn child must be <rect x='0' y='0' width='{w or 'W'}' height='{h or 'H'}' fill='#<colour of the surface under it>' /> (the exporter's PNG fallback turns transparency into white)"))
193
+ return hits
194
+
195
+ _ABS_TAG = re.compile(r"<(Box|Text|Image|svg)\b([^>]*?)/?>", re.S)
196
+ _ABS_STYLE = re.compile(r"style=\{\{(.*?)\}\}", re.S)
197
+
198
+
199
+ def _sprop(style, name):
200
+ m = (re.search(rf"\b{name}\s*:\s*'([^']*)'", style) or
201
+ re.search(rf"\b{name}\s*:\s*\"([^\"]*)\"", style) or
202
+ re.search(rf"\b{name}\s*:\s*([\d.-]+)", style))
203
+ return m.group(1).strip() if m else None
204
+
205
+
206
+ def _spx(v, base):
207
+ """'700px' / '50%' / 60 -> pixels (base is used for percentages)."""
208
+ if v is None:
209
+ return None
210
+ s = str(v).strip()
211
+ m = re.match(r"^(-?[\d.]+)\s*%$", s)
212
+ if m:
213
+ return float(m.group(1)) / 100.0 * base
214
+ m = re.match(r"^(-?[\d.]+)(?:px)?$", s)
215
+ return float(m.group(1)) if m else None
216
+
217
+
218
+ def _abs_hits(src, W=1280.0, H=720.0):
219
+ """Absolutely positioned elements that stick out of the canvas. The renderer rejects the whole page for
220
+ these (content overflow) instead of just clipping them, and a flow-layout height check will not catch
221
+ them because they sit outside the flow. Mirrors the renderer's own maths:
222
+ top = pct(top)*H - pct(translateY)*height
223
+ left = pct(left)*W - pct(translateX)*width"""
224
+ hits = []
225
+ for m in _ABS_TAG.finditer(src):
226
+ tag, attrs = m.group(1), m.group(2)
227
+ ms = _ABS_STYLE.search(attrs)
228
+ if not ms or _sprop(ms.group(1), 'position') != 'absolute':
229
+ continue
230
+ st = ms.group(1)
231
+ ln = src.count('\n', 0, m.start()) + 1
232
+ w, h = _spx(_sprop(st, 'width'), W), _spx(_sprop(st, 'height'), H)
233
+ dx = dy = 0.0
234
+ tr = _sprop(st, 'transform')
235
+ if tr:
236
+ tm = re.search(r"translate\(\s*([^,)]+)(?:,\s*([^)]+))?\)", tr)
237
+ if tm:
238
+ dx = _spx(tm.group(1), w or 0) or 0.0
239
+ dy = (_spx(tm.group(2), h or 0) or 0.0) if tm.group(2) else 0.0
240
+ for fn, idx in (("translateX", 'x'), ("translateY", 'y')):
241
+ fm = re.search(rf"{fn}\(\s*([^)]+)\)", tr)
242
+ if fm:
243
+ val = _spx(fm.group(1), (w or 0) if idx == 'x' else (h or 0)) or 0.0
244
+ if idx == 'x':
245
+ dx = val
246
+ else:
247
+ dy = val
248
+ top, left = _spx(_sprop(st, 'top'), H), _spx(_sprop(st, 'left'), W)
249
+ bot, rgt = _spx(_sprop(st, 'bottom'), H), _spx(_sprop(st, 'right'), W)
250
+
251
+ y0 = y1 = x0 = x1 = None
252
+ if top is not None:
253
+ y0 = top + dy
254
+ y1 = y0 + h if h is not None else None
255
+ elif bot is not None and h is not None:
256
+ y1 = H - bot + dy
257
+ y0 = y1 - h
258
+ if left is not None:
259
+ x0 = left + dx
260
+ x1 = x0 + w if w is not None else None
261
+ elif rgt is not None and w is not None:
262
+ x1 = W - rgt + dx
263
+ x0 = x1 - w
264
+
265
+ for val, lim, side in ((y0, 0, 'top'), (x0, 0, 'left')):
266
+ if val is not None and val < -0.5:
267
+ hits.append((ln, f"<{tag}> sticks out past the {side} of the canvas by {-val:.0f}px "
268
+ f"({side} edge at {val:.0f}) -> the page is rejected as overflowing. "
269
+ f"Pull it back inside (non-negative offsets, translate at most -50%)"))
270
+ if y1 is not None and y1 > H + 0.5:
271
+ hits.append((ln, f"<{tag}> sticks out past the bottom of the canvas by {y1-H:.0f}px "
272
+ f"(bottom edge at {y1:.0f}) -> the page is rejected as overflowing"))
273
+ if x1 is not None and x1 > W + 0.5:
274
+ hits.append((ln, f"<{tag}> sticks out past the right of the canvas by {x1-W:.0f}px "
275
+ f"(right edge at {x1:.0f}) -> the page is rejected as overflowing"))
276
+ for k in ('top', 'left', 'bottom', 'right'):
277
+ raw = _sprop(st, k)
278
+ if raw and str(raw).startswith('-'):
279
+ hits.append((ln, f"<{tag}> {k}:{raw} is a negative offset -> not allowed, "
280
+ f"position with positive values instead (e.g. top:40, right:40)"))
281
+ return hits
282
+
283
+
284
+ def contrast(a):
285
+ """Flag text whose colour is too close to the surface it sits on (nearest ancestor with a solid background).
286
+ Contrast under 3.0 fails; small text between 3.0 and 4.5 is only counted as a warning. Gradient surfaces and
287
+ decorative numerals of 150px and up are skipped. Also flags what the WeCom exporter breaks (six-digit colour
288
+ codes, SVGs without an opaque backing rect, '&' inside an svg, svg text past the viewBox) and absolutely
289
+ positioned elements that stick out of the 1280x720 canvas."""
290
+ bad = 0
291
+ for p in a.pages:
292
+ src = open(p, encoding='utf-8').read()
293
+ hits = _contrast_hits(src); digits = _digit_hits(src); svgs = _svg_hits(src); abso = _abs_hits(src)
294
+ fails = [h for h in hits if h[6] == 'FAIL']
295
+ print(('LOW ' if fails or digits or svgs or abso else 'OK ') + p + (f' ({len(hits) - len(fails)} small-text warnings under 4.5)' if len(hits) > len(fails) else ''))
296
+ for ln, c, b, fsz, r, need, lvl in fails[:20]: print(f' line {ln}: text #{c} on #{b}, {fsz}px, contrast {r:.2f} < 3.0 -> unreadable, change the text or surface colour')
297
+ for ln, c in digits[:20]: print(f' line {ln}: #{c} is six decimal digits; the WeCom exporter turns such values into pure red (FF0000) -> write #{_hexsafe(c)}')
298
+ for ln, msg in svgs[:20]: print(f' line {ln}: {msg}')
299
+ for ln, msg in abso[:20]: print(f' line {ln}: {msg}')
300
+ bad += bool(fails or digits or svgs or abso)
301
+ sys.exit(1 if bad else 0)
302
+
303
+ def _dims_from_bytes(b):
304
+ """Return (w, h) for PNG / JPEG / GIF / WebP headers, or None."""
305
+ import struct
306
+ if b[:8] == b'\x89PNG\r\n\x1a\n' and len(b) >= 24: return struct.unpack('>II', b[16:24])
307
+ if b[:6] in (b'GIF87a', b'GIF89a') and len(b) >= 10: return struct.unpack('<HH', b[6:10])
308
+ if b[:4] == b'RIFF' and b[8:12] == b'WEBP' and len(b) >= 30:
309
+ if b[12:16] == b'VP8 ': return struct.unpack('<HH', b[26:30])[0] & 0x3fff, struct.unpack('<HH', b[26:30])[1] & 0x3fff
310
+ if b[12:16] == b'VP8L': bits = int.from_bytes(b[21:25], 'little'); return (bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1
311
+ if b[12:16] == b'VP8X': return int.from_bytes(b[24:27], 'little') + 1, int.from_bytes(b[27:30], 'little') + 1
312
+ if b[:2] == b'\xff\xd8':
313
+ i = 2
314
+ while i + 9 < len(b):
315
+ if b[i] != 0xff: i += 1; continue
316
+ marker = b[i + 1]; seg = int.from_bytes(b[i + 2:i + 4], 'big')
317
+ if marker in (0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf):
318
+ return int.from_bytes(b[i + 7:i + 9], 'big'), int.from_bytes(b[i + 5:i + 7], 'big')
319
+ i += 2 + seg
320
+ return None
321
+
322
+ def _fetch_dims(url, timeout=8):
323
+ import urllib.request
324
+ try:
325
+ req = urllib.request.Request(url, headers={'Range': 'bytes=0-65535', 'User-Agent': 'build_page'})
326
+ with urllib.request.urlopen(req, timeout=timeout) as r: return _dims_from_bytes(r.read(65536))
327
+ except Exception: return None
328
+
329
+ def imgfit(a):
330
+ """Print the JSX for an image slot so the picture keeps its real aspect ratio. Never stretches, never relies on objectFit
331
+ (the WeCom compiler crops as if every picture were square, so a non-square picture filled into a slot gets squashed)."""
332
+ sw, sh = map(float, a.slot.lower().split('x')); aw, ah = map(float, a.actual.lower().split('x'))
333
+ slot_r, img_r = sw / sh, aw / ah; dev = abs(img_r - slot_r) / slot_r
334
+ if dev <= 0.03:
335
+ w, h = int(sw), int(sh); note = f'ratio matches slot ({dev*100:.1f}% off), fill the slot'
336
+ elif img_r > slot_r:
337
+ w, h = int(sw), round(sw / img_r); note = f'image wider than slot ({dev*100:.0f}% off): full width, {h}px tall, letterboxed'
338
+ else:
339
+ h, w = int(sh), round(sh * img_r); note = f'image taller than slot ({dev*100:.0f}% off): full height, {w}px wide, pillarboxed'
340
+ bg = f", background: '{a.bg}'" if a.bg else ''
341
+ print(f"<Box style={{{{ width: {int(sw)}, height: {int(sh)}, justifyContent: 'center', alignItems: 'center'{bg} }}}}>")
342
+ print(f" <Image src=\"{a.src}\" style={{{{ width: {w}, height: {h} }}}} />")
343
+ print("</Box>")
344
+ print(f"// {note}" if False else "", end='')
345
+ sys.stderr.write(note + ('\n consider regenerating at the slot ratio instead of letterboxing' if dev > 0.03 else '') + '\n')
346
+
347
+ def _image_issues(src, manifest, fetch=True):
348
+ tag = re.compile(r'<Image\b[^>]*?src=["\']([^"\']+)["\'][^>]*?>', re.S); issues = []
349
+ for m in tag.finditer(src):
350
+ url = m.group(1); attrs = m.group(0)
351
+ w = re.search(r'width:\s*(\d+(?:\.\d+)?)', attrs); h = re.search(r'height:\s*(\d+(?:\.\d+)?)', attrs)
352
+ if not (w and h): issues.append(f'{url[:60]}: width/height not both numeric'); continue
353
+ if url.startswith('tpl_assets/'): issues.append(f'{url}: template art not uploaded yet -> run `template --docid <docid>` once'); continue
354
+ act = manifest.get(url) or (_fetch_dims(url) if fetch else None)
355
+ if isinstance(act, dict) and act.get('stretch'): continue # a template's own page background, stretched to 16:9 on purpose
356
+ if not act: issues.append(f'{url[:60]}: real size unknown (not in manifest, not fetchable) -> record it in images.json'); continue
357
+ aw, ah = act if isinstance(act, (list, tuple)) else (act['width'], act['height'])
358
+ dev = abs((aw / ah) - (float(w.group(1)) / float(h.group(1)))) / (aw / ah)
359
+ if dev > 0.03: issues.append(f'{url[:60]}: real {aw}x{ah} vs written {w.group(1)}x{h.group(1)}, ratio off by {dev*100:.0f}% -> squashed; use imgfit')
360
+ return issues
361
+
362
+ def images(a):
363
+ """Check every <Image> in the pages: its written width/height must match the picture's real aspect ratio (within 3%)."""
364
+ manifest = json.load(open(a.manifest, encoding='utf-8')) if a.manifest else {}; bad = 0
365
+ for p in a.pages:
366
+ issues = _image_issues(open(p, encoding='utf-8').read(), manifest)
367
+ print(('BAD ' if issues else 'OK ') + p); [print(' ' + i) for i in issues]; bad += bool(issues)
368
+ sys.exit(1 if bad else 0)
369
+
370
+ _TEMPLATE_DIRS = (('..', 'assets', 'templates'), ('templates',), ('..', 'references', 'templates'))
371
+
372
+ def _templates_root():
373
+ """Locate the template pool. Runtimes ship it under assets/ (sandbox) or references/ (skill tree)."""
374
+ import os
375
+ here = os.path.dirname(os.path.abspath(__file__))
376
+ for rel in _TEMPLATE_DIRS:
377
+ cand = os.path.join(here, *rel)
378
+ if os.path.isdir(cand): return cand
379
+ sys.exit('template pool not found next to build_page.py; looked in: '
380
+ + ', '.join('/'.join(r) for r in _TEMPLATE_DIRS))
381
+
382
+ def _set_root(name):
383
+ import os
384
+ root = os.path.join(_templates_root(), name)
385
+ if not os.path.isdir(root): sys.exit(f'no such set: {name} (use the flat slug, e.g. signal)')
386
+ return root
387
+
388
+ def _set_files(root):
389
+ import os, glob
390
+ return sorted(glob.glob(os.path.join(root, 'shell', '*.jsx'))) + sorted(glob.glob(os.path.join(root, 'slides', '*.slide')))
391
+
392
+ def _rgb_to_hsl(h):
393
+ r, g, b = (int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
394
+ mx, mn = max(r, g, b), min(r, g, b); l = (mx + mn) / 2
395
+ if mx == mn: return 0.0, 0.0, l
396
+ d = mx - mn; s = d / (2 - mx - mn) if l > 0.5 else d / (mx + mn)
397
+ if mx == r: hu = ((g - b) / d) % 6
398
+ elif mx == g: hu = (b - r) / d + 2
399
+ else: hu = (r - g) / d + 4
400
+ return hu * 60, s, l
401
+
402
+ def _hsl_to_rgb(hu, s, l):
403
+ hu = hu % 360; c = (1 - abs(2 * l - 1)) * s; x = c * (1 - abs((hu / 60) % 2 - 1)); m = l - c / 2
404
+ r, g, b = [(c, x, 0), (x, c, 0), (0, c, x), (0, x, c), (x, 0, c), (c, 0, x)][int(hu // 60) % 6]
405
+ return '%02X%02X%02X' % tuple(round((v + m) * 255) for v in (r, g, b))
406
+
407
+ def _at_luminance(hu, s, target):
408
+ """The hue/saturation asked for, with lightness tuned until the colour has the given relative luminance.
409
+ Matching luminance (not HSL lightness) is what keeps every contrast ratio of the original palette intact:
410
+ HSL lightness lies, a yellow and a blue at the same lightness are nowhere near the same brightness."""
411
+ lo, hi = 0.0, 1.0
412
+ for _ in range(24):
413
+ mid = (lo + hi) / 2
414
+ if _lum(_hsl_to_rgb(hu, s, mid)) < target: lo = mid
415
+ else: hi = mid
416
+ return _hsl_to_rgb(hu, s, (lo + hi) / 2)
417
+
418
+ def palette(a):
419
+ """Derive a whole palette for a set from one hue, keeping every colour's luminance (so the contrast the set was
420
+ built with survives exactly) and the hue distances between colours (so multi-colour sets stay distinguishable).
421
+ Writes colors.json for `init --map` and checks every text/surface pair before doing so."""
422
+ import os, json as _json, collections
423
+ root = _set_root(a.set); files = _set_files(root)
424
+ srcs = {f: open(f, encoding='utf-8').read() for f in files}
425
+ counts = collections.Counter(h.upper() for s in srcs.values() for h in HEX.findall(s))
426
+ if not counts: sys.exit(f'no colours found in {a.set}')
427
+ hsl = {h: _rgb_to_hsl(h) for h in counts}
428
+ chroma = [h for h in counts if hsl[h][1] >= 0.12]
429
+ base_hue = hsl[max(chroma, key=lambda h: counts[h])][0] if chroma else 0.0
430
+ gap = abs((a.hue - base_hue + 180) % 360 - 180) # how far the asked-for hue is from the set's own
431
+ if chroma and not a.invert and not a.force and gap < a.min_gap:
432
+ print(f"{a.set} is already a {base_hue:.0f} hue set; --hue {a.hue:.0f} is only {gap:.0f} deg away "
433
+ f"(gate: {a.min_gap:.0f}).\nA palette this close to the default is the default with the edges filed "
434
+ "off: it clears every contrast check and\nstill looks like the set's own colours, so it is a recolour "
435
+ "in name only.")
436
+ print("\nUSE THE SET'S DEFAULT PALETTE. Run init WITHOUT --map, and record in DESIGN.md that the colour "
437
+ "intent\nmatches this set's default (state both hues and the gap). That is a legitimate outcome, not "
438
+ "a failure -- do\nNOT go hunting for some other hue just to get past this gate, and do NOT hand-write "
439
+ "a map.")
440
+ print(f"\nOnly if the deck genuinely needs a different colour: pick a hue at least {a.min_gap:.0f} deg from "
441
+ f"{base_hue:.0f} (i.e. outside\n{(base_hue - a.min_gap) % 360:.0f}-{(base_hue + a.min_gap) % 360:.0f}). "
442
+ "If the user named a brand colour that lands inside the gate, pass --force.")
443
+ return
444
+ cmap = {}
445
+ for h, (hu, s, l) in hsl.items():
446
+ if s < 0.12: # neutrals: keep them neutral, just a hint of the new hue
447
+ ns, nhu = min(s + 0.03, 0.08), a.hue
448
+ else: # chromatics: same hue distances, rotated onto the new hue.
449
+ ns = max(0.0, min(1.0, s * a.sat)) # tinted surfaces (low saturation) collapse onto the new hue
450
+ off = (hu - base_hue + 180) % 360 - 180 # instead of being flung to its opposite side
451
+ nhu = a.hue + off * a.spread * min(1.0, s / 0.35)
452
+ target = 1 - _lum(h) if a.invert else _lum(h)
453
+ new = _at_luminance(nhu, ns, target)
454
+ new = _hexsafe(new) # six decimal digits would export as pure red
455
+ if new != h: cmap[h] = new
456
+ if not cmap: print('the derived palette is identical to the default one -- use the default: run init without '
457
+ '--map.'); return
458
+ fails = []
459
+ for f, src in srcs.items():
460
+ for ln, c, b, fsz, r, need, lvl in _contrast_hits(_apply_cmap(src, cmap)):
461
+ if lvl == 'FAIL': fails.append(f'{os.path.basename(f)} line {ln}: text #{c} on #{b}, {fsz}px, contrast {r:.2f} < 3.0')
462
+ for h, n in sorted(cmap.items(), key=lambda kv: -counts[kv[0]]): print(f' #{h} -> #{n} (used {counts[h]}x)')
463
+ if fails:
464
+ print('\ncontrast FAIL on the derived palette:'); [print(' ' + f) for f in fails[:10]]
465
+ sys.exit('\nnot written. With --invert this is expected for most sets: flipping light and dark cannot keep the\n'
466
+ 'contrast the set was built with. Pick a set whose default scheme is already the one you want, or drop\n'
467
+ '--invert (a hue on its own always keeps the contrast). Otherwise try another --hue or --sat below 1.'
468
+ if a.invert else '\nnot written. Try another --hue, or --sat below 1.')
469
+ try:
470
+ _json.dump({'#' + k: '#' + v for k, v in cmap.items()}, open(a.out, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
471
+ except OSError as e:
472
+ sys.exit(f'cannot write {a.out!r}: {e.strerror}.\n'
473
+ 'Wrong location, not a broken environment -- write it inside the working directory\n'
474
+ 'under the session output dir, then retry.')
475
+ print(f'\ncontrast OK on every page of the set -> {a.out}\nnext: python3 "{{baseDir}}/scripts/build_page.py" init --set {a.set} --map {a.out}')
476
+
477
+ def _load_cmap(path):
478
+ cmap = {k.strip().lstrip('#').upper(): v.strip().lstrip('#').upper() for k, v in json.load(open(path, encoding='utf-8')).items()}
479
+ for k, v in cmap.items():
480
+ if not re.fullmatch(r'[0-9A-F]{6}', k) or not re.fullmatch(r'[0-9A-F]{6}', v): sys.exit(f'bad colour in map: {k} -> {v} (use 6-digit hex, e.g. "#1C2644": "#F4F1EA")')
481
+ return cmap
482
+
483
+ def _apply_cmap(text, cmap):
484
+ """Replace every mapped colour in a single pass, so {"#A": "#B", "#B": "#A"} really swaps the two
485
+ (replacing one entry after another would turn both into A and leave text the same colour as its background)."""
486
+ if not cmap: return text
487
+ rgb = {tuple(int(k[i:i + 2], 16) for i in (0, 2, 4)): v for k, v in cmap.items()}
488
+ hexes = '|'.join(cmap)
489
+ rgbas = '|'.join(r'%d\s*,\s*%d\s*,\s*%d\s*,' % t for t in rgb)
490
+ rx = re.compile(r'#(' + hexes + r')(?![0-9A-Fa-f])|rgba\(\s*(?=' + rgbas + r')(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,', re.I)
491
+ def sub(m):
492
+ if m.group(1): return '#' + cmap[m.group(1).upper()]
493
+ v = rgb[tuple(int(m.group(i)) for i in (2, 3, 4))]
494
+ return 'rgba(%d, %d, %d,' % tuple(int(v[i:i + 2], 16) for i in (0, 2, 4))
495
+ return rx.sub(sub, text)
496
+
497
+ def recolor(a):
498
+ """Apply a colour map {old_hex: new_hex} to shell / template files and write the recoloured copies to --out-dir.
499
+ Matches hex literals case-insensitively and the matching rgba(r, g, b, ...) forms. Colours not in the map are left as they are."""
500
+ import os
501
+ cmap = _load_cmap(a.map)
502
+ os.makedirs(a.out_dir, exist_ok=True); unused = set(cmap); untouched = {}
503
+ for p in a.files:
504
+ src = open(p, encoding='utf-8').read()
505
+ unused -= {old for old in cmap if re.search('#' + old + '(?![0-9A-Fa-f])', src, re.I)}
506
+ out = _apply_cmap(src, cmap)
507
+ for h in set(x.upper() for x in HEX.findall(out)):
508
+ if h not in cmap.values(): untouched[h] = untouched.get(h, 0) + 1
509
+ dst = os.path.join(a.out_dir, os.path.basename(p)); open(dst, 'w', encoding='utf-8').write(out); print(f'ok {dst}')
510
+ if unused: print('map entries that matched nothing: ' + ', '.join('#' + u for u in sorted(unused)))
511
+ if untouched: print('colours left unchanged (not in map): ' + ', '.join('#' + u for u in sorted(untouched)) + ' -> add them to the map if they belong to the old palette')
512
+ print('next: run `contrast` on the recoloured pages before using them')
513
+
514
+ def init(a):
515
+ """Copy a set's shells and template pages into the working dir in one go (optionally recoloured), so the agent never
516
+ has to run cp against the skill directory."""
517
+ import os, shutil
518
+ root = _set_root(a.set)
519
+ try:
520
+ os.makedirs(a.out, exist_ok=True)
521
+ except OSError as e:
522
+ sys.exit(f'cannot create the working directory {a.out!r}: {e.strerror}.\n'
523
+ 'This is the wrong location, not a broken environment -- put the working directory\n'
524
+ 'under the session output dir (e.g. <writable>/temp/<session_id>/output/<name>) and retry.\n'
525
+ 'Do not probe the filesystem for other writable paths.')
526
+ srcs = [os.path.join(root, 'shell', f) for f in sorted(os.listdir(os.path.join(root, 'shell')))] + \
527
+ [os.path.join(root, 'slides', f) for f in sorted(os.listdir(os.path.join(root, 'slides')))] + [os.path.join(root, 'DESIGN.preset.md')]
528
+ cmap = _load_cmap(a.map) if a.map else {}
529
+ for src in srcs:
530
+ name = os.path.basename(src)
531
+ if name.startswith('content'): name = '00_shell' + name[len('content'):]
532
+ elif src.endswith('.slide'): name = 'ref_' + name
533
+ text = _apply_cmap(open(src, encoding='utf-8').read(), cmap)
534
+ open(os.path.join(a.out, name), 'w', encoding='utf-8').write(text); print(f'ok {os.path.normpath(os.path.join(a.out, name))}')
535
+ print('\nthe files above are in the working directory: open and write them by these bare file names only, never by an absolute path')
536
+ refs = [os.path.basename(s).replace('.slide', '') for s in srcs if s.endswith('.slide')]
537
+ print('BEFORE WRITING EACH PAGE: open the ref_*.slide whose skeleton is closest to that page and rework it —\n'
538
+ f' keep its columns, card shapes and gaps, type scale and signature treatment, swap only the words and numbers.\n'
539
+ f' Available skeletons: {", ".join("ref_" + r for r in refs)}\n'
540
+ ' A body written without one of these open only looks like the template in its header and footer.')
541
+ if not cmap: print('NOTE: copied with the set\'s DEFAULT palette. That is correct in exactly two cases: the user asked\n'
542
+ ' for the default or a brand colour by name, or palette said the colour intent is within its\n'
543
+ ' hue gate of this set\'s own hue. Either way say so in DESIGN.md.\n'
544
+ f' Otherwise derive one first: palette --set {a.set} --hue <0-360> [--sat 0.8], then rerun init with --map colors.json')
545
+
546
+ def buildall(a):
547
+ """Build every NN_body.jsx in the working dir with its NN_vars.json, then run check + contrast (+ images) once."""
548
+ import glob, os, types
549
+ bodies = sorted(glob.glob(os.path.join(a.dir, '[0-9][0-9]_body*.jsx'))); bad = 0; built = []
550
+ # bodies written with a slug, e.g. 03_definition_body.jsx (+ 03_definition_vars.json -> 03_definition_page.jsx)
551
+ named = sorted(p for p in glob.glob(os.path.join(a.dir, '[0-9][0-9]_*_body*.jsx'))
552
+ if p not in bodies and not re.match(r'\d\d_body', os.path.basename(p)))
553
+ for body in named:
554
+ b = os.path.basename(body); stem, suffix = re.match(r'(\d\d_.+?)_body(.*)\.jsx$', b).groups()
555
+ shell = os.path.join(a.dir, '00_shell' + suffix + '.jsx')
556
+ if not os.path.exists(shell): shell = os.path.join(a.dir, '00_shell.jsx')
557
+ out = os.path.join(a.dir, f'{stem}_page.jsx'); vars_ = os.path.join(a.dir, f'{stem}_vars.json')
558
+ manifest = os.path.join(a.dir, 'images.json')
559
+ ns = types.SimpleNamespace(shell=shell, body=body, vars=vars_ if os.path.exists(vars_) else None,
560
+ manifest=manifest if os.path.exists(manifest) else None, out=out)
561
+ try: build(ns); built.append(out)
562
+ except SystemExit as e: bad += 1; print(f'FAIL {body}: {e}')
563
+ for body in bodies:
564
+ nn = os.path.basename(body)[:2]; suffix = os.path.basename(body)[len(nn) + 5:-4]
565
+ shell = os.path.join(a.dir, '00_shell' + suffix + '.jsx')
566
+ if not os.path.exists(shell): shell = os.path.join(a.dir, '00_shell.jsx')
567
+ out = os.path.join(a.dir, f'{nn}_page.jsx'); vars_ = os.path.join(a.dir, f'{nn}_vars.json')
568
+ manifest = os.path.join(a.dir, 'images.json')
569
+ ns = types.SimpleNamespace(shell=shell, body=body, vars=vars_ if os.path.exists(vars_) else None,
570
+ manifest=manifest if os.path.exists(manifest) else None, out=out)
571
+ try: build(ns); built.append(out)
572
+ except SystemExit as e: bad += 1; print(f'FAIL {body}: {e}')
573
+ bodies = bodies + named
574
+ pages = sorted(set(built + [p for p in glob.glob(os.path.join(a.dir, '[0-9][0-9]_*.jsx')) if not os.path.basename(p).startswith('00_')]) - set(bodies) - {p for p in glob.glob(os.path.join(a.dir, '[0-9][0-9]_*.jsx')) if re.search(r'_body[^/]*\.jsx$', p)})
575
+ if not bodies and not pages:
576
+ orphan = sorted(os.path.basename(p) for p in glob.glob(os.path.join(a.dir, '[0-9][0-9]_vars.json')))
577
+ if orphan:
578
+ sys.exit(f'nothing to build in {os.path.abspath(a.dir)}: found {", ".join(orphan)} but no matching body.\n'
579
+ 'A page needs BOTH files: NN_body.jsx (or NN_body_light.jsx / NN_body_dark.jsx for a second\n'
580
+ 'shell) plus NN_vars.json. Only the body file makes buildall pick the page up -- vars alone is\n'
581
+ 'invisible to it. Write the missing NN_body*.jsx and rerun; the suffix must match the shell you\n'
582
+ 'want (00_shell_dark.jsx <- NN_body_dark.jsx), no suffix falls back to 00_shell.jsx.')
583
+ sys.exit(f'nothing to build in {os.path.abspath(a.dir)}: no NN_body*.jsx and no NN_*.jsx page found.\n'
584
+ 'Run this command from the working directory that holds the page sources (or pass --dir), '
585
+ 'otherwise it would report ALL OK without checking anything.')
586
+ import io, contextlib
587
+ steps = [('contrast (colours, svg, canvas edges)', contrast, types.SimpleNamespace(pages=pages)),
588
+ ('fit (does the text fit its box)', fit, types.SimpleNamespace(pages=pages))]
589
+ if os.path.exists(os.path.join(a.dir, 'images.json')):
590
+ steps.append(('images (aspect ratio)', images, types.SimpleNamespace(manifest=os.path.join(a.dir, 'images.json'), pages=pages)))
591
+ failed = {}
592
+ for title, fn, ns in steps:
593
+ buf = io.StringIO()
594
+ with contextlib.redirect_stdout(buf):
595
+ try: fn(ns)
596
+ except SystemExit as e: bad += bool(e.code)
597
+ out = buf.getvalue()
598
+ print(f'== {title} ==')
599
+ print(out, end='')
600
+ for ln in out.splitlines():
601
+ m = re.match(r'(OVER|LOW|BAD|DRIFT)\s+(\S+)', ln)
602
+ if m: failed.setdefault(os.path.basename(m.group(2)), []).append(m.group(1))
603
+ if not bad:
604
+ print('ALL OK'); sys.exit(0)
605
+ print(f'\n{bad} problem(s) above. NOT OK -- these pages fail (a page is only OK when it passes EVERY section):')
606
+ for pg, kinds in sorted(failed.items()): print(f' {pg}: {", ".join(dict.fromkeys(kinds))}')
607
+ print('Fix ALL of them in one pass -- read each OVER line, edit every page listed, and only then rerun\n'
608
+ 'buildall once; rerunning after each small edit burns a round trip per box. When a box is short, cut\n'
609
+ 'words or drop a block (the hint under each page says which); do not creep heights up a few px at a time.')
610
+ print('Fix every page listed, whoever wrote it and whenever: pages submitted earlier, pages written in a\n'
611
+ 'previous plan step and cover / catalog / section / ending pages count too. Edit the source, rerun\n'
612
+ 'buildall until ALL OK. A page that is already in the document is redone as a whole: first\n'
613
+ '`slide pages delete` at its page_index, then `slide pages addjsx` at that same page_index\n'
614
+ '(addjsx INSERTS -- without the delete the page appears twice). Pages not submitted yet are just\n'
615
+ 'submitted as usual. Do not export or deliver while this list is not empty.')
616
+ sys.exit(1)
617
+
618
+ # ---- fit: does the content fit the box it was written into? -----------------------------------
619
+ _FIT_TAG = re.compile(r"<(/?)([A-Za-z][A-Za-z0-9]*)((?:[^<>]|=>)*?)(/?)>", re.S)
620
+ _NUM = re.compile(r"^-?\d+(?:\.\d+)?$")
621
+ _LEAF = ('Text', 'Image', 'Chart', 'Table', 'FAIcon', 'QRCode', 'CodeBlock', 'Math', 'svg', 'br')
622
+
623
+ class _N:
624
+ __slots__ = ('tag', 'st', 'line', 'lines', 'kids', 'raw')
625
+ def __init__(s, tag, st, line): s.tag, s.st, s.line, s.lines, s.kids, s.raw = tag, st, line, [], [], False
626
+
627
+ def _style_dict(attrs):
628
+ """One tag's inline style={{ ... }} as {property: raw value}."""
629
+ m = re.search(r"style=\{\{", attrs)
630
+ if not m: return {}
631
+ i, depth = m.end(), 2
632
+ while i < len(attrs) and depth:
633
+ if attrs[i] == '{': depth += 1
634
+ elif attrs[i] == '}': depth -= 1
635
+ i += 1
636
+ parts, cur, depth, q = [], '', 0, ''
637
+ for ch in attrs[m.end():i - 2]:
638
+ if q:
639
+ cur += ch
640
+ if ch == q: q = ''
641
+ continue
642
+ if ch in '"\'': q = ch; cur += ch; continue
643
+ if ch in '([{': depth += 1
644
+ elif ch in ')]}': depth -= 1
645
+ if ch == ',' and depth == 0: parts.append(cur); cur = ''; continue
646
+ cur += ch
647
+ parts.append(cur)
648
+ out = {}
649
+ for p in parts:
650
+ if ':' not in p: continue
651
+ k, v = p.split(':', 1)
652
+ out[k.strip().strip("'\"")] = v.strip()
653
+ return out
654
+
655
+ def _px(v, base=None):
656
+ """A style value in pixels: 12, '12px', or '50%' of base. None when it cannot be resolved."""
657
+ if v is None: return None
658
+ v = str(v).strip().strip("'\"")
659
+ if _NUM.match(v): return float(v)
660
+ if v.endswith('px') and _NUM.match(v[:-2]): return float(v[:-2])
661
+ if v.endswith('%') and _NUM.match(v[:-1]): return None if base is None else float(v[:-1]) / 100 * base
662
+ return None
663
+
664
+ def _edges(st, key):
665
+ """(top, right, bottom, left) for padding / margin, from the shorthand and the per-side keys."""
666
+ t = r = b = l = 0.0
667
+ raw = st.get(key)
668
+ if raw is not None:
669
+ nums = [n for n in (_px(x) for x in str(raw).strip().strip("'\"").split()) if n is not None]
670
+ if len(nums) == 1: t = r = b = l = nums[0]
671
+ elif len(nums) == 2: t = b = nums[0]; r = l = nums[1]
672
+ elif len(nums) == 3: t, r, b = nums[:3]; l = r
673
+ elif len(nums) >= 4: t, r, b, l = nums[:4]
674
+ for i, side in enumerate(('Top', 'Right', 'Bottom', 'Left')):
675
+ v = _px(st.get(key + side))
676
+ if v is None: continue
677
+ t, r, b, l = (v, r, b, l) if i == 0 else (t, v, b, l) if i == 1 else (t, r, v, l) if i == 2 else (t, r, b, v)
678
+ return t, r, b, l
679
+
680
+ def _border(st):
681
+ def w(k):
682
+ m = re.match(r"\s*'?\s*(\d+(?:\.\d+)?)px", str(st.get(k, '') or ''))
683
+ return float(m.group(1)) if m else None
684
+ a = w('border') or 0.0
685
+ return tuple(w('border' + s) if w('border' + s) is not None else a for s in ('Top', 'Right', 'Bottom', 'Left'))
686
+
687
+ def _advance(ch, mono):
688
+ """Advance width of one character in em — the model the presets quote for counting lines."""
689
+ o = ord(ch)
690
+ if o >= 0x1100 or 0x2010 <= o <= 0x203F: return 1.0
691
+ if mono: return 0.6
692
+ if ch == ' ': return 0.3
693
+ if 'A' <= ch <= 'Z': return 0.75
694
+ if 'a' <= ch <= 'z' or ch.isdigit(): return 0.55
695
+ return 0.5
696
+
697
+ def _runs(inner):
698
+ """A <Text>'s body as lines of (text, span style): <br /> breaks a line, spans keep their own size."""
699
+ lines, cur, stack, i = [], [], [], 0
700
+ def put(s):
701
+ s = re.sub(r"^\s*\n\s*|\s*\n\s*$", '', s) # newlines next to a tag vanish (JSX)
702
+ s = re.sub(r"\s*\n\s*", ' ', s).replace('&nbsp;', ' ') # a newline between words becomes ONE space (JSX)
703
+ if s: cur.append((s, stack[-1] if stack else {}))
704
+ while i < len(inner):
705
+ m = re.compile(r"<(/?)([A-Za-z][A-Za-z0-9]*)?((?:[^<>]|=>)*?)(/?)>").search(inner, i)
706
+ if not m: put(inner[i:]); break
707
+ put(inner[i:m.start()])
708
+ name, close, selfc = (m.group(2) or ''), m.group(1), m.group(4)
709
+ if name == 'br': lines.append(cur); cur = []
710
+ elif name == 'span' and not close and not selfc: stack.append(_style_dict(m.group(3)))
711
+ elif name == 'span' and close and stack: stack.pop()
712
+ i = m.end()
713
+ lines.append(cur)
714
+ return [ln for ln in lines if any(t.strip() for t, _ in ln)] or []
715
+
716
+ def _close_at(src, pos, name):
717
+ """(inner end, resume) for the tag that was opened just before pos."""
718
+ depth = 1
719
+ for m in re.finditer(r"<(/?)" + name + r"\b((?:[^<>]|=>)*?)(/?)>", src[pos:], re.S):
720
+ if m.group(1): depth -= 1
721
+ elif not m.group(3): depth += 1
722
+ if not depth: return pos + m.start(), pos + m.end()
723
+ return len(src), len(src)
724
+
725
+ def _parse(src):
726
+ root = _N('root', {}, 0); stack, i = [root], 0
727
+ while True:
728
+ m = _FIT_TAG.search(src, i)
729
+ if not m: break
730
+ close, name, attrs, selfc = m.group(1), m.group(2), m.group(3), m.group(4)
731
+ if close:
732
+ if len(stack) > 1 and stack[-1].tag == name: stack.pop()
733
+ i = m.end(); continue
734
+ n = _N(name, _style_dict(attrs), src.count('\n', 0, m.start()) + 1)
735
+ stack[-1].kids.append(n)
736
+ if name == 'Text' and not selfc:
737
+ end, after = _close_at(src, m.end(), 'Text'); inner = src[m.end():end]
738
+ n.lines = _runs(inner); n.raw = bool(re.search(r"[^\s<>]\s*\n\s*[^\s<>]", inner)); i = after; continue
739
+ if name == 'svg' and not selfc:
740
+ for k in ('width', 'height'):
741
+ a = re.search(r"\b" + k + r"=[\"']?\{?(\d+(?:\.\d+)?)", attrs)
742
+ if a and k not in n.st: n.st[k] = a.group(1)
743
+ end, after = _close_at(src, m.end(), 'svg')
744
+ n.lines = [attrs, src[m.end():end]]
745
+ i = after; continue
746
+ if not selfc and name not in _LEAF: stack.append(n)
747
+ i = m.end()
748
+ return root
749
+
750
+ def _inherit(st, parent):
751
+ """Font context a node passes to its children: (fontSize, lineHeight, letterSpacing, family)."""
752
+ fs, lh, ls, fam = parent
753
+ return (_px(st.get('fontSize')) or fs, _px(st.get('lineHeight')) or lh,
754
+ _px(st.get('letterSpacing')) if st.get('letterSpacing') is not None else ls,
755
+ str(st.get('fontFamily') or fam).strip("'\""))
756
+
757
+ def _line_w(runs, ctx):
758
+ fs, _lh, ls, fam = ctx
759
+ w = 0.0
760
+ for text, sst in runs:
761
+ f = _px(sst.get('fontSize')) or fs
762
+ sp = _px(sst.get('letterSpacing')) if sst.get('letterSpacing') is not None else ls
763
+ mono = 'Courier' in str(sst.get('fontFamily') or fam)
764
+ w += sum(_advance(c, mono) for c in text) * f + (sp or 0.0) * len(text)
765
+ return w
766
+
767
+ def _flow(n): return [k for k in n.kids if str(k.st.get('position', '')).strip("'\"") != 'absolute']
768
+
769
+ def _max_w(n, ctx, avail=None):
770
+ """Width the node wants when nothing forces it to wrap (flexbox max-content)."""
771
+ st = n.st
772
+ ex = _px(st.get('width'), avail)
773
+ pt, pr, pb, pl = _edges(st, 'padding'); bt, br_, bb, bl = _border(st)
774
+ ml = _edges(st, 'margin')[3] + _edges(st, 'margin')[1]
775
+ if ex is not None: return ex + ml
776
+ if n.tag == 'Text':
777
+ c = _inherit(st, ctx)
778
+ return (max([_line_w(l, c) for l in n.lines] or [0.0]) + pl + pr + bl + br_ + ml)
779
+ if n.tag in _LEAF: return ml
780
+ kids, c = _flow(n), _inherit(st, ctx)
781
+ if not kids: return pl + pr + bl + br_ + ml
782
+ inner = [_max_w(k, c) for k in kids]
783
+ gap = _px(st.get('gap')) or 0.0
784
+ room = sum(inner) + gap * (len(inner) - 1) if 'row' in str(st.get('flexDirection', '')) else max(inner)
785
+ return room + pl + pr + bl + br_ + ml
786
+
787
+ def _min_w(n, ctx, avail=None):
788
+ """Width below which the node cannot shrink (nowrap text cannot shrink at all)."""
789
+ st = n.st
790
+ ex = _px(st.get('width'), avail)
791
+ if ex is not None: return ex
792
+ if n.tag == 'Text':
793
+ c = _inherit(st, ctx)
794
+ if 'nowrap' in str(st.get('whiteSpace', '')): return _max_w(n, ctx)
795
+ return max([max([_line_w([(w, s)], c) for w, s in l] or [0.0]) for l in n.lines] or [0.0]) * 0.12 + 1
796
+ if n.tag in _LEAF: return 0.0
797
+ kids, c = _flow(n), _inherit(st, ctx)
798
+ if not kids: return 0.0
799
+ pt, pr, pb, pl = _edges(st, 'padding'); bt, br_, bb, bl = _border(st)
800
+ inner = [_min_w(k, c) for k in kids]
801
+ return (sum(inner) if 'row' in str(st.get('flexDirection', '')) else max(inner)) + pl + pr + bl + br_
802
+
803
+ def _row_widths(kids, cw, gap, ctx):
804
+ """Resolve a row's child widths the way flexbox does: explicit, then flex share, then max-content shrunk to fit."""
805
+ n = len(kids)
806
+ basis, grow, fixed = [], [], []
807
+ for k in kids:
808
+ ex = _px(k.st.get('width'), cw)
809
+ fl = _px(str(k.st.get('flex', '')).split()[0]) if k.st.get('flex') is not None else None
810
+ basis.append(ex if ex is not None else (0.0 if fl is not None else _max_w(k, ctx)))
811
+ grow.append(fl); fixed.append(ex is not None)
812
+ free = cw - gap * max(0, n - 1) - sum(basis)
813
+ pool = [i for i, g in enumerate(grow) if g is not None]
814
+ out = list(basis)
815
+ if pool and free > 0:
816
+ units = sum(grow[i] or 1.0 for i in pool) or 1.0
817
+ for i in pool: out[i] += free * (grow[i] or 1.0) / units
818
+ elif free < 0:
819
+ shrink = [i for i in range(n) if not fixed[i]] or list(range(n))
820
+ total = sum(basis[i] for i in shrink) or 1.0
821
+ for i in shrink:
822
+ out[i] = max(_min_w(kids[i], ctx), basis[i] + free * basis[i] / total)
823
+ return out
824
+
825
+ def _fit(n, avail_w, avail_h, ctx, hits, sized=True):
826
+ """Lay the node out in (avail_w, avail_h); return the height it actually needs.
827
+ `sized`: the node has a definite width (its own, a stretched column parent's, or a flex share). Text inside an
828
+ auto-width container is measured by the WeCom compiler at its one-line width: if that is wider than the room the
829
+ row leaves it, the box is placed as ONE line but drawn wrapped, so it runs down behind the block below."""
830
+ import math
831
+ st = n.st
832
+ if _px(st.get('width'), avail_w) is not None: sized = True
833
+ pt, pr, pb, pl = _edges(st, 'padding'); bt, br_, bb, bl = _border(st)
834
+ mt, mr, mb, ml = _edges(st, 'margin')
835
+ absolute = str(st.get('position', '')).strip("'\"") == 'absolute'
836
+ w = _px(st.get('width'), avail_w)
837
+ if w is None and not absolute: w = None if avail_w is None else avail_w - ml - mr
838
+ if w is None and absolute and avail_w is not None:
839
+ lft, rgt = _px(st.get('left'), avail_w), _px(st.get('right'), avail_w)
840
+ if lft is not None and rgt is not None: w = avail_w - lft - rgt
841
+ cw = None if w is None else max(0.0, w - pl - pr - bl - br_)
842
+ h = _px(st.get('height'), avail_h)
843
+ ch = None if h is None else max(0.0, h - pt - pb - bt - bb)
844
+ c = _inherit(st, ctx)
845
+
846
+ if n.tag == 'Text':
847
+ fs, lh, _ls, _fam = c
848
+ if lh > 4: lh = lh / fs
849
+ nowrap = 'nowrap' in str(st.get('whiteSpace', ''))
850
+ rows, widest = 0, 0.0
851
+ for ln in n.lines:
852
+ wide = _line_w(ln, c); widest = max(widest, wide)
853
+ rows += 1 if (nowrap or not cw) else max(1, math.ceil(wide / cw - 1e-6))
854
+ if nowrap and cw and widest > cw + 1:
855
+ hits.append((n.line, f'{fs:.0f}px nowrap text needs {widest:.0f}px, its column is {cw:.0f}px wide', widest - cw))
856
+ elif not sized and cw and widest > cw + 1:
857
+ hits.append((n.line, f'{fs:.0f}px text in a container with no fixed width needs {widest:.0f}px on one line but only '
858
+ f'{cw:.0f}px is left in the row: the compiler places it as ONE line and it runs down behind the block '
859
+ f'below -- break it with <br /> so every line fits, or give the container a width', widest - cw))
860
+ if n.raw:
861
+ hits.append((n.line, 'a raw line break inside <Text>: JSX turns it into a space, not a new line -- write <br />', 0.0))
862
+ return rows * fs * lh * 1.2 + pt + pb + bt + bb + mt + mb # the compiler's line box is 1.2 x the declared lineHeight (measured on exports: 76px/1.1 -> 100.5px, 15px/1.55 -> 28px, no lineHeight -> 1.2em)
863
+
864
+ if n.tag in _LEAF: return (h if h is not None else 0.0) + mt + mb
865
+
866
+ kids = _flow(n)
867
+ row = 'row' in str(st.get('flexDirection', ''))
868
+ gap = _px(st.get('gap')) or 0.0
869
+ widths = _row_widths(kids, cw, gap, c) if (row and cw is not None) else [None if cw is None else cw] * len(kids)
870
+ heights = []
871
+ stretch = str(st.get('alignItems', 'stretch')).strip("'\"") == 'stretch'
872
+ for k, kw in zip(kids, widths):
873
+ ks = sized and (k.st.get('flex') is not None if row else stretch) # own width is picked up inside _fit
874
+ need = _fit(k, kw, ch, c, hits, ks)
875
+ fix = _px(k.st.get('height'), ch)
876
+ km = _edges(k.st, 'margin')
877
+ heights.append((fix + km[0] + km[2]) if fix is not None else need)
878
+ for k in n.kids:
879
+ if str(k.st.get('position', '')).strip("'\"") == 'absolute':
880
+ _fit(k, cw, ch, c, hits, k.st.get('left') is not None and k.st.get('right') is not None)
881
+ inner = (max(heights) if row else sum(heights) + gap * (len(heights) - 1)) if heights else 0.0
882
+ need = inner + pt + pb + bt + bb
883
+ if h is not None and need > h + max(2.0, 0.015 * h):
884
+ hits.append((n.line, f'the children need {need:.0f}px, this box is {h:.0f}px tall', need - h))
885
+ return (h if h is not None else need) + mt + mb
886
+
887
+ _ESC_NL = re.compile(r"""(['"])(?:[^'"\\\n]|\\.)*?\\n(?:[^'"\\\n]|\\.)*?\1""")
888
+
889
+ def _escaped_nl_hits(src):
890
+ r"""String literals holding a \n escape. The compiler renders it as a real line break, but the height
891
+ estimate only sees the interpolation ({d[1]}) or one joined line, so such a box silently comes out
892
+ taller than measured and runs over whatever sits below it. Write <br /> instead (or split the data)."""
893
+ hits = []
894
+ for m in _ESC_NL.finditer(src):
895
+ ln = src.count('\n', 0, m.start()) + 1
896
+ txt = m.group(0)
897
+ n = txt.count('\\n')
898
+ hits.append((ln, rf"a \n escape inside a string literal ({n} of them): the compiler draws it as a real "
899
+ rf"line break, but the height check counts ONE line -- the box renders taller than "
900
+ rf"measured and overlaps the block below. Use <br /> in the <Text>, or split the value "
901
+ rf"into separate <Text> elements: {txt[:58]}", 0.0))
902
+ return hits
903
+
904
+ _BR_IN_STR = re.compile(r"""(['"])(?:[^'"\\\n]|\\.)*?<br\s*/?>(?:[^'"\\\n]|\\.)*?\1""")
905
+
906
+ def _in_jsx_text(src, pos):
907
+ """True when pos sits in JSX text (child text of a tag), not inside a {...} JS expression. A quote mark
908
+ there is a literal character, so a '<br />' next to it is a real JSX line break, not text in a string."""
909
+ depth, q, i = 0, '', 0
910
+ while i < pos:
911
+ ch = src[i]
912
+ if q:
913
+ if ch == '\\': i += 2; continue
914
+ if ch == q: q = ''
915
+ elif depth and ch in '\'"`': q = ch
916
+ elif ch == '{': depth += 1
917
+ elif ch == '}': depth = max(0, depth - 1)
918
+ i += 1
919
+ if depth: return False
920
+ k = pos - 1
921
+ while k >= 0 and src[k] not in '<>': k -= 1
922
+ return k >= 0 and src[k] == '>' # last tag bracket before pos is a closing '>': we are in text
923
+
924
+ def _br_in_string_hits(src):
925
+ r"""String literals holding a <br /> tag. <br /> only works in JSX text position (a direct child of
926
+ <Text>); inside a data-array string interpolated via {d[i]} it is inserted as PLAIN TEXT and the
927
+ six characters render verbatim on the page. Split the value into separate <Text> elements, or drop
928
+ the array and write the JSX out."""
929
+ hits = []
930
+ for m in _BR_IN_STR.finditer(src):
931
+ br = src.find('<br', m.start())
932
+ if br >= 0 and _in_jsx_text(src, br): continue # the <br /> is JSX text (quotes around it are literal characters): it works
933
+ ln = src.count('\n', 0, m.start()) + 1
934
+ txt = m.group(0)
935
+ hits.append((ln, f"a <br /> tag inside a string literal: interpolated strings are inserted as plain "
936
+ f"text, so the tag renders verbatim on the page -- split the value into separate "
937
+ f"<Text> elements or write the JSX out instead of a data array: {txt[:58]}", 0.0))
938
+ return hits
939
+
940
+ # ---- layer: absolutely positioned text vs. flow-laid-out content ---------------------------------
941
+ # The flow height check (_fit) and the canvas check (_abs_hits) each look at ONE coordinate system. A block
942
+ # pinned with bottom:/top: is placed without knowing where the flow actually put the title above it, so the
943
+ # two can land on the same pixels and both checks still say OK (seen on section pages: a lead-in pinned at
944
+ # bottom:158 sat right on top of a title the flow had pushed down to y 484). This pass lays the page out with
945
+ # real coordinates and reports every absolute text box that intersects FLOW text. Left alone on purpose: text over
946
+ # an svg / image backdrop and absolute blocks overlapping each other (Venn diagrams, badges). {[...].map(...)}
947
+ # over a literal array is unrolled first; a .map the parser cannot unroll makes it skip the page, not guess.
948
+ _VIS = ('Image', 'Chart', 'Table', 'svg', 'CodeBlock', 'Math', 'QRCode')
949
+
950
+ def _is_abs(n): return str(n.st.get('position', '')).strip("'\"") == 'absolute'
951
+
952
+ def _text_w(n, ctx, cw):
953
+ c = _inherit(n.st, ctx)
954
+ pl, pr = _edges(n.st, 'padding')[3], _edges(n.st, 'padding')[1]
955
+ ex = _px(n.st.get('width'), cw)
956
+ if ex is not None: return ex
957
+ want = max([_line_w(l, c) for l in n.lines] or [0.0]) + pl + pr
958
+ return want if cw is None else min(cw, want)
959
+
960
+ def _place(n, x, y, avail_w, avail_h, ctx, sized, layer, out):
961
+ """Lay n out with its border box at (x, y); append (x0, y0, x1, y1, line, layer, kind, fontSize) for every
962
+ Text / visual leaf. `layer` is None for flow content, otherwise the line of the absolute ancestor."""
963
+ st = n.st
964
+ if _px(st.get('width'), avail_w) is not None: sized = True
965
+ pt, pr, pb, pl = _edges(st, 'padding'); bt, br_, bb, bl = _border(st)
966
+ mt, mr, mb, ml = _edges(st, 'margin')
967
+ w = _px(st.get('width'), avail_w)
968
+ if w is None and not _is_abs(n) and avail_w is not None: w = avail_w - ml - mr
969
+ c = _inherit(st, ctx)
970
+ need = _fit(n, avail_w, avail_h, ctx, [], sized) - mt - mb
971
+ h = _px(st.get('height'), avail_h)
972
+ h = need if h is None else h
973
+ if n.tag == 'Text':
974
+ tw = _text_w(n, ctx, w if w is not None else avail_w)
975
+ op = _px(st.get('opacity'))
976
+ if not (c[0] >= 150 or (op is not None and op < 0.5)): # watermark numerals / ghosted text are decoration
977
+ out.append((x, y, x + tw, y + h, n.line, layer, 'Text', c[0]))
978
+ return
979
+ if n.tag in _LEAF:
980
+ if n.tag in _VIS and w is not None: out.append((x, y, x + w, y + h, n.line, layer, n.tag, 0.0))
981
+ if n.tag == 'svg' and layer is not None and w and h and len(n.lines) == 2:
982
+ for sx0, sy0, sx1, sy1 in _svg_shapes(n.lines[0], n.lines[1], w, h):
983
+ out.append((x + sx0, y + sy0, x + sx1, y + sy1, n.line, layer, 'deco', 0.0))
984
+ return
985
+ cw = None if w is None else max(0.0, w - pl - pr - bl - br_)
986
+ ch = max(0.0, h - pt - pb - bt - bb)
987
+ ox, oy = x + bl + pl, y + bt + pt
988
+ kids = _flow(n)
989
+ row = 'row' in str(st.get('flexDirection', ''))
990
+ gap = _px(st.get('gap')) or 0.0
991
+ widths = _row_widths(kids, cw, gap, c) if (row and cw is not None) else [cw] * len(kids)
992
+ stretch = str(st.get('alignItems', 'stretch')).strip("'\"") == 'stretch'
993
+ align = str(st.get('alignItems', 'stretch')).strip("'\"")
994
+ just = str(st.get('justifyContent', 'flex-start')).strip("'\"")
995
+ sizes = []
996
+ for k, kw in zip(kids, widths):
997
+ ks = sized and (k.st.get('flex') is not None if row else stretch)
998
+ km = _edges(k.st, 'margin')
999
+ fix = _px(k.st.get('height'), ch)
1000
+ kh = fix if fix is not None else _fit(k, kw, ch, c, [], ks) - km[0] - km[2]
1001
+ if row: kwid = kw if kw is not None else 0.0
1002
+ elif k.tag == 'Text': kwid = _text_w(k, c, kw)
1003
+ else:
1004
+ kwid = _px(k.st.get('width'), cw)
1005
+ kwid = kwid if kwid is not None else ((kw - km[1] - km[3]) if (kw is not None and stretch) else (_max_w(k, c) - km[1] - km[3]))
1006
+ sizes.append((kwid, kh, km, ks))
1007
+ main = [(s[0] + s[2][1] + s[2][3]) if row else (s[1] + s[2][0] + s[2][2]) for s in sizes]
1008
+ room = (cw if row else ch) or 0.0
1009
+ free = room - sum(main) - gap * max(0, len(main) - 1)
1010
+ lead, step = 0.0, gap
1011
+ if free > 0 and (row or _px(st.get('height'), avail_h) is not None):
1012
+ if just == 'center': lead = free / 2
1013
+ elif just == 'flex-end': lead = free
1014
+ elif just == 'space-between' and len(main) > 1: step = gap + free / (len(main) - 1)
1015
+ elif just == 'space-around' and main: lead = free / len(main) / 2; step = gap + free / len(main)
1016
+ cur = lead
1017
+ for k, kw, (kwid, kh, km, ks) in zip(kids, widths, sizes):
1018
+ if row:
1019
+ cross = ch if ch else max([s[1] + s[2][0] + s[2][2] for s in sizes] or [0.0])
1020
+ off = (cross - kh - km[0] - km[2]) / 2 if align == 'center' else (cross - kh - km[0] - km[2]) if align == 'flex-end' else 0.0
1021
+ _place(k, ox + cur + km[3], oy + max(0.0, off) + km[0], kw, ch, c, ks, layer, out)
1022
+ cur += kwid + km[1] + km[3] + step
1023
+ else:
1024
+ off = ((cw or 0) - kwid - km[1] - km[3]) / 2 if align == 'center' else ((cw or 0) - kwid - km[1] - km[3]) if align == 'flex-end' else 0.0
1025
+ _place(k, ox + max(0.0, off) + km[3], oy + cur + km[0], kw, ch, c, ks, layer, out)
1026
+ cur += kh + km[0] + km[2] + step
1027
+ pw = w if w is not None else (avail_w or 0.0)
1028
+ for k in n.kids:
1029
+ if not _is_abs(k): continue
1030
+ ks_ = k.st
1031
+ kw_ = _px(ks_.get('width'), pw)
1032
+ lft, rgt = _px(ks_.get('left'), pw), _px(ks_.get('right'), pw)
1033
+ if kw_ is None and lft is not None and rgt is not None: kw_ = pw - lft - rgt
1034
+ if kw_ is None: kw_ = _max_w(k, c)
1035
+ kh_ = _px(ks_.get('height'), h)
1036
+ if kh_ is None: kh_ = _fit(k, kw_, h, c, [], True)
1037
+ top, bot = _px(ks_.get('top'), h), _px(ks_.get('bottom'), h)
1038
+ ax = x + (lft if lft is not None else (pw - rgt - kw_) if rgt is not None else bl + pl)
1039
+ ay = y + (top if top is not None else (h - bot - kh_) if bot is not None else bt + pt)
1040
+ _place(k, ax, ay, kw_, kh_, c, True, layer if layer is not None else k.line, out)
1041
+
1042
+ def _match(src, i, o, c):
1043
+ """Index just past the bracket that closes src[i] (== o), skipping string literals."""
1044
+ depth, q, j = 0, '', i
1045
+ while j < len(src):
1046
+ ch = src[j]
1047
+ if q:
1048
+ if ch == '\\': j += 2; continue
1049
+ if ch == q: q = ''
1050
+ elif ch in '\'"`': q = ch
1051
+ elif ch == o: depth += 1
1052
+ elif ch == c:
1053
+ depth -= 1
1054
+ if not depth: return j + 1
1055
+ j += 1
1056
+ return -1
1057
+
1058
+ def _split_top(s):
1059
+ out, cur, depth, q = [], '', 0, ''
1060
+ for ch in s:
1061
+ if q:
1062
+ cur += ch
1063
+ if ch == q: q = ''
1064
+ continue
1065
+ if ch in '\'"`': q = ch; cur += ch; continue
1066
+ if ch in '([{': depth += 1
1067
+ elif ch in ')]}': depth -= 1
1068
+ if ch == ',' and depth == 0: out.append(cur); cur = ''; continue
1069
+ cur += ch
1070
+ if cur.strip(): out.append(cur)
1071
+ return [x.strip() for x in out if x.strip()]
1072
+
1073
+ def _lit(v):
1074
+ v = v.strip()
1075
+ return v[1:-1] if len(v) >= 2 and v[0] == v[-1] and v[0] in '\'"`' else None
1076
+
1077
+ _MAP = re.compile(r"\{\s*\[")
1078
+ def _expand_maps(src):
1079
+ """Unroll {[literal, ...].map((d, i) => ( <JSX/> ))} into N copies of the JSX with d[k] / d.key / i filled
1080
+ in, so the layout pass sees the real row count and the real strings. Returns None when a .map cannot be
1081
+ unrolled (variable array, nested function body) -- the caller then skips the page instead of guessing."""
1082
+ for _ in range(50):
1083
+ m = _MAP.search(src)
1084
+ if not m: break
1085
+ a0 = m.end() - 1; a1 = _match(src, a0, '[', ']')
1086
+ if a1 < 0: return None
1087
+ mm = re.match(r"\s*\.map\(\s*\(?\s*(\w+)\s*(?:,\s*(\w+)\s*)?\)?\s*=>\s*\(", src[a1:])
1088
+ if not mm: return None
1089
+ b0 = a1 + mm.end() - 1; b1 = _match(src, b0, '(', ')')
1090
+ if b1 < 0: return None
1091
+ tail = re.match(r"\s*\)\s*\}", src[b1:])
1092
+ if not tail: return None
1093
+ var, idx, body = mm.group(1), mm.group(2), src[b0 + 1:b1 - 1]
1094
+ rows = []
1095
+ for k, el in enumerate(_split_top(src[a0 + 1:a1 - 1])):
1096
+ vals = {}
1097
+ if el.startswith('['):
1098
+ for n, v in enumerate(_split_top(el[1:-1])): vals[f'{var}[{n}]'] = _lit(v)
1099
+ elif el.startswith('{'):
1100
+ for kv in _split_top(el[1:-1]):
1101
+ if ':' in kv:
1102
+ kk, vv = kv.split(':', 1); vals[f'{var}.{kk.strip().strip(chr(39) + chr(34))}'] = _lit(vv)
1103
+ else: vals[var] = _lit(el)
1104
+ b = body
1105
+ if idx: b = re.sub(r"\b" + idx + r"\b(?=\s*(?:[=!<>]=?=?|\)|\}|\+|-|\*))", str(k), b)
1106
+ b = re.sub(r"\{\s*" + re.escape(var) + r"(\[\d+\]|\.\w+)?\s*\}",
1107
+ lambda q: (vals.get(var + (q.group(1) or '')) or 'X' * 6).replace('<', '&lt;'), b)
1108
+ rows.append(b)
1109
+ src = src[:m.start()] + '\n'.join(rows) + src[b1 + tail.end():]
1110
+ if '.map(' in src or '=>' in src: return None
1111
+ # leftover JS the tag parser cannot read (ternaries, comparisons, method calls) -> the layout would be a guess
1112
+ if re.search(r"\?[^{}]*:|\b\d+\s*[<>]=?\s*\d+|\{[^{}]*\.\w+\([^{}]*\}", src): return None
1113
+ return src
1114
+
1115
+ _SHAPE = re.compile(r"<(rect|circle|ellipse)\b([^>]*)/?>")
1116
+ def _svg_shapes(attrs, inner, w, h):
1117
+ """Solid decoration shapes inside an absolutely positioned svg, in page pixels relative to the svg box.
1118
+ Kept: rect / circle / ellipse that are filled (colour or pattern), at least 24px on both sides and cover
1119
+ less than half of the svg -- i.e. a corner mark, a bar, a stripe block. Dropped: backdrop rects, hairlines,
1120
+ sparkle dots, outline-only rings, faint (< 0.3 opacity) shapes, anything inside <defs> / <pattern>."""
1121
+ vb = re.search(r"viewBox=['\"]\s*([-\d.]+)[\s,]+([-\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)", attrs)
1122
+ vx, vy, vw, vh = (float(v) for v in vb.groups()) if vb else (0.0, 0.0, w, h)
1123
+ if not vw or not vh: return []
1124
+ kx, ky = w / vw, h / vh
1125
+ sop = re.search(r"\bopacity:\s*([\d.]+)", attrs)
1126
+ if sop and float(sop.group(1)) < 0.3: return [] # the whole svg is a faint watermark
1127
+ inner = re.sub(r"<g\b[^>]*\bfill=['\"]none['\"][^>]*>.*?</g>", '', inner, flags=re.S) # outline-only groups
1128
+ inner = re.sub(r"<defs\b.*?</defs>|<pattern\b.*?</pattern>|<clipPath\b.*?</clipPath>|<mask\b.*?</mask>", '', inner, flags=re.S)
1129
+ if re.search(r"<g\b[^>]*transform", inner): return [] # moved groups: geometry is not where it is written
1130
+ out = []
1131
+ for m in _SHAPE.finditer(inner):
1132
+ tag, a = m.group(1), m.group(2)
1133
+ if re.search(r"\b(?:x|y|width|height|cx|cy|r|rx|ry)=['\"][^'\"]*%", a): continue # percent geometry
1134
+ def f(k, d=None):
1135
+ q = re.search(r"\b" + k + r"=['\"]\{?\s*([-\d.]+)", a)
1136
+ return float(q.group(1)) if q else d
1137
+ fill = re.search(r"\bfill=['\"]([^'\"]*)", a)
1138
+ if (fill and fill.group(1).strip().lower() in ('none', 'transparent')) or 'transform' in a: continue
1139
+ op = f('opacity', 1.0); fo = f('fillOpacity', 1.0)
1140
+ if op * fo < 0.3: continue
1141
+ if tag == 'rect':
1142
+ x0, y0, ww, hh = f('x', 0.0), f('y', 0.0), f('width'), f('height')
1143
+ if ww is None or hh is None: continue
1144
+ else:
1145
+ cx, cy = f('cx', 0.0), f('cy', 0.0)
1146
+ rx = f('r') if tag == 'circle' else f('rx'); ry = f('r') if tag == 'circle' else f('ry')
1147
+ if rx is None or ry is None: continue
1148
+ x0, y0, ww, hh = cx - rx, cy - ry, 2 * rx, 2 * ry
1149
+ if ww * hh >= 0.5 * vw * vh: continue # backdrop
1150
+ if ww * kx < 24 or hh * ky < 24: continue # hairline / dot
1151
+ out.append(((x0 - vx) * kx, (y0 - vy) * ky, (x0 - vx + ww) * kx, (y0 - vy + hh) * ky))
1152
+ return out
1153
+
1154
+ def _layer_hits(src):
1155
+ hits = []
1156
+ if '.map(' in src or '=>' in src:
1157
+ src = _expand_maps(src)
1158
+ if src is None: return hits # data the static parser cannot unroll: stay silent rather than guess
1159
+ for top in _parse(src).kids:
1160
+ if top.tag != 'Slide': continue
1161
+ boxes = []
1162
+ _place(top, 0.0, 0.0, _px(top.st.get('width')) or 1280.0, _px(top.st.get('height')) or 720.0,
1163
+ (16.0, 1.0, 0.0, ''), True, None, boxes)
1164
+ seen = set()
1165
+ for i, a in enumerate(boxes):
1166
+ for b in boxes[i + 1:]:
1167
+ if a[5] == b[5]: continue # same layer: the flow keeps them apart
1168
+ if 'deco' in (a[6], b[6]):
1169
+ d_, t_ = (a, b) if a[6] == 'deco' else (b, a)
1170
+ if t_[6] != 'Text' or t_[5] is not None: continue # only flow text is checked against decoration
1171
+ dx = min(a[2], b[2]) - max(a[0], b[0]); dy = min(a[3], b[3]) - max(a[1], b[1])
1172
+ if dx < 8 or dy < 4 or (d_[4], t_[4]) in seen: continue
1173
+ seen.add((d_[4], t_[4]))
1174
+ hits.append((t_[4], f"{t_[7]:.0f}px text at x {t_[0]:.0f}-{t_[2]:.0f} y {t_[1]:.0f}-{t_[3]:.0f} runs {dx:.0f}px into the "
1175
+ f"decoration drawn by the svg of line {d_[4]} (a shape at x {d_[0]:.0f}-{d_[2]:.0f} y {d_[1]:.0f}-{d_[3]:.0f}). "
1176
+ f"Keep text left of it: give the text a width (maxWidth is ignored by the compiler) or break it with <br />", dx))
1177
+ continue
1178
+ if a[5] is not None and b[5] is not None: continue # two absolute blocks (Venn circles, badges) overlap on purpose
1179
+ if a[6] != 'Text' or b[6] != 'Text': continue # svg / picture under text is a backdrop by design; text on text never is
1180
+ ab, fl = (a, b) if a[5] is not None and (b[5] is None or a[5] > b[5]) else (b, a)
1181
+ dx = min(a[2], b[2]) - max(a[0], b[0]); dy = min(a[3], b[3]) - max(a[1], b[1])
1182
+ if dx < 4 or dy < 4: continue
1183
+ key = (ab[4], fl[4])
1184
+ if key in seen: continue
1185
+ seen.add(key)
1186
+ other = 'flow' if fl[5] is None else f'absolute (line {fl[5]})'
1187
+ hits.append((ab[4], f"absolutely positioned {ab[6]} at y {ab[1]:.0f}-{ab[3]:.0f} x {ab[0]:.0f}-{ab[2]:.0f} lands on "
1188
+ f"the {other} {fl[6]} of line {fl[4]} (y {fl[1]:.0f}-{fl[3]:.0f}): {dy:.0f}px of the two overlap. "
1189
+ f"Absolute offsets do not move when the flow above grows -- put this block in the flow "
1190
+ f"(drop position/top/bottom, give it a marginTop) or delete it; nudging bottom/top a few px is not a fix, "
1191
+ f"the next longer title lands on it again", dy))
1192
+ return hits
1193
+
1194
+ def _slide_size_hits(src):
1195
+ hits = []
1196
+ for top in _parse(src).kids:
1197
+ if top.tag != 'Slide': continue
1198
+ w, h = _px(top.st.get('width')) or 1280.0, _px(top.st.get('height')) or 720.0 # unset = the 1280x720 default
1199
+ if (w, h) != (1280.0, 720.0):
1200
+ hits.append((top.line, f"<Slide> is {w:.0f}x{h:.0f}: every page must be exactly 1280x720 (and keep the shell's padding) "
1201
+ f"-- another size is stretched on export and its coordinates no longer line up with the other pages", 0.0))
1202
+ return hits
1203
+
1204
+ _BARE_LT = re.compile(r"<(?![A-Za-z/>!])")
1205
+ def _bare_lt_hits(src):
1206
+ """A '<' in JSX text that does not open a tag ('<500ms', '< 5%', '<=') -- the compiler reads it as the start
1207
+ of an element and addjsx fails with JSX_PARSE_ERROR after the page has already been submitted."""
1208
+ hits = []
1209
+ for m in _BARE_LT.finditer(src):
1210
+ if not _in_jsx_text(src, m.start()): continue
1211
+ ln = src.count('\n', 0, m.start()) + 1
1212
+ hits.append((ln, f"a bare '<' in text ({src[m.start():m.start() + 12].splitlines()[0]!r}) is parsed as a tag and "
1213
+ f"addjsx fails with JSX_PARSE_ERROR -- write {{'<'}} or reword it (低于 / 小于)", 0.0))
1214
+ return hits
1215
+
1216
+ def _iter_nodes(n):
1217
+ for k in n.kids:
1218
+ yield k
1219
+ yield from _iter_nodes(k)
1220
+
1221
+ def _loose_rows(n, cw, ctx, hits):
1222
+ """Rows whose children all carry a hard-coded width and together leave most of the row unused."""
1223
+ st = n.st
1224
+ pr, pl = _edges(st, 'padding')[1], _edges(st, 'padding')[3]
1225
+ br_, bl = _border(st)[1], _border(st)[3]
1226
+ w = _px(st.get('width'), cw)
1227
+ inner = None if (w if w is not None else cw) is None else max(0.0, (w if w is not None else cw) - pl - pr - bl - br_)
1228
+ c = _inherit(st, ctx); kids = _flow(n); gap = _px(st.get('gap')) or 0.0
1229
+ row = 'row' in str(st.get('flexDirection', ''))
1230
+ if row and inner and len(kids) >= 2 and all(_px(k.st.get('width'), inner) is not None for k in kids):
1231
+ used = sum(_px(k.st.get('width'), inner) for k in kids) + gap * (len(kids) - 1)
1232
+ if used < 0.86 * inner and inner - used > 90:
1233
+ hits.append((n.line, f'this row of {len(kids)} blocks has every width hard-coded: {used:.0f}px used of the '
1234
+ f'{inner:.0f}px row, so {inner - used:.0f}px stays empty at the right. Replace the fixed '
1235
+ f"`width:` on each block with `flex: 1` so the row fills the region", 0.0))
1236
+ ws = _row_widths(kids, inner, gap, c) if (row and inner is not None) else [inner] * len(kids)
1237
+ for k, kw in zip(kids, ws): _loose_rows(k, kw, c, hits)
1238
+ for k in n.kids:
1239
+ if str(k.st.get('position', '')).strip("'\"") == 'absolute': _loose_rows(k, inner, c, hits)
1240
+
1241
+ def _slack_hits(src):
1242
+ """The mirror image of the fit check: content that falls far SHORT of the region it was given. A body region
1243
+ 1216x551 holding blocks that stop at 780px wide and 327px tall renders as a page with its lower right third
1244
+ blank -- every box passes fit and contrast on its own, so nothing downstream ever sees it. Only regions big
1245
+ enough to be a body are looked at, and only when they hold a real set of blocks, so a cover or a section
1246
+ divider (a few lines on purpose) is never flagged."""
1247
+ hits = []
1248
+ for top in _parse(src).kids:
1249
+ if top.tag != 'Slide': continue
1250
+ ctx = (16.0, 1.0, 0.0, '')
1251
+ for box in _iter_nodes(top):
1252
+ if box.tag != 'Box' or str(box.st.get('position', '')).strip("'\"") != 'absolute': continue
1253
+ w, h = _px(box.st.get('width'), 1280.0), _px(box.st.get('height'), 720.0)
1254
+ if not w or not h or w < 560 or h < 240: continue
1255
+ if sum(1 for k in _iter_nodes(box) if k.tag == 'Text') < 5: continue
1256
+ if not any(k.tag == 'Box' for k in _flow(box)): continue
1257
+ keep = box.st.get('height')
1258
+ box.st.pop('height', None)
1259
+ try: need = _fit(box, w, h, ctx, [])
1260
+ finally:
1261
+ if keep is not None: box.st['height'] = keep
1262
+ if h - need > max(70.0, 0.22 * h):
1263
+ hits.append((box.line, f'the blocks in this {w:.0f}x{h:.0f} region add up to {need:.0f}px tall, leaving '
1264
+ f'{h - need:.0f}px ({(h - need) / h:.0%}) of it empty at the bottom. Give the blocks '
1265
+ f'real height (taller padding, one more row of substance, a bigger lead paragraph) '
1266
+ f'or move a block here from another page -- do NOT just stretch a box with a fixed '
1267
+ f'height, and do not pad it with filler sentences', 0.0))
1268
+ _loose_rows(box, w, ctx, hits)
1269
+ return hits
1270
+
1271
+ def _fit_hits(src):
1272
+ hits = []
1273
+ for top in _parse(src).kids:
1274
+ if top.tag != 'Slide': continue
1275
+ _fit(top, _px(top.st.get('width')) or 1280.0, _px(top.st.get('height')) or 720.0,
1276
+ (16.0, 1.0, 0.0, ''), hits)
1277
+ hits += _slide_size_hits(src)
1278
+ hits += _slack_hits(src)
1279
+ hits += _layer_hits(src)
1280
+ hits += _escaped_nl_hits(src)
1281
+ hits += _br_in_string_hits(src)
1282
+ hits += _bare_lt_hits(src)
1283
+ return sorted(hits, key=lambda x: -x[2])
1284
+
1285
+ def fit(a):
1286
+ """Flag content that does not fit its container: text whose wrapped height is taller than the fixed-height
1287
+ box around it, nowrap text wider than its column, and any fixed-height box — up to the 720px Slide — whose
1288
+ children add up to more than it holds. Sizes are estimated from the type metrics the presets use."""
1289
+ bad = 0
1290
+ for p in a.pages:
1291
+ hits = _fit_hits(open(p, encoding='utf-8').read())
1292
+ print(('OVER ' if hits else 'OK ') + p)
1293
+ for ln, msg, over in hits[:12]:
1294
+ print(f' line {ln}: {msg}' + (f', over by {over:.0f}px' if over > 0 else ''))
1295
+ if any('lands on the' in m for _, m, _o in hits):
1296
+ print(' -> overlap: keep all text of a page in the flow (only decoration, footer and page number may be absolute); '
1297
+ 'a lead-in under a section / cover title goes right after the title with a marginTop, not pinned with bottom:')
1298
+ if any('stays empty' in m or 'empty at the bottom' in m for _, m, _o in hits):
1299
+ print(' -> this page is too EMPTY, not too full: fill the region instead of trimming. Fix it in one pass '
1300
+ '(flex: 1 on the row, more substance per block) -- nudging sizes a few px at a time will not close it')
1301
+ if any('lands on the' not in m and 'empty' not in m for _, m, _o in hits):
1302
+ print(' -> cut the words, drop a block or split the page; do not shrink the type or edit the shell')
1303
+ bad += bool(hits)
1304
+ sys.exit(1 if bad else 0)
1305
+
1306
+ # ---------------------------------------------------------------- template: build the deck's shells FROM a user's PPT template
1307
+ # A user who sends a template wants the deck to look like it. The pool sets cannot do that, so this path reads the
1308
+ # template's own masters and layouts and turns them into shells: decorations (shapes, EMF art, small pictures) are
1309
+ # rasterised into one transparent layer per page type, full-bleed pictures stay pictures, placeholders become 〔…〕
1310
+ # slots at the template's own positions, sizes, colours and fonts. Standard library only (Pillow / sips optional).
1311
+ _TNS = {'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
1312
+ 'p': 'http://schemas.openxmlformats.org/presentationml/2006/main',
1313
+ 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
1314
+ 'rel': 'http://schemas.openxmlformats.org/package/2006/relationships'}
1315
+ _T_RID = '{%s}id' % _TNS['r']; _T_EMBED = '{%s}embed' % _TNS['r']
1316
+ _T_ALIAS = {'tx1': 'dk1', 'bg1': 'lt1', 'tx2': 'dk2', 'bg2': 'lt2'}
1317
+ _T_SERIF = re.compile(r'宋|明朝|明體|仿宋|楷|隶|魏碑|serif(?!.*sans)|song|ming|mincho|kai|fangsong|times|georgia|garamond|'
1318
+ r'cambria|palatino|baskerville|bodoni|didot|playfair|caslon|minion|book antiqua|century schoolbook|'
1319
+ r'noto serif|source han serif|思源宋', re.I)
1320
+ _T_MONO = re.compile(r'mono|courier|consolas|menlo|code', re.I)
1321
+ _T_FILLER = re.compile(r'单击此处|点击此处|单击添加|点击添加|点击输入|单击输入|添加标题|输入标题|添加文字|添加文本|添加章节|'
1322
+ r'请在此|在此输入|此处输入|此处添加|请输入|请替换|替换为您|输入您的|您的内容|您的标题|标题文字|示例文字|'
1323
+ r'内容标题|建议\s*\d+\s*字|文字内容|内容填充|XX公司|XXX|20XX|\d{4}\.XX|XX\.XX|click to (?:add|edit)|'
1324
+ r'lorem ipsum|your (?:title|text|company|logo)|add (?:your )?(?:title|text)|text here|title here|sample text', re.I)
1325
+ # fontFamily whitelist of the WeCom renderer (design-principle.md §5) and the names templates use for them
1326
+ _T_FONTS = {'microsoft yahei': 'Microsoft YaHei', '微软雅黑': 'Microsoft YaHei', 'microsoft yahei ui': 'Microsoft YaHei',
1327
+ 'pingfang sc': 'PingFang SC', '苹方': 'PingFang SC', 'pingfang': 'PingFang SC', 'hiragino sans gb': 'Hiragino Sans GB',
1328
+ '冬青黑体简体中文': 'Hiragino Sans GB', 'simhei': 'SimHei', '黑体': 'SimHei', 'tencentsans w3': 'TencentSans W3',
1329
+ 'tencentsans w7': 'TencentSans W7', 'tencent sans w3': 'TencentSans W3', 'tencent sans w7': 'TencentSans W7',
1330
+ '腾讯体 w3': 'TencentSans W3', '腾讯体 w7': 'TencentSans W7', '腾讯体': 'TencentSans W7', 'stsong': 'STSong',
1331
+ '华文宋体': 'STSong', 'simsun': 'SimSun', '宋体': 'SimSun', 'stfangsong': 'STFangsong', '华文仿宋': 'STFangsong',
1332
+ 'stkaiti': 'STKaiti', '华文楷体': 'STKaiti', 'arial': 'Arial', 'calibri': 'Calibri', 'times new roman': 'Times New Roman',
1333
+ 'courier new': 'Courier New'}
1334
+
1335
+
1336
+ class _TplPkg:
1337
+ def __init__(self, path):
1338
+ import zipfile
1339
+ try: self.z = zipfile.ZipFile(path)
1340
+ except (zipfile.BadZipFile, FileNotFoundError, IsADirectoryError) as e:
1341
+ sys.stderr.write(f'not a pptx package ({e}). An old .ppt has to be converted to .pptx first.\n'); sys.exit(2)
1342
+ self.names = set(self.z.namelist())
1343
+ if 'ppt/presentation.xml' not in self.names:
1344
+ sys.stderr.write('no ppt/presentation.xml inside -- not a PowerPoint file\n'); sys.exit(2)
1345
+ self._x = {}
1346
+
1347
+ def xml(self, name):
1348
+ from xml.etree import ElementTree as ET
1349
+ if name not in self._x: self._x[name] = ET.fromstring(self.z.read(name)) if name in self.names else None
1350
+ return self._x[name]
1351
+
1352
+ def raw(self, name):
1353
+ return self.z.read(name).decode('utf-8', 'replace') if name in self.names else ''
1354
+
1355
+ def rels(self, name):
1356
+ """{rId: (type_tail, target_part)} for one part."""
1357
+ import posixpath
1358
+ d, b = posixpath.split(name); root = self.xml(posixpath.join(d, '_rels', b + '.rels')); out = {}
1359
+ for r in (root.findall('rel:Relationship', _TNS) if root is not None else []):
1360
+ if r.get('TargetMode') == 'External': continue
1361
+ out[r.get('Id')] = (r.get('Type', '').rsplit('/', 1)[-1], posixpath.normpath(posixpath.join(d, r.get('Target'))))
1362
+ return out
1363
+
1364
+ def first_rel(self, name, kind):
1365
+ return next((t for k, t in self.rels(name).values() if k == kind), None)
1366
+
1367
+
1368
+ def _tpl_chroma(h):
1369
+ _, s, l = _rgb_to_hsl(h); return s >= 0.25 and 0.08 < l < 0.92
1370
+
1371
+ def _tpl_color(el, scheme):
1372
+ """(hex, alpha 0-1) of a fill-like element: srgbClr / schemeClr (through the theme) / sysClr / prstClr,
1373
+ with lumMod / lumOff / tint / shade / alpha applied. None when there is no colour."""
1374
+ if el is None: return None
1375
+ for tag in ('srgbClr', 'schemeClr', 'sysClr', 'prstClr'):
1376
+ c = el.find('a:' + tag, _TNS)
1377
+ if c is not None: break
1378
+ else: return None
1379
+ if tag == 'srgbClr': h = (c.get('val') or '').upper()
1380
+ elif tag == 'schemeClr': v = c.get('val'); h = scheme.get(_T_ALIAS.get(v, v), '')
1381
+ elif tag == 'sysClr': h = (c.get('lastClr') or '').upper()
1382
+ else: h = {'black': '000000', 'white': 'FFFFFF', 'red': 'FF0000', 'blue': '0000FF', 'green': '008000'}.get(c.get('val'), '')
1383
+ if not re.fullmatch(r'[0-9A-F]{6}', h): return None
1384
+ alpha = 1.0; hu, s, l = _rgb_to_hsl(h); mod = False
1385
+ for m in c:
1386
+ k = m.tag.split('}')[1]; v = int(m.get('val', '100000')) / 100000
1387
+ if k == 'lumMod': l *= v; mod = True
1388
+ elif k == 'lumOff': l += v; mod = True
1389
+ elif k == 'tint': l = l + (1 - l) * (1 - v); mod = True
1390
+ elif k == 'shade': l *= v; mod = True
1391
+ elif k == 'alpha': alpha = v
1392
+ if mod: h = _hsl_to_rgb(hu, s, max(0.0, min(1.0, l)))
1393
+ return h, alpha
1394
+
1395
+
1396
+
1397
+
1398
+ def _tpl_xfrm(el):
1399
+ x = el.find('.//a:xfrm', _TNS)
1400
+ if x is None: return None
1401
+ off, ext = x.find('a:off', _TNS), x.find('a:ext', _TNS)
1402
+ try: return int(off.get('x')), int(off.get('y')), int(ext.get('cx')), int(ext.get('cy'))
1403
+ except (AttributeError, TypeError, ValueError): return None
1404
+
1405
+
1406
+ # ---- raster: PNG in / out, scanline polygon fill (all stdlib) -----------------------------------
1407
+ def _png_decode(b):
1408
+ """(w, h, RGBA bytearray) for an 8-bit non-interlaced PNG (grey / RGB / palette / grey+alpha / RGBA), else None."""
1409
+ import zlib
1410
+ if b[:8] != b'\x89PNG\r\n\x1a\n': return None
1411
+ import struct
1412
+ i, idat, plte, trns, w, h, depth, ctype, inter = 8, [], None, None, 0, 0, 0, 0, 0
1413
+ while i + 8 <= len(b):
1414
+ n = int.from_bytes(b[i:i + 4], 'big'); t = b[i + 4:i + 8]; d = b[i + 8:i + 8 + n]; i += 12 + n
1415
+ if t == b'IHDR': w, h = struct.unpack('>II', d[:8]); depth, ctype, inter = d[8], d[9], d[12]
1416
+ elif t == b'PLTE': plte = d
1417
+ elif t == b'tRNS': trns = d
1418
+ elif t == b'IDAT': idat.append(d)
1419
+ elif t == b'IEND': break
1420
+ ch = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(ctype)
1421
+ if not w or depth != 8 or not ch or (ctype == 3 and not plte): return None
1422
+ raw = zlib.decompress(b''.join(idat)); pos = 0
1423
+ out = bytearray(w * h * 4)
1424
+
1425
+ def unfilter(pw, ph):
1426
+ """Undo the per-scanline filter for one pass, pw pixels wide and ph rows tall."""
1427
+ nonlocal pos
1428
+ stride = pw * ch; prev = bytearray(stride)
1429
+ for _y in range(ph):
1430
+ f = raw[pos]; row = bytearray(raw[pos + 1:pos + 1 + stride]); pos += 1 + stride
1431
+ if f == 1:
1432
+ for x in range(ch, stride): row[x] = (row[x] + row[x - ch]) & 255
1433
+ elif f == 2: row = bytearray((p + q) & 255 for p, q in zip(row, prev))
1434
+ elif f == 3:
1435
+ for x in range(stride): row[x] = (row[x] + ((row[x - ch] if x >= ch else 0) + prev[x]) // 2) & 255
1436
+ elif f == 4:
1437
+ for x in range(stride):
1438
+ l_ = row[x - ch] if x >= ch else 0; c_ = prev[x - ch] if x >= ch else 0; u = prev[x]
1439
+ p = l_ + u - c_; pa, pb, pc = abs(p - l_), abs(p - u), abs(p - c_)
1440
+ row[x] = (row[x] + (l_ if pa <= pb and pa <= pc else u if pb <= pc else c_)) & 255
1441
+ prev = row; yield row
1442
+
1443
+ def px4(row, x):
1444
+ if ctype == 6: return row[4 * x:4 * x + 4]
1445
+ if ctype == 2: return bytes((row[3 * x], row[3 * x + 1], row[3 * x + 2], 255))
1446
+ if ctype == 3:
1447
+ k = row[x]
1448
+ if 3 * k + 2 >= len(plte): return b'\0\0\0\0'
1449
+ return bytes((plte[3 * k], plte[3 * k + 1], plte[3 * k + 2], trns[k] if trns and k < len(trns) else 255))
1450
+ if ctype == 0: return bytes((row[x], row[x], row[x], 255))
1451
+ return bytes((row[2 * x], row[2 * x], row[2 * x], row[2 * x + 1]))
1452
+
1453
+ if inter:
1454
+ # Adam7: the image arrives as seven passes of scattered pixels. Icon-sized art inside PPT templates is
1455
+ # routinely saved interlaced, and refusing it meant the decoration was dropped on every machine without
1456
+ # Pillow or sips -- which is the normal case in the agent's sandbox.
1457
+ for xs, ys, xst, yst in ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)):
1458
+ pw, ph = max(0, -(-(w - xs) // xst)), max(0, -(-(h - ys) // yst))
1459
+ if not pw or not ph: continue
1460
+ for y, row in enumerate(unfilter(pw, ph)):
1461
+ o = (ys + y * yst) * w * 4
1462
+ for x in range(pw):
1463
+ q = o + (xs + x * xst) * 4; out[q:q + 4] = px4(row, x)
1464
+ return w, h, out
1465
+ for y, row in enumerate(unfilter(w, h)):
1466
+ o = y * w * 4
1467
+ if ctype == 6: out[o:o + w * 4] = row
1468
+ elif ctype == 2:
1469
+ for x in range(w): out[o + 4 * x:o + 4 * x + 4] = bytes((row[3 * x], row[3 * x + 1], row[3 * x + 2], 255))
1470
+ elif ctype == 3:
1471
+ for x in range(w):
1472
+ k = row[x]; a = trns[k] if trns and k < len(trns) else 255
1473
+ out[o + 4 * x:o + 4 * x + 4] = bytes((plte[3 * k], plte[3 * k + 1], plte[3 * k + 2], a))
1474
+ elif ctype == 0:
1475
+ for x in range(w): out[o + 4 * x:o + 4 * x + 4] = bytes((row[x], row[x], row[x], 255))
1476
+ else:
1477
+ for x in range(w): out[o + 4 * x:o + 4 * x + 4] = bytes((row[2 * x], row[2 * x], row[2 * x], row[2 * x + 1]))
1478
+ return w, h, out
1479
+
1480
+ def _png_encode(w, h, px):
1481
+ import zlib, struct
1482
+ stride = w * 4; raw = bytearray()
1483
+ for y in range(h): raw.append(0); raw += px[y * stride:(y + 1) * stride]
1484
+ def chunk(t, d): return struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d) & 0xffffffff)
1485
+ return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0))
1486
+ + chunk(b'IDAT', zlib.compress(bytes(raw), 6)) + chunk(b'IEND', b''))
1487
+
1488
+ class _Canvas:
1489
+ """A transparent RGBA bitmap the band furniture is painted into. Only two operations are needed now that the
1490
+ template's body shapes are no longer traced: fill a polygon (the EMF art and the thin rules) and composite a
1491
+ picture (logos, page backgrounds)."""
1492
+
1493
+ def __init__(s, w, h): s.w, s.h, s.px, s.used = w, h, bytearray(w * h * 4), False
1494
+
1495
+ def fill(s, polys, rgb, alpha=1.0, evenodd=False):
1496
+ edges = []
1497
+ for pts in polys:
1498
+ for i in range(len(pts)):
1499
+ (x0, y0), (x1, y1) = pts[i], pts[(i + 1) % len(pts)]
1500
+ if y0 == y1: continue
1501
+ d = 1
1502
+ if y0 > y1: x0, y0, x1, y1, d = x1, y1, x0, y0, -1
1503
+ edges.append((y0, y1, x0, (x1 - x0) / (y1 - y0), d))
1504
+ if not edges: return
1505
+ r, g, b = (int(rgb[i:i + 2], 16) for i in (0, 2, 4)); a = max(0, min(255, round(alpha * 255)))
1506
+ if a == 0: return
1507
+ col = bytes((r, g, b, a)); s.used = True
1508
+ y0 = max(0, int(min(e[0] for e in edges))); y1 = min(s.h - 1, int(max(e[1] for e in edges)) + 1)
1509
+ for y in range(y0, y1 + 1):
1510
+ yc = y + 0.5; xs = sorted((ex + (yc - ey0) * k, d) for ey0, ey1, ex, k, d in edges if ey0 <= yc < ey1)
1511
+ if not xs: continue
1512
+ spans = []
1513
+ if evenodd: spans = [(xs[i][0], xs[i + 1][0]) for i in range(0, len(xs) - 1, 2)]
1514
+ else:
1515
+ wnd = 0; start = 0.0
1516
+ for x, d in xs:
1517
+ prev = wnd; wnd += d
1518
+ if prev == 0 and wnd != 0: start = x
1519
+ elif prev != 0 and wnd == 0: spans.append((start, x))
1520
+ row = y * s.w * 4
1521
+ for xa, xb in spans:
1522
+ ia, ib = max(0, int(round(xa))), min(s.w, int(round(xb)))
1523
+ if ib <= ia: continue
1524
+ if a == 255: s.px[row + ia * 4:row + ib * 4] = col * (ib - ia)
1525
+ else:
1526
+ for x in range(ia, ib): s._over(row + 4 * x, r, g, b, a)
1527
+
1528
+ def _over(s, o, r, g, b, a):
1529
+ da = s.px[o + 3]
1530
+ if da == 0: s.px[o:o + 4] = bytes((r, g, b, a)); return
1531
+ oa = a + da * (255 - a) // 255
1532
+ if oa == 0: return
1533
+ for k, v in enumerate((r, g, b)): s.px[o + k] = (v * a + s.px[o + k] * da * (255 - a) // 255) // oa
1534
+ s.px[o + 3] = oa
1535
+
1536
+ def stroke(s, pts, closed, width, rgb, alpha=1.0):
1537
+ import math
1538
+ hw = max(0.5, width / 2); quads = []
1539
+ seq = pts + [pts[0]] if closed else pts
1540
+ for (x0, y0), (x1, y1) in zip(seq, seq[1:]):
1541
+ dx, dy = x1 - x0, y1 - y0; L = math.hypot(dx, dy)
1542
+ if L == 0: continue
1543
+ nx, ny = -dy / L * hw, dx / L * hw
1544
+ quads.append([(x0 + nx, y0 + ny), (x1 + nx, y1 + ny), (x1 - nx, y1 - ny), (x0 - nx, y0 - ny)])
1545
+ for q in quads: s.fill([q], rgb, alpha)
1546
+
1547
+ def blit(s, w, h, src, x, y, dw, dh):
1548
+ """Composite an RGBA picture (w x h) onto the canvas box (x, y, dw, dh), nearest neighbour, source over."""
1549
+ x, y, dw, dh = int(round(x)), int(round(y)), max(1, int(round(dw))), max(1, int(round(dh)))
1550
+ for ty in range(max(0, y), min(s.h, y + dh)):
1551
+ sy = min(h - 1, (ty - y) * h // dh); row = ty * s.w * 4
1552
+ for tx in range(max(0, x), min(s.w, x + dw)):
1553
+ sx = min(w - 1, (tx - x) * w // dw); o = (sy * w + sx) * 4; a = src[o + 3]
1554
+ if a == 0: continue
1555
+ s.used = True
1556
+ if a == 255: s.px[row + 4 * tx:row + 4 * tx + 4] = src[o:o + 4]
1557
+ else: s._over(row + 4 * tx, src[o], src[o + 1], src[o + 2], a)
1558
+
1559
+
1560
+
1561
+
1562
+ def _bezier(p0, p1, p2, p3, n=16):
1563
+ out = []
1564
+ for i in range(1, n + 1):
1565
+ t = i / n; u = 1 - t
1566
+ out.append((u ** 3 * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t ** 3 * p3[0],
1567
+ u ** 3 * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t ** 3 * p3[1]))
1568
+ return out
1569
+
1570
+
1571
+ # ---- EMF (classic GDI records) -> drawing ops ------------------------------------------------------
1572
+ def _emf_ops(b):
1573
+ """Parse a GDI EMF into ([(kind, polys, rgb, alpha, evenodd, width)], frame=(x0, y0, x1, y1) in device units).
1574
+ kind 'fill' or 'stroke'. Clipping, text and embedded bitmaps are ignored. None if this is not an EMF."""
1575
+ import struct
1576
+ if len(b) < 88 or struct.unpack('<I', b[:4])[0] != 1 or b[40:44] != b' EMF': return None
1577
+ bounds = struct.unpack('<4i', b[8:24]); frame = struct.unpack('<4i', b[24:40])
1578
+ devw, devh, mmw, mmh = struct.unpack('<4i', b[72:88])
1579
+ if mmw > 0 and mmh > 0 and devw > 0 and devh > 0:
1580
+ kx, ky = devw / (mmw * 100), devh / (mmh * 100)
1581
+ fr = (frame[0] * kx, frame[1] * ky, frame[2] * kx, frame[3] * ky)
1582
+ else: fr = tuple(float(v) for v in bounds)
1583
+ if fr[2] - fr[0] < 1 or fr[3] - fr[1] < 1: fr = tuple(float(v) for v in bounds)
1584
+ st = {'wo': (0, 0), 'we': None, 'vo': (0, 0), 've': None, 'm': (1, 0, 0, 1, 0, 0), 'brush': ('FFFFFF', 1.0),
1585
+ 'pen': ('000000', 1.0), 'mode': 1}
1586
+ stock = {0: ('brush', ('FFFFFF', 1.0)), 1: ('brush', ('C0C0C0', 1.0)), 2: ('brush', ('808080', 1.0)),
1587
+ 3: ('brush', ('404040', 1.0)), 4: ('brush', ('000000', 1.0)), 5: ('brush', None),
1588
+ 6: ('pen', ('FFFFFF', 1.0)), 7: ('pen', ('000000', 1.0)), 8: ('pen', None)}
1589
+ objs, saved, ops = {}, [], []
1590
+ figs, cur, inpath, pos = [], [], False, (0, 0)
1591
+ def ref(c): return '%02X%02X%02X' % (c & 255, (c >> 8) & 255, (c >> 16) & 255)
1592
+ def T(x, y):
1593
+ a, bb, c, d, e, f = st['m']; xw, yw = x * a + y * c + e, x * bb + y * d + f
1594
+ if st['we'] and st['ve'] and st['we'][0] and st['we'][1]:
1595
+ return ((xw - st['wo'][0]) * st['ve'][0] / st['we'][0] + st['vo'][0], (yw - st['wo'][1]) * st['ve'][1] / st['we'][1] + st['vo'][1])
1596
+ return (xw - st['wo'][0] + st['vo'][0], yw - st['wo'][1] + st['vo'][1])
1597
+ def penw():
1598
+ w = st['pen'][2] if st['pen'] and len(st['pen']) > 2 else 1
1599
+ if st['we'] and st['ve'] and st['we'][0]: w = w * abs(st['ve'][0] / st['we'][0])
1600
+ return max(1.0, w)
1601
+ def emit(polys, fill, stroke, closed=True):
1602
+ polys = [p for p in polys if len(p) >= 2]
1603
+ if not polys: return
1604
+ if fill and st['brush']: ops.append(('fill', [p for p in polys if len(p) >= 3], st['brush'][0], st['brush'][1], st['mode'] == 1, 0))
1605
+ if stroke and st['pen']: ops.append(('stroke', polys, st['pen'][0], st['pen'][1], closed, penw()))
1606
+ def pts16(d, n, off): return [T(*struct.unpack('<hh', d[off + 4 * i:off + 4 * i + 4])) for i in range(n)]
1607
+ def pts32(d, n, off): return [T(*struct.unpack('<ii', d[off + 8 * i:off + 8 * i + 8])) for i in range(n)]
1608
+ i = 0
1609
+ while i + 8 <= len(b):
1610
+ t, n = struct.unpack('<II', b[i:i + 8]); d = b[i + 8:i + n]
1611
+ if n < 8: break
1612
+ try:
1613
+ if t == 14: break
1614
+ elif t == 9: st['we'] = struct.unpack('<ii', d[:8])
1615
+ elif t == 10: st['wo'] = struct.unpack('<ii', d[:8])
1616
+ elif t == 11: st['ve'] = struct.unpack('<ii', d[:8])
1617
+ elif t == 12: st['vo'] = struct.unpack('<ii', d[:8])
1618
+ elif t == 19: st['mode'] = struct.unpack('<I', d[:4])[0]
1619
+ elif t == 35: st['m'] = struct.unpack('<6f', d[:24])
1620
+ elif t == 36:
1621
+ m = struct.unpack('<6f', d[:24]); mode = struct.unpack('<I', d[24:28])[0]
1622
+ def mul(p, q): return (p[0] * q[0] + p[1] * q[2], p[0] * q[1] + p[1] * q[3], p[2] * q[0] + p[3] * q[2],
1623
+ p[2] * q[1] + p[3] * q[3], p[4] * q[0] + p[5] * q[2] + q[4], p[4] * q[1] + p[5] * q[3] + q[5])
1624
+ st['m'] = (1, 0, 0, 1, 0, 0) if mode == 1 else mul(m, st['m']) if mode == 2 else mul(st['m'], m) if mode == 3 else m
1625
+ elif t == 33: saved.append(dict(st))
1626
+ elif t == 34:
1627
+ k = struct.unpack('<i', d[:4])[0]
1628
+ for _ in range(min(len(saved), abs(k) if k < 0 else 1)): st.update(saved.pop())
1629
+ elif t == 39:
1630
+ ih, style, col = struct.unpack('<III', d[:12]); objs[ih] = ('brush', None if style == 1 else (ref(col), 1.0))
1631
+ elif t == 38:
1632
+ ih, style, w, _h, col = struct.unpack('<IIiiI', d[:20]); objs[ih] = ('pen', None if style & 15 == 5 else (ref(col), 1.0, w))
1633
+ elif t == 95:
1634
+ ih = struct.unpack('<I', d[:4])[0]; style, w, _bs, col = struct.unpack('<IIII', d[20:36])
1635
+ objs[ih] = ('pen', None if style & 15 == 5 else (ref(col), 1.0, w))
1636
+ elif t == 37:
1637
+ ih = struct.unpack('<I', d[:4])[0]
1638
+ o = stock.get(ih & 0x7FFFFFFF) if ih & 0x80000000 else objs.get(ih)
1639
+ if o: st[o[0]] = o[1]
1640
+ elif t == 40: objs.pop(struct.unpack('<I', d[:4])[0], None)
1641
+ elif t == 59: inpath, figs, cur = True, [], []
1642
+ elif t == 60: inpath = False; figs.append(cur) if cur else None; cur = []
1643
+ elif t == 68: inpath, figs, cur = False, [], []
1644
+ elif t == 27:
1645
+ pos = T(*struct.unpack('<ii', d[:8]))
1646
+ if inpath:
1647
+ if len(cur) > 1: figs.append(cur)
1648
+ cur = [pos]
1649
+ elif t == 54:
1650
+ p = T(*struct.unpack('<ii', d[:8]))
1651
+ if inpath: cur = cur or [pos]; cur.append(p)
1652
+ else: emit([[pos, p]], False, True, False)
1653
+ pos = p
1654
+ elif t == 61:
1655
+ if inpath and cur: figs.append(cur); cur = []
1656
+ elif t in (88, 89, 5, 6):
1657
+ cnt = struct.unpack('<I', d[16:20])[0]; ps = pts16(d, cnt, 20) if t in (88, 89) else pts32(d, cnt, 20)
1658
+ if t in (89, 6): seg = ps
1659
+ else:
1660
+ seg, p0 = [], pos
1661
+ for k in range(0, len(ps) - 2, 3): seg += _bezier(p0, ps[k], ps[k + 1], ps[k + 2]); p0 = ps[k + 2]
1662
+ if inpath: cur = cur or [pos]; cur += seg
1663
+ else: emit([[pos] + seg], False, True, False)
1664
+ pos = ps[-1] if ps else pos
1665
+ elif t in (85, 86, 87, 2, 3, 4):
1666
+ cnt = struct.unpack('<I', d[16:20])[0]; ps = pts16(d, cnt, 20) if t in (85, 86, 87) else pts32(d, cnt, 20)
1667
+ if t in (85, 2):
1668
+ seg = [ps[0]] if ps else []
1669
+ for k in range(1, len(ps) - 2, 3): seg += _bezier(seg[-1], ps[k], ps[k + 1], ps[k + 2])
1670
+ ps = seg
1671
+ if inpath:
1672
+ if len(cur) > 1: figs.append(cur)
1673
+ figs.append(ps); cur = []
1674
+ else: emit([ps], t in (86, 3), True, t in (86, 3))
1675
+ elif t in (91, 90, 8, 7):
1676
+ npoly, _tot = struct.unpack('<II', d[16:24]); counts = struct.unpack('<%dI' % npoly, d[24:24 + 4 * npoly])
1677
+ off = 24 + 4 * npoly; polys = []
1678
+ for c in counts:
1679
+ polys.append(pts16(d, c, off) if t in (91, 90) else pts32(d, c, off)); off += c * (4 if t in (91, 90) else 8)
1680
+ if inpath: figs += polys
1681
+ else: emit(polys, t in (91, 8), True, t in (91, 8))
1682
+ elif t in (43, 42):
1683
+ l_, tp, r_, bt = struct.unpack('<4i', d[:16])
1684
+ if t == 43: ps = [T(l_, tp), T(r_, tp), T(r_, bt), T(l_, bt)]
1685
+ else:
1686
+ import math
1687
+ cx, cy, rx, ry = (l_ + r_) / 2, (tp + bt) / 2, (r_ - l_) / 2, (bt - tp) / 2
1688
+ ps = [T(cx + rx * math.cos(k * math.pi / 32), cy + ry * math.sin(k * math.pi / 32)) for k in range(64)]
1689
+ emit([ps], True, True)
1690
+ elif t in (62, 63, 64):
1691
+ polys = figs + ([cur] if len(cur) > 1 else [])
1692
+ emit(polys, t in (62, 63), t in (63, 64), True); figs, cur = [], []
1693
+ elif t == 67: figs, cur = [], [] # SELECTCLIPPATH consumes the path; clipping itself is ignored
1694
+ except struct.error:
1695
+ pass
1696
+ i += n
1697
+ return ops, fr
1698
+
1699
+
1700
+ # ---- preset shapes -> polygon (shape-local coordinates, w x h) --------------------------------------
1701
+
1702
+
1703
+
1704
+
1705
+ _ROLE_RX = [('cover', re.compile(r'封面|cover|title slide|标题幻灯片|^标题$', re.I)),
1706
+ ('end', re.compile(r'结束|结尾|封底|致谢|谢谢|感谢|thank|closing|ending|^end', re.I)),
1707
+ ('toc', re.compile(r'目录|table of contents|\bcontents\b|\bagenda\b|议程|catalog', re.I)),
1708
+ ('section', re.compile(r'扉页|章节|节标题|过渡|section|divider|chapter|part\b|transition', re.I)),
1709
+ ('content', re.compile(r'内容|正文|content|title and|标题和|仅标题|title only|text|body', re.I))]
1710
+ _SKIP_PH = ('dt', 'ftr', 'hdr', 'sldImg', 'clipArt', 'chart', 'tbl', 'dgm', 'media', 'pic', 'obj')
1711
+
1712
+
1713
+ class _Tpl:
1714
+ def __init__(s, path):
1715
+ import os
1716
+ s.path = path; s.pkg = pkg = _TplPkg(path); pres = pkg.xml('ppt/presentation.xml'); sz = pres.find('p:sldSz', _TNS)
1717
+ s.W, s.H = (int(sz.get('cx')), int(sz.get('cy'))) if sz is not None else (12192000, 6858000)
1718
+ s.kx, s.ky = 1280 / s.W, 720 / s.H; s.pt = 720 / (s.H / 12700) # px per EMU (x, y) and px per point
1719
+ r = s.W / s.H
1720
+ s.ratio = '16:9' if abs(r - 16 / 9) < 0.03 else '4:3' if abs(r - 4 / 3) < 0.03 else '16:10' if abs(r - 1.6) < 0.03 else f'{r:.2f}:1'
1721
+ prels = pkg.rels('ppt/presentation.xml')
1722
+ s.slides = [prels[x.get(_T_RID)][1] for x in pres.findall('p:sldIdLst/p:sldId', _TNS) if x.get(_T_RID) in prels]
1723
+ s.masters = [prels[m.get(_T_RID)][1] for m in pres.findall('p:sldMasterIdLst/p:sldMasterId', _TNS) if m.get(_T_RID) in prels] \
1724
+ or sorted(n for n in pkg.names if re.match(r'ppt/slideMasters/slideMaster\d+\.xml$', n))
1725
+ s.layouts = sorted((n for n in pkg.names if re.match(r'ppt/slideLayouts/slideLayout\d+\.xml$', n)),
1726
+ key=lambda n: int(re.findall(r'\d+', n)[-1]))
1727
+ s.layout_of = {x: pkg.first_rel(x, 'slideLayout') for x in s.slides}
1728
+ s.master_of = {l: pkg.first_rel(l, 'slideMaster') or (s.masters[0] if s.masters else None) for l in s.layouts}
1729
+ s.scheme, s.tfonts = {}, {}
1730
+ troot = pkg.xml((pkg.first_rel(s.masters[0], 'theme') if s.masters else None) or 'ppt/theme/theme1.xml')
1731
+ if troot is not None:
1732
+ cs = troot.find('.//a:clrScheme', _TNS)
1733
+ for el in (cs if cs is not None else []):
1734
+ c = el.find('a:srgbClr', _TNS); x = el.find('a:sysClr', _TNS)
1735
+ v = c.get('val') if c is not None else x.get('lastClr') if x is not None else None
1736
+ if v: s.scheme[el.tag.split('}')[1]] = v.upper()
1737
+ for kind in ('major', 'minor'):
1738
+ f = troot.find(f'.//a:{kind}Font', _TNS)
1739
+ if f is None: continue
1740
+ for script in ('latin', 'ea'):
1741
+ e = f.find(f'a:{script}', _TNS)
1742
+ if e is not None and e.get('typeface'): s.tfonts[f'{kind}_{script}'] = e.get('typeface')
1743
+ hans = f.find("a:font[@script='Hans']", _TNS)
1744
+ if not s.tfonts.get(f'{kind}_ea') and hans is not None and hans.get('typeface'): s.tfonts[f'{kind}_ea'] = hans.get('typeface')
1745
+ s.notes = []
1746
+
1747
+ def name(s, part):
1748
+ root = s.pkg.xml(part); c = root.find('p:cSld', _TNS) if root is not None else None
1749
+ return (c.get('name') if c is not None else '') or ''
1750
+
1751
+ # --- colours / fonts actually used
1752
+ def painted(s):
1753
+ import collections
1754
+ counter = collections.Counter()
1755
+ used = sorted({l for l in s.layout_of.values() if l}) or s.layouts
1756
+ for part in s.slides + used + s.masters:
1757
+ src = re.sub(r'<p:style>.*?</p:style>', '', s.pkg.raw(part), flags=re.S)
1758
+ for v in re.findall(r'<a:srgbClr val="([0-9A-Fa-f]{6})"', src): counter[v.upper()] += 1
1759
+ for v in re.findall(r'<a:schemeClr val="(\w+)"', src):
1760
+ h = s.scheme.get(_T_ALIAS.get(v, v))
1761
+ if h: counter[h] += 1
1762
+ return counter
1763
+
1764
+ def font(s, tf):
1765
+ """A template typeface -> (whitelisted fontFamily, class)."""
1766
+ m = re.match(r'\+(mj|mn)-(lt|ea|cs)', tf or '')
1767
+ if m: tf = s.tfonts.get(('major' if m.group(1) == 'mj' else 'minor') + '_' + ('latin' if m.group(2) == 'lt' else 'ea'), '')
1768
+ tf = (tf or '').strip()
1769
+ cls = 'mono' if _T_MONO.search(tf) else 'serif' if _T_SERIF.search(tf) else 'sans'
1770
+ hit = _T_FONTS.get(tf.lower())
1771
+ if hit: return hit, cls
1772
+ if not tf: return 'Microsoft YaHei', 'sans'
1773
+ return {'serif': 'STSong', 'mono': 'Courier New'}.get(cls, 'Microsoft YaHei'), cls
1774
+
1775
+ # --- geometry
1776
+ def box(s, g, small_keep_ratio=False):
1777
+ """EMU (x, y, w, h) -> canvas px. A 4:3 template is stretched to 16:9 horizontally; small art keeps its ratio
1778
+ (left-anchored on the left half, right-anchored on the right half) so logos and badges are not squashed."""
1779
+ x, y, w, h = g
1780
+ X, Y, Wd, Hd = x * s.kx, y * s.ky, w * s.kx, h * s.ky
1781
+ if small_keep_ratio and abs(s.kx - s.ky) > 1e-9 and w * s.ky < 0.25 * 1280:
1782
+ nw = w * s.ky
1783
+ X = X if (x + w / 2) < s.W / 2 else (x + w) * s.kx - nw
1784
+ Wd = nw
1785
+ return X, Y, Wd, Hd
1786
+
1787
+ def elements(s, part, ox=0.0, oy=0.0, sx=1.0, sy=1.0, tree=None):
1788
+ """Flatten a part's shape tree into (kind, el, emu_box, rot, flipH, flipV) with group transforms applied."""
1789
+ root = s.pkg.xml(part)
1790
+ if tree is None:
1791
+ tree = root.find('p:cSld/p:spTree', _TNS) if root is not None else None
1792
+ if tree is None: return []
1793
+ out = []
1794
+ for el in tree:
1795
+ tag = el.tag.split('}')[1]
1796
+ if tag == 'grpSp':
1797
+ x = el.find('p:grpSpPr/a:xfrm', _TNS)
1798
+ try:
1799
+ off, ext = x.find('a:off', _TNS), x.find('a:ext', _TNS); co, ce = x.find('a:chOff', _TNS), x.find('a:chExt', _TNS)
1800
+ gx, gy, gw, gh = int(off.get('x')), int(off.get('y')), int(ext.get('cx')), int(ext.get('cy'))
1801
+ cx, cy, cw, chh = int(co.get('x')), int(co.get('y')), int(ce.get('cx')) or 1, int(ce.get('cy')) or 1
1802
+ nsx, nsy = sx * gw / cw, sy * gh / chh
1803
+ out += s.elements(part, ox + (gx - cx * gw / cw) * sx, oy + (gy - cy * gh / chh) * sy, nsx, nsy, el)
1804
+ except (AttributeError, TypeError, ValueError):
1805
+ s.notes.append(f'{part}: a group without a usable transform was skipped')
1806
+ continue
1807
+ if tag not in ('sp', 'pic', 'cxnSp'): continue
1808
+ xf = el.find('p:spPr/a:xfrm', _TNS) if tag != 'pic' else el.find('p:spPr/a:xfrm', _TNS)
1809
+ g = None
1810
+ if xf is not None and xf.find('a:off', _TNS) is not None:
1811
+ o, e = xf.find('a:off', _TNS), xf.find('a:ext', _TNS)
1812
+ g = (ox + int(o.get('x')) * sx, oy + int(o.get('y')) * sy, int(e.get('cx')) * sx, int(e.get('cy')) * sy)
1813
+ rot = int(xf.get('rot', '0')) / 60000 if xf is not None else 0.0
1814
+ fh = xf is not None and xf.get('flipH') == '1'; fv = xf is not None and xf.get('flipV') == '1'
1815
+ out.append((tag, el, g, rot, fh, fv))
1816
+ return out
1817
+
1818
+ def ph(s, el):
1819
+ p = el.find('p:nvSpPr/p:nvPr/p:ph', _TNS)
1820
+ if p is None: return None
1821
+ return (p.get('type') or 'body'), p.get('idx')
1822
+
1823
+ def inherited_ph(s, master, phinfo):
1824
+ """The master placeholder a layout placeholder inherits from (same type, else same idx, else body)."""
1825
+ typ, idx = phinfo; best = None
1826
+ for kind, el, g, *_ in s.elements(master):
1827
+ p = s.ph(el) if kind == 'sp' else None
1828
+ if not p: continue
1829
+ t2 = p[0]
1830
+ if t2 == typ or (typ in ('ctrTitle',) and t2 == 'title') or (typ == 'subTitle' and t2 == 'body'):
1831
+ return el, g
1832
+ if best is None and t2 == 'body': best = (el, g)
1833
+ return best or (None, None)
1834
+
1835
+ def text_style(s, chain, master, kind):
1836
+ """Font size px, colour, bold, family, class, align, anchor, line spacing and insets for a placeholder,
1837
+ resolved along layout ph (list style, then the prompt text's own run) -> master ph -> master txStyles."""
1838
+ A = lambda tag: '{%s}%s' % (_TNS['a'], tag)
1839
+ mroot = s.pkg.xml(master) if master else None
1840
+ sty = None
1841
+ if mroot is not None:
1842
+ key = 'titleStyle' if kind in ('title', 'ctrTitle') else 'bodyStyle' if kind in ('body', 'subTitle', 'obj') else 'otherStyle'
1843
+ sty = mroot.find(f'p:txStyles/p:{key}', _TNS)
1844
+ paras, runs = [], [] # (lvl1pPr-like, run-properties-like) in priority order
1845
+ for c in chain:
1846
+ if c is None: continue
1847
+ lv = c.find('.//a:lstStyle/a:lvl1pPr', _TNS); pp = c.find('.//a:p/a:pPr', _TNS)
1848
+ for e in (lv, pp):
1849
+ if e is not None: paras.append(e); d = e.find('a:defRPr', _TNS); runs.append(d) if d is not None else None
1850
+ for e in (c.find('.//a:r/a:rPr', _TNS), c.find('.//a:endParaRPr', _TNS)):
1851
+ if e is not None: runs.append(e)
1852
+ if sty is not None:
1853
+ lv = sty.find('a:lvl1pPr', _TNS)
1854
+ if lv is not None:
1855
+ paras.append(lv); d = lv.find('a:defRPr', _TNS); runs.append(d) if d is not None else None
1856
+ def first(items, fn):
1857
+ for e in items:
1858
+ v = fn(e)
1859
+ if v is not None: return v
1860
+ return None
1861
+ sz = first(runs, lambda e: e.get('sz'))
1862
+ col = first(runs, lambda e: _tpl_color(e.find('a:solidFill', _TNS), s.scheme) if e.find('a:solidFill', _TNS) is not None else None)
1863
+ b = first(runs, lambda e: e.get('b'))
1864
+ tf = first(runs, lambda e: next((x.get('typeface') for x in (e.find('a:ea', _TNS), e.find('a:latin', _TNS))
1865
+ if x is not None and x.get('typeface')), None))
1866
+ algn = first(paras, lambda e: e.get('algn'))
1867
+ lns = first(paras, lambda e: (lambda p: int(p.get('val')) / 100000 if p is not None and p.get('val') else None)(e.find('a:lnSpc/a:spcPct', _TNS)))
1868
+ bp = [c.find('.//a:bodyPr', _TNS) for c in chain if c is not None]; bp = [e for e in bp if e is not None]
1869
+ anchor = first(bp, lambda e: e.get('anchor'))
1870
+ ins = {k: first(bp, lambda e, k=k: e.get(k)) for k in ('lIns', 'tIns', 'rIns', 'bIns')}
1871
+ fam, cls = s.font(tf or ('+mj-ea' if kind in ('title', 'ctrTitle') else '+mn-ea'))
1872
+ return {'size': round((int(sz) / 100 if sz else (44 if kind in ('title', 'ctrTitle') else 18)) * s.pt),
1873
+ 'color': (col or (s.scheme.get('dk1', '000000'), 1.0))[0], 'bold': b in ('1', 'true'), 'family': fam,
1874
+ 'class': cls, 'align': {'ctr': 'center', 'r': 'right', 'just': 'left', 'dist': 'center'}.get(algn or 'l', 'left'),
1875
+ 'anchor': {'ctr': 'center', 'b': 'flex-end'}.get(anchor or 't', 'flex-start'),
1876
+ 'lh': max(0.9, min(1.5, lns or 1.0)),
1877
+ 'ins': tuple(int(ins[k]) if ins[k] is not None else d for k, d in
1878
+ (('lIns', 91440), ('tIns', 45720), ('rIns', 91440), ('bIns', 45720))),
1879
+ 'sample': ''.join(t.text or '' for t in (chain[0].iter(A('t')) if chain[0] is not None else [])).strip(),
1880
+ 'typeface': tf}
1881
+
1882
+ def bg_solid(s, part):
1883
+ root = s.pkg.xml(part); bg = root.find('p:cSld/p:bg', _TNS) if root is not None else None
1884
+ if bg is None: return None
1885
+ pr = bg.find('p:bgPr', _TNS)
1886
+ if pr is not None:
1887
+ sf = pr.find('a:solidFill', _TNS)
1888
+ if sf is not None: c = _tpl_color(sf, s.scheme); return ('color', c[0]) if c else None
1889
+ gf = pr.find('a:gradFill', _TNS)
1890
+ if gf is not None:
1891
+ cs = [c[0] for c in (_tpl_color(g, s.scheme) for g in gf.findall('.//a:gs', _TNS)) if c]
1892
+ if cs: return ('color', cs[0])
1893
+ blip = pr.find('a:blipFill/a:blip', _TNS)
1894
+ if blip is not None:
1895
+ t = s.pkg.rels(part).get(blip.get(_T_EMBED)); return ('image', t[1]) if t else None
1896
+ ref = bg.find('p:bgRef', _TNS)
1897
+ if ref is not None: c = _tpl_color(ref, s.scheme); return ('color', c[0]) if c else None
1898
+ return None
1899
+
1900
+ def slide_sig(s, sl):
1901
+ """(text shape count, biggest font pt, joined text) of one of the template's own slides -- used to tell
1902
+ a cover / section / toc / thanks page apart from a content page by what is actually on it."""
1903
+ n, big, txt = 0, 0, []
1904
+ for kind, el, g, *_ in s.elements(sl):
1905
+ if kind != 'sp': continue
1906
+ t = ''.join(x.text or '' for x in el.iter('{%s}t' % _TNS['a'])).strip()
1907
+ if not t: continue
1908
+ if s.ph(el) and s.ph(el)[0] in _SKIP_PH: continue
1909
+ n += 1; txt.append(t)
1910
+ for tag in ('rPr', 'defRPr'):
1911
+ for e in el.iter('{%s}%s' % (_TNS['a'], tag)):
1912
+ if e.get('sz'): big = max(big, int(e.get('sz')) / 100)
1913
+ return n, big, ' '.join(txt)
1914
+
1915
+ def rep_slides(s, uses):
1916
+ """One representative slide per page type, read off the template's own slides. A template whose design lives
1917
+ on the slides (text boxes, no layout placeholders -- the common case for Chinese templates) is only
1918
+ reproducible from these; the layouts are empty."""
1919
+ sig = {sl: s.slide_sig(sl) for sl in s.slides}
1920
+ out = {}
1921
+ if s.slides: out['cover'] = s.slides[0]
1922
+ for sl in s.slides:
1923
+ if 'toc' not in out and _ROLE_RX[2][1].search(sig[sl][2]): out['toc'] = sl
1924
+ sect = [sl for sl in s.slides[1:] if sig[sl][0] <= 6 and
1925
+ (re.search(r'\bPART\b|\bCHAPTER\b|章节', sig[sl][2], re.I) or
1926
+ (sig[sl][1] >= 40 and re.search(r'(?<!\d)\d{1,2}(?!\d)', sig[sl][2]))) and sl is not out.get('toc')]
1927
+ if sect: out['section'] = sect[0]
1928
+ last = s.slides[-1] if len(s.slides) > 1 else None
1929
+ if last is not None and last not in out.values() and (sig[last][0] <= 4 or
1930
+ re.search(r'thank|谢|感谢|结束', sig[last][2], re.I)): out['end'] = last
1931
+ body = [sl for sl in s.slides if sl not in out.values()]
1932
+ if body: out['content'] = max(body, key=lambda sl: sig[sl][0])
1933
+ return out
1934
+
1935
+ def roles(s):
1936
+ """Pick one layout per page type: the layout the template's own slides use for it, else the first name match."""
1937
+ named = {}
1938
+ for l in s.layouts:
1939
+ nm = s.name(l)
1940
+ for role, rx in _ROLE_RX:
1941
+ if rx.search(nm): named.setdefault(role, []).append(l); break
1942
+ uses = {}
1943
+ for i, x in enumerate(s.slides):
1944
+ l = s.layout_of.get(x)
1945
+ if l: uses.setdefault(l, []).append(i)
1946
+ out = {}
1947
+ for role in ('cover', 'toc', 'section', 'end'):
1948
+ cands = named.get(role, [])
1949
+ used = [l for l in cands if l in uses]
1950
+ if used: out[role] = min(used, key=lambda l: uses[l][0])
1951
+ elif cands: out[role] = cands[0]
1952
+ if 'cover' not in out and s.slides and s.layout_of.get(s.slides[0]): out['cover'] = s.layout_of[s.slides[0]]
1953
+ taken = set(out.values())
1954
+ def busy(l): # share of the canvas taken by pictures / picture placeholders
1955
+ a = 0.0
1956
+ for k, el, g, *_ in s.elements(l):
1957
+ p = s.ph(el) if k == 'sp' else None
1958
+ if g and (k == 'pic' or (p and p[0] in ('pic', 'clipArt', 'media'))): a += g[2] * g[3] / (s.W * s.H)
1959
+ return a
1960
+ pool = [l for l in s.layouts if l not in taken and s.has_title(l)] or [l for l in s.layouts if l not in taken]
1961
+ avoid = re.compile(r'图片|图像|插图|照片|picture|photo|image|quote|引用', re.I)
1962
+ plain = re.compile(r'仅标题|只有标题|title only|标题和内容|title and content|标题与内容', re.I)
1963
+ # the layout the template's own content slides use most is what "looks like the template"
1964
+ pool = [l for l in s.layouts if l not in taken and (s.has_title(l) or uses.get(l))] or [l for l in s.layouts if l not in taken]
1965
+ content = sorted(pool, key=lambda l: (busy(l) > 0.15, bool(avoid.search(s.name(l))), -len(uses.get(l, [])),
1966
+ not plain.search(s.name(l)), not _ROLE_RX[4][1].search(s.name(l)), s.layouts.index(l)))
1967
+ if content: out['content'] = content[0]
1968
+ elif s.layouts: out['content'] = s.layouts[0]
1969
+ reps = s.rep_slides(uses) # the template's own slide for each page type
1970
+ for role, sl in reps.items():
1971
+ l = s.layout_of.get(sl)
1972
+ if l and (role not in out or not s.has_title(out[role])): out[role] = l
1973
+ for role in reps:
1974
+ if role not in out and s.layouts: out[role] = s.layout_of.get(reps[role]) or s.layouts[0]
1975
+ return out, uses, reps
1976
+
1977
+ def has_title(s, layout):
1978
+ return any(s.ph(el) and s.ph(el)[0] in ('title', 'body', 'ctrTitle') for k, el, *_ in s.elements(layout) if k == 'sp')
1979
+
1980
+
1981
+ def _tpl_shrink(dec, max_side):
1982
+ """Nearest-neighbour downscale of a decoded (w, h, RGBA) picture. Good enough: the result is either composited
1983
+ at 1/8 scale to sample a colour, or drawn small into the decoration layer."""
1984
+ w, h, px = dec
1985
+ f = max(w, h) / float(max_side)
1986
+ if f <= 1.0: return dec
1987
+ nw, nh = max(1, int(w / f)), max(1, int(h / f))
1988
+ out = bytearray(nw * nh * 4)
1989
+ for y in range(nh):
1990
+ src, dst = min(h - 1, int(y * f)) * w * 4, y * nw * 4
1991
+ for x in range(nw):
1992
+ s = src + min(w - 1, int(x * f)) * 4
1993
+ out[dst:dst + 4] = px[s:s + 4]; dst += 4
1994
+ return nw, nh, out
1995
+
1996
+
1997
+ def _raster(data, ext, max_side=None):
1998
+ """Decode a picture to (w, h, RGBA). PNG natively; others via Pillow or sips."""
1999
+ dims = _dims_from_bytes(data)
2000
+ if ext == 'png' and dims and dims[0] * dims[1] <= 16_000_000:
2001
+ # Template decorations are routinely high-res art placed small -- a 1600px glow used as a 120px corner
2002
+ # piece. Handing those to Pillow / sips just because they need shrinking loses them outright wherever
2003
+ # neither exists, which is the common case; decode here and shrink instead.
2004
+ dec = _png_decode(data)
2005
+ if dec and max_side and max(dec[0], dec[1]) > max_side * 1.5: dec = _tpl_shrink(dec, max_side)
2006
+ if dec: return dec
2007
+ try:
2008
+ import io
2009
+ from PIL import Image
2010
+ im = Image.open(io.BytesIO(data)).convert('RGBA')
2011
+ if max_side: im.thumbnail((max_side, max_side))
2012
+ return im.size[0], im.size[1], bytearray(im.tobytes())
2013
+ except Exception: pass
2014
+ import shutil, subprocess, tempfile, os
2015
+ if not shutil.which('sips'): return None
2016
+ with tempfile.TemporaryDirectory() as d:
2017
+ src, dst = os.path.join(d, 'in.' + ext), os.path.join(d, 'out.png'); open(src, 'wb').write(data)
2018
+ cmd = ['sips', '-s', 'format', 'png'] + (['-Z', str(int(max_side))] if max_side else []) + [src, '--out', dst]
2019
+ r = subprocess.run(cmd, capture_output=True)
2020
+ return _png_decode(open(dst, 'rb').read()) if r.returncode == 0 and os.path.exists(dst) else None
2021
+
2022
+
2023
+ _BAND_TOP, _BAND_BOT = 0.22, 0.9 # header / footer bands: what a template parks there is page furniture
2024
+ _BAND_BAR = 48.0 # px: a filled shape thinner than this, inside a band, is a rule -- not a panel
2025
+ _BAND_PIC = 0.15 # share of the page above which a picture in a band is not furniture either
2026
+
2027
+
2028
+ def _tpl_page(tpl, role, layout, assets, uses, rep_slide=None):
2029
+ """One page type of the template -> a shell holding only what cannot be designed from scratch: the page
2030
+ background, and the art the template keeps in its header / footer bands (rules, logos, page furniture).
2031
+
2032
+ Shapes in the body are deliberately NOT traced. Tracing them is what produced the whole bug trail: bounding-box
2033
+ squares for every preset the rasteriser did not know, flat slabs for gradients, cut-out photos that lost their
2034
+ outline, cards without their shadow, and a cover whose small picture hung in mid-air once the bar behind it was
2035
+ dropped. The deck's own layout is designed from the template's palette and type instead, which is also what the
2036
+ template's own identity actually consists of once its background art is in place.
2037
+
2038
+ Returns dict(jsx, notes, files, area, bg, layout, layout_name, dropped)."""
2039
+ import os
2040
+ master = tpl.master_of.get(layout) or (tpl.masters[0] if tpl.masters else None)
2041
+ lroot = tpl.pkg.xml(layout)
2042
+ show_master = lroot is None or lroot.get('showMasterSp', '1') not in ('0', 'false')
2043
+ sample = [tpl.slides[i] for i in uses.get(layout, [])]
2044
+ rep = rep_slide if rep_slide is not None else (sample[0] if sample else None)
2045
+ # OOXML resolves a page's background slide -> layout -> master. Reading only the last two loses every template
2046
+ # that sets its art on the slide itself (a 'blank' layout with <p:bg> on slide1).
2047
+ bg = (tpl.bg_solid(rep) if rep is not None else None) or tpl.bg_solid(layout) \
2048
+ or (tpl.bg_solid(master) if master else None) or ('color', tpl.scheme.get('lt1', 'FFFFFF'))
2049
+ base = bg[1] if bg[0] == 'color' and bg[1] else tpl.scheme.get('lt1', 'FFFFFF')
2050
+ S = 2
2051
+ art = _Canvas(1280 * S, 720 * S) # the band furniture, one transparent layer per page type
2052
+ under = _Canvas(1280 * S, 720 * S) # a vector full-page background, painted below that layer
2053
+ notes, files, dropped, bgfiles = [], {}, [], []
2054
+ pics = [bg[1]] if bg[0] == 'image' and bg[1] else [] # full-bleed rasters, in z-order
2055
+ parts = ([master] if master and show_master and master != layout else []) + [layout] \
2056
+ + ([rep] if rep is not None and rep != layout else [])
2057
+ band = lambda Y, H: (Y + H / 2) / 720 < _BAND_TOP or (Y + H / 2) / 720 > _BAND_BOT
2058
+ top_edge, bot_edge = [], [] # how far the kept furniture reaches into the page
2059
+ for part in parts:
2060
+ for kind, el, g, rot, fh, fv in tpl.elements(part):
2061
+ if g is None or kind not in ('sp', 'pic', 'cxnSp'): continue
2062
+ if kind != 'pic' and ''.join(t.text or '' for t in el.iter('{%s}t' % _TNS['a'])).strip():
2063
+ continue # the template's own words are filler; they are never reused
2064
+ X, Y, Wd, Hd = tpl.box(g, small_keep_ratio=(kind == 'pic'))
2065
+ fullpage = Wd >= 0.97 * 1280 and Hd >= 0.97 * 720
2066
+ if kind == 'pic':
2067
+ blip = el.find('.//a:blip', _TNS)
2068
+ tgt = tpl.pkg.rels(part).get(blip.get(_T_EMBED)) if blip is not None else None
2069
+ if not tgt or tgt[1] not in tpl.pkg.names: continue
2070
+ f = tgt[1]
2071
+ if fullpage: pics.append(f); continue
2072
+ if not (band(Y, Hd) and Wd * Hd <= _BAND_PIC * 1280 * 720):
2073
+ dropped.append(f'版心图片 {Wd:.0f}x{Hd:.0f}'); continue
2074
+ ext = f.rsplit('.', 1)[-1].lower()
2075
+ if ext == 'emf':
2076
+ r = _emf_ops(tpl.pkg.z.read(f))
2077
+ if r and r[0]: _draw_emf(art, r, X * S, Y * S, Wd * S, Hd * S)
2078
+ else: notes.append(f'{f}: EMF 里没有可绘制的矢量记录,跳过')
2079
+ elif ext in ('wmf', 'svg'):
2080
+ notes.append(f'{f}: 不支持 {ext.upper()} 图形,跳过')
2081
+ else:
2082
+ dec = _raster(tpl.pkg.z.read(f), ext, max_side=max(Wd, Hd) * S)
2083
+ if dec: art.blit(dec[0], dec[1], dec[2], X * S, Y * S, Wd * S, Hd * S)
2084
+ else: notes.append(f'{f}: {ext} 在这个环境里解不出来,跳过')
2085
+ (top_edge if (Y + Hd / 2) / 720 < _BAND_TOP else bot_edge).append((Y, Hd))
2086
+ continue
2087
+ spPr = el.find('p:spPr', _TNS)
2088
+ if spPr is None or spPr.find('a:noFill', _TNS) is not None: continue
2089
+ sf = spPr.find('a:solidFill', _TNS)
2090
+ fill = _tpl_color(sf, tpl.scheme) if sf is not None else None
2091
+ if fill is None: # gradient / picture / pattern fill: only ever body art here
2092
+ if not fullpage: dropped.append(f'{kind} {Wd:.0f}x{Hd:.0f}')
2093
+ continue
2094
+ if fullpage:
2095
+ # A flat opaque full-page rectangle IS the page colour. Painting it would turn the furniture layer
2096
+ # into an opaque sheet that hides the template's own background picture.
2097
+ if fill[1] >= 0.99: base = fill[0]
2098
+ else: under.fill([[(0, 0), (under.w, 0), (under.w, under.h), (0, under.h)]], fill[0], fill[1])
2099
+ continue
2100
+ if not (band(Y, Hd) and min(Wd, Hd) <= _BAND_BAR):
2101
+ dropped.append(f'{kind} {Wd:.0f}x{Hd:.0f}'); continue
2102
+ art.fill([[(X * S, Y * S), ((X + Wd) * S, Y * S), ((X + Wd) * S, (Y + Hd) * S), (X * S, (Y + Hd) * S)]],
2103
+ fill[0], fill[1])
2104
+ (top_edge if (Y + Hd / 2) / 720 < _BAND_TOP else bot_edge).append((Y, Hd))
2105
+ # Only the backgrounds that can actually be seen: everything under the last opaque raster is hidden by it.
2106
+ opq = lambda f: f.rsplit('.', 1)[-1].lower() in ('jpg', 'jpeg', 'bmp')
2107
+ cut = max((i for i, f in enumerate(pics) if opq(f)), default=None)
2108
+ if cut is not None: pics = pics[cut:]
2109
+ seen = set(); pics = [f for f in pics if not (f in seen or seen.add(f))]
2110
+ for i, f in enumerate(pics):
2111
+ ext = f.rsplit('.', 1)[-1].lower(); data = tpl.pkg.z.read(f)
2112
+ if ext in ('emf', 'wmf'):
2113
+ # A vector full-page background (the Tencent deck's grid is one): draw it into the layer under the
2114
+ # furniture rather than reporting it as lost -- it is the only art some page types have.
2115
+ r = _emf_ops(data)
2116
+ if r and r[0]: _draw_emf(under, r, 0, 0, under.w, under.h)
2117
+ else: notes.append(f'{f}: 整页 {ext.upper()} 里没有可绘制的矢量记录,跳过')
2118
+ continue
2119
+ if ext not in ('jpg', 'jpeg', 'png'):
2120
+ dec = _raster(data, ext, 1600)
2121
+ if not dec: notes.append(f'{f}: {ext} 整页底图在这个环境里转不出来,跳过'); continue
2122
+ data, ext = _png_encode(*dec), 'png'
2123
+ name = f"{role}_bg{'' if i == 0 else i + 1}.{'jpg' if ext in ('jpg', 'jpeg') else 'png'}"
2124
+ open(os.path.join(assets, name), 'wb').write(data)
2125
+ bgfiles.append((name, _dims_from_bytes(data), _raster(data, ext, 320)))
2126
+ if under.used:
2127
+ under.blit(art.w, art.h, art.px, 0, 0, art.w, art.h); art = under
2128
+ # Composite at 1/8 scale to learn what colour actually sits under the page, for the contrast check.
2129
+ comp = _Canvas(320, 180); comp.fill([[(0, 0), (320, 0), (320, 180), (0, 180)]], base)
2130
+ guessed = False
2131
+ for _n, _d, small in bgfiles:
2132
+ if small: comp.blit(small[0], small[1], small[2], 0, 0, 320, 180)
2133
+ else: guessed = True
2134
+ if art.used: comp.blit(art.w, art.h, art.px, 0, 0, 320, 180)
2135
+ if guessed:
2136
+ notes.append(f'{bgfiles[0][0]}: 这个环境读不出图片亮度(无 Pillow / sips),页面底色是估的,排版后请核对对比度')
2137
+ # The <Slide> colour is hidden behind full-page art, but the contrast check reads it as the surface under every
2138
+ # text box without a background of its own. Use the colour covering most of the page, not its mean: a page that
2139
+ # is white on top and red below averages to a pink that exists nowhere on it.
2140
+ slide_bg = _hexsafe(_comp_mode(comp) if (bgfiles or art.used) else base)
2141
+ # The body region clears whatever furniture was kept, and keeps a normal margin where there is none.
2142
+ top = max([y + h for y, h in top_edge] + [0.0])
2143
+ bot = min([y for y, h in bot_edge] + [720.0])
2144
+ top = min(max(top + 24.0, 64.0), 200.0)
2145
+ bot = max(min(bot - 24.0, 664.0), top + 300.0)
2146
+ area = [64, round(top), 1152, round(bot - top)]
2147
+ jsx = [f"<Slide style={{{{ background: '#{slide_bg}', position: 'relative' }}}}>"]
2148
+ for name, dims, _s in bgfiles:
2149
+ files[name] = {'size': list(dims) if dims else None, 'stretch': bool(dims) and abs(dims[0] / dims[1] - 16 / 9) > 0.03}
2150
+ jsx.append(f" <Image src=\"tpl_assets/{name}\" style={{{{ position: 'absolute', left: 0, top: 0, width: 1280, height: 720 }}}} />")
2151
+ if art.used:
2152
+ name = f'{role}_art.png'
2153
+ open(os.path.join(assets, name), 'wb').write(_png_encode(art.w, art.h, art.px))
2154
+ files[name] = {'size': [art.w, art.h], 'stretch': False}
2155
+ jsx.append(f" <Image src=\"tpl_assets/{name}\" style={{{{ position: 'absolute', left: 0, top: 0, width: 1280, height: 720 }}}} />")
2156
+ jsx.append(f" <Box style={{{{ position: 'absolute', left: {area[0]}, top: {area[1]}, width: {area[2]}, height: {area[3]} }}}}>")
2157
+ jsx += [' 〔B区内容〕', ' </Box>', '</Slide>']
2158
+ return {'jsx': '\n'.join(jsx) + '\n', 'notes': notes, 'files': files, 'area': area,
2159
+ 'layout': layout, 'layout_name': tpl.name(layout), 'bg': [b[0] for b in bgfiles],
2160
+ 'art': bool(art.used), 'dropped': dropped, 'surface': _hexsafe(base)}
2161
+
2162
+
2163
+ def _comp_mode(c):
2164
+ """The colour covering most of the canvas, quantised to 16 levels per channel and averaged within its bucket."""
2165
+ import collections
2166
+ buckets = collections.defaultdict(lambda: [0, 0, 0, 0])
2167
+ for o in range(0, len(c.px), 4):
2168
+ r, g, b = c.px[o], c.px[o + 1], c.px[o + 2]
2169
+ k = (r >> 4, g >> 4, b >> 4); e = buckets[k]
2170
+ e[0] += r; e[1] += g; e[2] += b; e[3] += 1
2171
+ if not buckets: return 'FFFFFF'
2172
+ # A gradient scatters across neighbouring buckets, so a small flat area can out-count a large graded one:
2173
+ # score each bucket with its neighbours folded in, then average the winning neighbourhood.
2174
+ ks = list(buckets)
2175
+ near = lambda a, b: all(abs(a[i] - b[i]) <= 2 for i in range(3))
2176
+ best = max(ks, key=lambda k: sum(buckets[j][3] for j in ks if near(k, j)))
2177
+ tot = [0, 0, 0, 0]
2178
+ for j in ks:
2179
+ if not near(best, j): continue
2180
+ for i in range(4): tot[i] += buckets[j][i]
2181
+ return '%02X%02X%02X' % tuple(round(tot[i] / tot[3]) for i in range(3))
2182
+
2183
+
2184
+
2185
+
2186
+
2187
+
2188
+ def _draw_emf(canvas, r, X, Y, Wd, Hd):
2189
+ ops, (x0, y0, x1, y1) = r
2190
+ sx, sy = Wd / max(1e-6, x1 - x0), Hd / max(1e-6, y1 - y0)
2191
+ tr = lambda p: (X + (p[0] - x0) * sx, Y + (p[1] - y0) * sy)
2192
+ for kind, polys, rgb, alpha, eo, w in ops:
2193
+ ps = [[tr(p) for p in pp] for pp in polys]
2194
+ if kind == 'fill': canvas.fill(ps, rgb, alpha, eo)
2195
+ else:
2196
+ for pp in ps: canvas.stroke(pp, eo, w * min(sx, sy), rgb, alpha)
2197
+
2198
+
2199
+
2200
+ def _tpl_design_md(tpl, pages, style):
2201
+ """DESIGN.template.md: what the template actually contributes -- its page art, its palette, its type -- plus the
2202
+ rules for designing on top of that. It is NOT a position contract: the shells carry no text slots, so there is
2203
+ nothing to fill in, only a page to design inside."""
2204
+ c = style['colors']; f = style['fonts']; scale = style.get('type_scale') or []
2205
+ src = tpl.path.replace('\\', '/').rsplit('/', 1)[-1]
2206
+ L = ['# 设计契约(由用户模板生成)', '',
2207
+ f'来源:用户模板 {src};原画幅 {tpl.ratio}' + (',已横向拉伸为 16:9(徽标、图标等小图保持原比例)' if tpl.ratio != '16:9' else '') + '。',
2208
+ '',
2209
+ '**模板提供的只有三样:整页底图 / 底色、页眉页脚带里的页面家具(细条、logo)、以及配色与字体。**'
2210
+ '版式由你按这三样自己设计——模板里的色块、异形图、卡片、示例文字一律不复刻,也不要在页面上补回来。', '',
2211
+ '## 1. 页型外壳', '',
2212
+ '| 页型(模板版式) | 外壳 | 本页写的文件 | 整页底图 | 页眉页脚家具 | 可用版心 [x,y,宽,高] |', '|---|---|---|---|---|---|']
2213
+ fn = {'cover': '`NN_body_cover.jsx`', 'toc': '`NN_body_toc.jsx`', 'section': '`NN_body_section.jsx`',
2214
+ 'content': '`NN_body.jsx`', 'end': '`NN_body_end.jsx`'}
2215
+ for role in ('cover', 'toc', 'section', 'content', 'end'):
2216
+ if role not in pages: continue
2217
+ pg = pages[role]; shell = '00_shell.jsx' if role == 'content' else f'00_shell_{role}.jsx'
2218
+ L.append(f"| {role}(「{pg['layout_name']}」) | `{shell}` | {fn[role]} | "
2219
+ f"{'、'.join(pg['bg']) or '无(底色 #' + pg['surface'] + ')'} | {'有' if pg.get('art') else '无'} | {pg['area']} |")
2220
+ miss = [r for r in ('cover', 'toc', 'section', 'content', 'end') if r not in pages]
2221
+ if miss: L += ['', '模板里没有对应版式的页型:' + '、'.join(miss) + '。目录缺 → 用内容页外壳;章节页 / 结束页缺 → 用封面外壳。']
2222
+ nobg = [r for r in ('cover', 'toc', 'section', 'content', 'end') if r in pages and not pages[r]['bg'] and not pages[r].get('art')]
2223
+ if nobg:
2224
+ L += ['', f"⚠️ 这些页型模板里没有底图也没有家具,外壳就是一张底色页:**{'、'.join(nobg)}**。"
2225
+ f"别让它们空着——用主色 {c['primary']} 铺整页或铺一个大色块,再压大号标题 / 章节号,"
2226
+ f"做成和其他页同一套视觉的页面。"]
2227
+ L += ['', '## 2. 版心', '',
2228
+ '- 每种页型的可用版心见上表最后一列:它已经避开了模板保留下来的页眉页脚家具。**页面上所有内容都落在这个盒子里。**',
2229
+ '- `〔B区内容〕` 就在这个盒子里;外壳除此之外没有任何占位,标题、副标题、正文、图表全部由你在这里排。',
2230
+ '', '## 3. 色彩(模板里实际涂上去的颜色,按使用次数)', '']
2231
+ L.append(f"- 主色 **{c['primary']}**" + (f",辅色 **{c['secondary']}**" if c['secondary'] else '') + '。')
2232
+ chroma = [m['hex'] for m in c['top'] if m['chroma']]; neutral = [m['hex'] for m in c['top'] if not m['chroma']]
2233
+ chroma = list(dict.fromkeys('#' + _hexsafe(h[1:]) for h in chroma)); neutral = list(dict.fromkeys('#' + _hexsafe(h[1:]) for h in neutral))
2234
+ if chroma: L.append('- 彩色(图表系列、色块、强调按此顺序取):' + '、'.join(chroma[:8]))
2235
+ if neutral: L.append('- 中性色(文字、线、浅面):' + '、'.join(neutral[:6]) + ';正文深色字用 #1F2329,次级灰字用 #5F6368')
2236
+ L.append('- 只用上面这些色值,不加新色相。模板主色配白字过不了对比度检查时,先换 §3 里更深的色值,'
2237
+ '再考虑深字配浅色块;最后才把主色压暗到刚好过线,并在交付时说明。一次定下来,不要逐页微调。')
2238
+ L += ['', '## 4. 字体与字号', '',
2239
+ f"- 标题字体 `{f['title']}`(模板:{f['title_typeface'] or '主题字体'}),正文字体 `{f['body']}`(模板:{f['body_typeface'] or '主题字体'});"
2240
+ "全篇只用这两种,纯西文数字可用 `Arial`。"]
2241
+ if scale:
2242
+ L += ['- 下表是**模板自己用的字号档**(px,已按本画幅换算),「模板原文」说明这一档是干什么的:', '',
2243
+ '| 字号 | 模板里用了几处 | 模板原文 |', '|---|---|---|']
2244
+ L += [f"| **{px}px** | {n} | {'、'.join(eg) or '—'} |" for px, n, eg in scale]
2245
+ L += ['', '**从这张表里挑字号,不要自己定。** 挑法:排一页时先定这页的视觉锚点(封面主题 / 章节号 / 核心数字),'
2246
+ '从上表大字档里取一个;正文取「用了十几处以上」的那档;小标题取介于两者之间的一档。'
2247
+ '原文是 `O1`/`01`/`2O2X` 这类编号年份的大字档,是模板的装饰尺度——要用就同样只放编号或数字,别拿它排标题。',
2248
+ '- **同一层级全篇同一个字号**,定下来就不再逐页微调。字号不够用时宁可复用已有档,也不要新造中间值。']
2249
+ else:
2250
+ L += ['- 模板没有显式字号可读(字号全部走主题继承)。按这个层级自己定并全篇统一:'
2251
+ '封面 / 章节号 72–120px,页标题 32–48px,小标题 20–24px,正文 15–18px,注释 12–14px。']
2252
+ L += ['', '## 5. 怎么排', '',
2253
+ '- 版式按内容自由设计(相邻页不重复、非对称优先,见 story-principle.md 版式速查)。',
2254
+ '- 视觉语言跟模板走:模板的色块是直角就用直角,没有圆角 / 阴影 / 描边就不加;强调方式照模板(主色色块、色条、编号)。',
2255
+ '- **每页一个视觉锚点**:一页上必须有一个明显比其他元素大的东西(大号数字 / 大标题 / 整块主视觉),'
2256
+ '其余元素围着它组织。所有元素字号都差不多大 = 流水线页,返工。',
2257
+ '- **版心要填满**:行里的块用 `flex: 1` 而不是写死 `width:`;纵向按版心高度反推每块该多厚,填不到八成就并页或拆页,'
2258
+ '不要靠空话和拉高固定 height 来凑。`buildall` 会直接报空旷。',
2259
+ '- **卡片内部也要填满**:卡片里的内容垂直占到卡高的八成以上;卡越高字越多(高 ≥ 380px 的卡正文不少于 100 字)。'
2260
+ '卡尾的标签条 / 引文条用 `marginTop: auto` 钉到底部,别让它浮在卡中间。',
2261
+ '- **同一行的几张卡要对齐**:标题块、正文块、尾部条三段在各卡之间高度一致,差出十几像素就看得出来。',
2262
+ '- 留白要围着锚点留(锚点周围留出一圈呼吸空间),不要每两个元素之间都留一样大的空 —— 那是稀薄,不是留白。',
2263
+ '- 数据用原生 `<Chart>` / `<Table>`,系列颜色按 §3 彩色顺序;表头用主色底白字。',
2264
+ '- 不放模板以外的装饰图;模板里的示例照片、示例文字、示例数据一律不用。']
2265
+ nts = list(dict.fromkeys([n for r in pages for n in pages[r]['notes']] + tpl.notes))
2266
+ drop = sorted({d for r in pages for d in pages[r].get('dropped', [])})
2267
+ if nts: L += ['', '## 6. 没能带过来的模板元素(交付时如实说明)', ''] + [f'- {n}' for n in nts]
2268
+ if drop:
2269
+ L += ['', '## 7. 按设计舍弃的模板装饰(内部用,不必写进交付说明)', '',
2270
+ f"- 模板版心里的 {len(drop)} 处色块 / 异形图没有复刻(这是设计选择,不是失败):"
2271
+ + '、'.join(drop[:10]) + ('…' if len(drop) > 10 else '')]
2272
+ return '\n'.join(L) + '\n'
2273
+
2274
+
2275
+
2276
+
2277
+ def template(a):
2278
+ """Build the deck's shells from a user's PPT template (see create-from-template.md):
2279
+ template <user.pptx> [--dir .] read the template, write 00_shell*.jsx + tpl_assets/ + DESIGN.template.md
2280
+ template --docid <docid> [--dir .] upload tpl_assets/ to the document and put the urls into the shells
2281
+ template --urls tpl_urls.json [--dir .] same, with urls you uploaded yourself"""
2282
+ import os, collections
2283
+ d = a.dir; os.makedirs(d, exist_ok=True)
2284
+ if a.docid or a.urls: return _tpl_bake(a)
2285
+ if not a.pptx: sys.exit('template needs the template file: template <user.pptx> (or --docid <docid> after the document exists)')
2286
+ tpl = _Tpl(a.pptx); assets = os.path.join(d, 'tpl_assets'); os.makedirs(assets, exist_ok=True)
2287
+ roles, uses, reps = tpl.roles()
2288
+ pages = {}
2289
+ for role, layout in roles.items():
2290
+ pages[role] = _tpl_page(tpl, role, layout, assets, uses, reps.get(role))
2291
+ counter = tpl.painted()
2292
+ chroma = [h for h, _n in counter.most_common() if _tpl_chroma(h)]
2293
+ primary = chroma[0] if chroma else None
2294
+ secondary = next((h for h in chroma[1:] if abs((_rgb_to_hsl(h)[0] - _rgb_to_hsl(primary)[0] + 180) % 360 - 180) >= 30), None) if primary else None
2295
+ title_tf = body_tf = None
2296
+ for role in ('content', 'cover'):
2297
+ if role in pages:
2298
+ lay = pages[role]['layout']; m = tpl.master_of.get(lay)
2299
+ for kind, el, g, *_ in tpl.elements(lay):
2300
+ p = tpl.ph(el) if kind == 'sp' else None
2301
+ if p and p[0] in ('title', 'ctrTitle') and title_tf is None: title_tf = tpl.text_style([el, tpl.inherited_ph(m, p)[0]], m, p[0])['typeface']
2302
+ if p and p[0] in ('body', 'subTitle') and body_tf is None: body_tf = tpl.text_style([el, tpl.inherited_ph(m, p)[0]], m, p[0])['typeface']
2303
+ # The display face of a template is read off its own pages, not off the theme: a deck whose headings are set in
2304
+ # one face would otherwise be reported as the theme default and come out in the wrong type throughout. Taking
2305
+ # the single largest run is not enough -- the biggest type on a page is often a decorative numeral in a display
2306
+ # face used nowhere else (this deck sets 01 / 02 / 03 at 80pt in Impact, and its real headings at 54pt). Among
2307
+ # the runs that are large for this template, the face used by the most of them is the one to follow.
2308
+ runs = []
2309
+ for part in list(tpl.slides) + [p['layout'] for p in pages.values()]:
2310
+ root = tpl.pkg.xml(part)
2311
+ if root is None: continue
2312
+ for r in root.iter('{%s}r' % _TNS['a']):
2313
+ rpr = r.find('a:rPr', _TNS)
2314
+ if rpr is None: continue
2315
+ try: sz = int(rpr.get('sz') or 0)
2316
+ except ValueError: continue
2317
+ if not sz: continue
2318
+ face = rpr.find('a:ea', _TNS)
2319
+ if face is None or not (face.get('typeface') or '').strip(): face = rpr.find('a:latin', _TNS)
2320
+ tf = (face.get('typeface') or '').strip() if face is not None else ''
2321
+ t = r.find('a:t', _TNS)
2322
+ runs.append((sz, tf if tf and not tf.startswith('+') else '', (t.text or '').strip() if t is not None else ''))
2323
+ big = None
2324
+ if runs:
2325
+ cut = 0.6 * max(sz for sz, _t, _x in runs)
2326
+ tally = collections.Counter(tf for sz, tf, _x in runs if sz >= cut and tf)
2327
+ big = tally.most_common(1)[0][0] if tally else None
2328
+ tfam = tpl.font(big or title_tf or '+mj-ea')[0]
2329
+ bfam = tpl.font(body_tf or '+mn-ea')[0]
2330
+ # The template's own type scale, as a plain tally of the sizes it actually sets -- deliberately NOT labelled
2331
+ # 'display / heading / body'. Naming them means guessing, and the guess is wrong on real decks: the two biggest
2332
+ # steps in this template are its decorative section numerals (O1..O4 at 138pt and 96pt), not a title of any
2333
+ # kind. The sample words carry that information without an inference: a step whose samples read 'O1', '02' is
2334
+ # ornament, a step with hundreds of runs of prose is the body size. Pick the steps, do not invent sizes.
2335
+ steps = collections.defaultdict(lambda: [0, []])
2336
+ for sz, _tf, txt in runs:
2337
+ px = max(8, round(sz / 100 * tpl.pt))
2338
+ key = next((k for k in steps if abs(k - px) <= 2), px)
2339
+ steps[key][0] += 1
2340
+ if txt and len(steps[key][1]) < 3 and txt not in steps[key][1]: steps[key][1].append(txt[:12])
2341
+ # Keep both ends: the largest steps (the template's display scale) and the most-used ones (its body scale).
2342
+ # Taking the top N by size alone drops body text entirely -- this deck sets prose at 19px, step 11 of 12.
2343
+ keep = set(sorted(steps, reverse=True)[:5]) | set(sorted(steps, key=lambda k: -steps[k][0])[:5])
2344
+ scale = [[k, steps[k][0], steps[k][1]] for k in sorted(keep, reverse=True)]
2345
+ filler, chars = [], []
2346
+ for i, sl in enumerate(tpl.slides, 1):
2347
+ txt = [t.text or '' for t in tpl.pkg.xml(sl).iter('{%s}t' % _TNS['a'])]
2348
+ if any(_T_FILLER.search(t) for t in txt): filler.append(i)
2349
+ chars.append(sum(len(re.sub(r'\s', '', t)) for t in txt if not _T_FILLER.search(t)))
2350
+ n = len(tpl.slides); fr = round(len(filler) / n, 2) if n else 1.0
2351
+ style = {'file': os.path.abspath(a.pptx), 'canvas': {'ratio': tpl.ratio, 'emu': [tpl.W, tpl.H]},
2352
+ 'colors': {'primary': '#' + primary if primary else None, 'secondary': '#' + secondary if secondary else None,
2353
+ 'top': [{'hex': '#' + h, 'count': c, 'chroma': _tpl_chroma(h)} for h, c in counter.most_common(14)]},
2354
+ 'fonts': {'title': tfam, 'title_typeface': title_tf, 'body': bfam, 'body_typeface': body_tf},
2355
+ 'type_scale': scale,
2356
+ 'text': {'slides': n, 'filler_slides': filler, 'filler_ratio': fr, 'avg_chars': round(sum(chars) / n) if n else 0},
2357
+ 'kind_hint': 'template' if n == 0 or fr >= 0.3 else 'deck' if fr <= 0.1 else 'mixed',
2358
+ 'pages': {r: {k: v for k, v in p.items() if k not in ('jsx',)} for r, p in pages.items()}}
2359
+ written = []
2360
+ for role, pg in pages.items():
2361
+ name = '00_shell.jsx' if role == 'content' else f'00_shell_{role}.jsx'
2362
+ open(os.path.join(d, name), 'w', encoding='utf-8').write(pg['jsx']); written.append(name)
2363
+ open(os.path.join(d, 'DESIGN.template.md'), 'w', encoding='utf-8').write(_tpl_design_md(tpl, pages, style))
2364
+ json.dump(style, open(os.path.join(d, 'template_style.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
2365
+ print(f"canvas {tpl.ratio}" + (' (stretched to 16:9; small art keeps its ratio)' if tpl.ratio != '16:9' else ''))
2366
+ print(f"colours primary {style['colors']['primary']} secondary {style['colors']['secondary']} fonts {tfam} / {bfam}")
2367
+ for role in ('cover', 'toc', 'section', 'content', 'end'):
2368
+ if role not in pages: print(f"{role:8s} -- no layout for it in the template"); continue
2369
+ pg = pages[role]
2370
+ print(f"{role:8s} layout 「{pg['layout_name']}」 -> {'00_shell.jsx' if role == 'content' else '00_shell_' + role + '.jsx'} "
2371
+ f"版心 {pg['area'][2]}x{pg['area'][3]} @({pg['area'][0]},{pg['area'][1]})"
2372
+ + (f" 底图 {', '.join(pg['bg'])}" if pg['bg'] else f" 底色 #{pg['surface']}")
2373
+ + (' 页眉页脚家具' if pg.get('art') else ''))
2374
+ for nt in pg['notes']: print(f" note: {nt}")
2375
+ print(f"assets {', '.join(sorted(os.listdir(assets)))}")
2376
+ plain = [r for r in ('cover', 'toc', 'section', 'content', 'end') if r in pages and not pages[r]['bg'] and not pages[r].get('art')]
2377
+ if plain:
2378
+ print(f"\n注意 {', '.join(plain)} 在模板里没有底图也没有页眉页脚家具,外壳就是一张底色页。"
2379
+ f"按 DESIGN.template.md §1 的提示用主色 {style['colors']['primary']} 自己做出视觉,别让它空着。")
2380
+ print('\n-> DESIGN.template.md, template_style.json, ' + ', '.join(written))
2381
+ print('next: DESIGN.template.md is the body of DESIGN.md. After the document exists, upload the art with ONE command:\n'
2382
+ ' template --docid <docid> (then write pages: NN_body*.jsx, and run buildall)\n'
2383
+ 'the shells carry no text slots: every word on the page is yours to design and place.\n'
2384
+ 'every text in the template is filler or sample data -- none of it goes into STORY.md as a fact.')
2385
+
2386
+
2387
+ def _tpl_bake(a):
2388
+ """Upload tpl_assets/* referenced by the shells and replace the local paths with the returned urls."""
2389
+ import os, glob, subprocess, shutil
2390
+ d = a.dir; shells = sorted(glob.glob(os.path.join(d, '00_shell*.jsx')))
2391
+ used = sorted({m for p in shells for m in re.findall(r'tpl_assets/[\w.\-]+', open(p, encoding='utf-8').read())})
2392
+ style = json.load(open(os.path.join(d, 'template_style.json'), encoding='utf-8')) if os.path.exists(os.path.join(d, 'template_style.json')) else {'pages': {}}
2393
+ meta = {('tpl_assets/' + k): v for pg in style['pages'].values() for k, v in pg.get('files', {}).items()}
2394
+ used = sorted(set(used))
2395
+ cache_p = os.path.join(d, 'tpl_urls.json')
2396
+ urls = json.load(open(cache_p, encoding='utf-8')) if os.path.exists(cache_p) else {}
2397
+ if a.urls: urls.update(json.load(open(a.urls, encoding='utf-8')))
2398
+ todo = [u for u in used if u not in urls]
2399
+ if todo and a.docid:
2400
+ cli = shutil.which(a.cli) or a.cli
2401
+ for rel in todo:
2402
+ path = os.path.abspath(os.path.join(d, rel))
2403
+ r = subprocess.run([cli, 'smartpage', 'images', 'upload', '--json', json.dumps({'docid': a.docid, 'file_path': path})],
2404
+ capture_output=True, text=True)
2405
+ m = re.search(r'"url"\s*:\s*"([^"]+)"', r.stdout or '')
2406
+ if r.returncode or not m:
2407
+ print(f'upload failed for {rel}: {(r.stderr or r.stdout).strip()[:300]}'); continue
2408
+ urls[rel] = m.group(1); print(f'uploaded {rel}')
2409
+ json.dump(urls, open(cache_p, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
2410
+ missing = [u for u in used if u not in urls]
2411
+ if missing:
2412
+ print('\nnot uploaded yet: ' + ', '.join(missing))
2413
+ print(f'upload each with {a.cli} smartpage images upload --json \'{{"docid": "<DOCID>", "file_path": "<abs path>"}}\'\n'
2414
+ 'put {"tpl_assets/x.png": "<url>"} into a json and rerun: template --urls that.json')
2415
+ sys.exit(1)
2416
+ for p in shells:
2417
+ src = open(p, encoding='utf-8').read(); out = src
2418
+ for rel, url in urls.items(): out = out.replace(f'"{rel}"', f'"{url}"')
2419
+ if out != src: open(p, 'w', encoding='utf-8').write(out); print(f'ok {os.path.basename(p)}')
2420
+ man_p = os.path.join(d, 'images.json'); man = json.load(open(man_p, encoding='utf-8')) if os.path.exists(man_p) else {}
2421
+ for rel, url in urls.items():
2422
+ m = meta.get(rel) or {}
2423
+ if m.get('size'): man[url] = {'width': m['size'][0], 'height': m['size'][1], 'stretch': bool(m.get('stretch'))}
2424
+ json.dump(man, open(man_p, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
2425
+ dmd = os.path.join(d, 'DESIGN.template.md')
2426
+ if os.path.exists(dmd):
2427
+ s = open(dmd, encoding='utf-8').read(); s2 = s
2428
+ for rel, url in urls.items(): s2 = s2.replace(f'`{rel}`', f'`{url}`')
2429
+ if s2 != s: open(dmd, 'w', encoding='utf-8').write(s2)
2430
+ print('\nshells now point at the uploaded art; images.json updated. Write the pages and run buildall.')
2431
+
2432
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
2433
+ sub = ap.add_subparsers(dest='cmd', required=True)
2434
+ b = sub.add_parser('build'); b.add_argument('--shell', required=True); b.add_argument('--body', required=True); b.add_argument('--vars'); b.add_argument('--manifest', help='images.json; required when the body contains <Image>'); b.add_argument('--out', required=True); b.set_defaults(fn=build)
2435
+ c = sub.add_parser('check'); c.add_argument('--shell', required=True); c.add_argument('pages', nargs='+'); c.set_defaults(fn=check)
2436
+ f = sub.add_parser('imgfit'); f.add_argument('--slot', required=True, help='slot WxH, e.g. 576x434'); f.add_argument('--actual', required=True, help='real picture WxH from the generator / upload result'); f.add_argument('--src', required=True); f.add_argument('--bg', help='letterbox colour, e.g. #DCEBFD'); f.set_defaults(fn=imgfit)
2437
+ g = sub.add_parser('images'); g.add_argument('--manifest', help='json {url: [w, h]} written in Step6'); g.add_argument('pages', nargs='+'); g.set_defaults(fn=images)
2438
+ r_ = sub.add_parser('recolor'); r_.add_argument('--map', required=True, help='json {"#old": "#new"}'); r_.add_argument('--out-dir', required=True); r_.add_argument('files', nargs='+'); r_.set_defaults(fn=recolor)
2439
+ i_ = sub.add_parser('init'); i_.add_argument('--set', required=True); i_.add_argument('--out', default='.'); i_.add_argument('--map', help='colors.json for recolouring'); i_.set_defaults(fn=init)
2440
+ pa = sub.add_parser('palette'); pa.add_argument('--set', required=True); pa.add_argument('--hue', type=float, required=True, help='0-360: 0 red, 30 orange, 45 gold, 90 olive, 140 green, 190 teal, 215 blue, 265 violet, 330 magenta')
2441
+ pa.add_argument('--sat', type=float, default=1.0, help='saturation multiplier, e.g. 0.7 for a calmer palette'); pa.add_argument('--spread', type=float, default=1.0, help='0-1: how much of the set\'s original hue spread to keep (multi-colour sets)')
2442
+ pa.add_argument('--invert', action='store_true', help='flip light and dark (light set -> dark scheme)'); pa.add_argument('--out', default='colors.json')
2443
+ pa.add_argument('--min-gap', dest='min_gap', type=float, default=60.0, help="min degrees between --hue and the set's own hue; inside it, use the set's default palette instead (default 60)")
2444
+ pa.add_argument('--force', action='store_true', help='derive anyway inside --min-gap (only for a brand colour the user named)'); pa.set_defaults(fn=palette)
2445
+ tp = sub.add_parser('template'); tp.add_argument('pptx', nargs='?', help="the user's template, .pptx / .potx (convert .ppt first)"); tp.add_argument('--dir', default='.'); tp.add_argument('--docid', help='after the document exists: upload tpl_assets/ to it and put the urls into the shells'); tp.add_argument('--urls', help='json {"tpl_assets/x.png": url} of art you uploaded yourself'); tp.add_argument('--cli', default='wecom-cli'); tp.set_defaults(fn=template)
2446
+ ba = sub.add_parser('buildall'); ba.add_argument('--dir', default='.'); ba.set_defaults(fn=buildall)
2447
+ ft = sub.add_parser('fit'); ft.add_argument('pages', nargs='+'); ft.set_defaults(fn=fit)
2448
+ k = sub.add_parser('contrast'); k.add_argument('pages', nargs='+'); k.set_defaults(fn=contrast)
2449
+ a = ap.parse_args(); a.fn(a)