@lark-apaas/coding-steering 0.1.32-dev.942e73f → 0.1.32-dev.f3c32d8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/coding-steering",
3
- "version": "0.1.32-dev.942e73f",
3
+ "version": "0.1.32-dev.f3c32d8",
4
4
  "description": "Stack-specific steering content for miaoda-coding templates",
5
5
  "type": "module",
6
6
  "files": [
@@ -133,16 +133,16 @@ When generating a deck:
133
133
  2. Build `<deck-stage width="<canvas width>" height="<canvas height>">` using the `canvas` declared in `layouts.md` — source decks are not always 16:9, and a default-sized stage shifts every coordinate on the page. Each slide is one static `<section data-pptx-layout="<chosen archetype>">`.
134
134
  3. Inline CSS variables from `design.md` into the HTML `<style>` block using a `--ppt-*` prefix.
135
135
  4. **位移动画用独立的 `translate` 属性**:`@keyframes fadeUp { from{opacity:0; translate:0 24px} to{opacity:1; translate:0 0} }`。`transform` 是单一属性,动画里碰它会覆盖掉元素原有的那条(`left:50%; transform:translateX(-50%)` 的居中就此丢失);`translate` / `rotate` / `scale` 各自独立,与已有 `transform` 叠加。
136
- 5. Map `layouts.md` slots to absolute-positioned elements inside each section: expand `box: [x,y,w,h]` mechanically to `left/top/width/height`, then apply the slot's `css` declaration string unchanged. `box` owns geometry; `css` owns all rendering style, including the template's text padding, typography, alignment, line height, letter spacing, and rotation. Do not reinterpret PPTX fields or replace slot CSS with your own type scale. A slot with `asset` is a fixed image element (logo, mark): place that asset at that box on that archetype only. Do not reflow any of this as generic web grids.
136
+ 5. Map `layouts.md` slots to absolute-positioned elements inside each section: expand `box: [x,y,w,h]` mechanically to `left/top/width/height`, then apply the slot's `css` declaration string unchanged. `box` owns geometry; `css` owns all rendering style, including the template's text padding, typography, alignment, line height, letter spacing, and rotation. Do not reinterpret PPTX fields or replace slot CSS with your own type scale. A slot with `asset` is a fixed image element: use that exact asset at that box on that archetype only; do not omit or replace it. Do not reflow any of this as generic web grids.
137
137
  6. Copy `<pack_dir>/assets/` into the project, for example `assets/pptx-style/<pack-name>/`, and reference those copied files with relative URLs. The scratch `tmp/pptx-style-extract/...` path must never appear in the final HTML.
138
138
  7. Use the font stacks and fallback rules from `design.md`; do not install fonts or dependencies at runtime.
139
- 8. Before the regular slide preflight, verify every template logo against the selected archetype:
139
+ 8. Before the regular slide preflight, verify every background and fixed image asset against the selected archetype:
140
140
 
141
141
  ```bash
142
- PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_logo_scope.py <pack_dir> <index.html> --asset-prefix <copied-assets-prefix>
142
+ PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_layout_assets.py <pack_dir> <index.html> --asset-prefix <copied-assets-prefix>
143
143
  ```
144
144
 
145
- `PPTX_LOGO_SCOPE: FAIL` means remove or move every listed logo according to `layouts.md`, then rerun this command.
145
+ `PPTX_LAYOUT_ASSETS: FAIL` means add every missing bound asset and remove every cross-layout use according to `layouts.md`, then rerun this command.
146
146
  9. Run the slide preflight checks: no resource failures, no section overflow, and sampled screenshots follow the package colors, typography, layouts, assets, and Hard Rules.
147
147
 
148
148
  ## Export Consumer Attachments
@@ -981,6 +981,13 @@ def background_decor(background, canvas):
981
981
  'trace': 'canvas-background'}
982
982
 
983
983
 
984
+ def background_identity(background):
985
+ """返回可用于聚类和审计的稳定背景标识,不改变背景的原始表达。"""
986
+ if isinstance(background, dict):
987
+ return json.dumps(background, sort_keys=True, separators=(',', ':'))
988
+ return background
989
+
990
+
984
991
  # ---------------------------------------------------------------- 版式聚类
985
992
  DECOR_MIN = 40.0
986
993
 
@@ -1539,16 +1546,19 @@ def draft_layouts(d, outdir, effective_alpha=None):
1539
1546
  image_marks = slide_image_marks(d, overlay_media)
1540
1547
 
1541
1548
  bg_of_slide, layout_of_slide = {}, {}
1542
- bg_of_layout = {row['part']: row.get('background') for row in d.get('layouts') or []}
1549
+ background_of_layout = {
1550
+ row['part']: row.get('background') for row in d.get('layouts') or []
1551
+ }
1543
1552
  for s in d.get('slides', []):
1544
1553
  bg = s.get('background')
1545
- bg_of_slide[s['part']] = json.dumps(bg, sort_keys=True) if isinstance(bg, dict) else bg
1554
+ bg_of_slide[s['part']] = background_identity(bg)
1546
1555
  layout_of_slide[s['part']] = s.get('layout')
1547
1556
  # 版式层的满屏底图(form=2 常态:底图挂在 layout 上)
1548
1557
  composites = d.get('background_composites') or {}
1558
+ bg_media_of_layout = {}
1549
1559
  for s in shapes:
1550
1560
  if s.get('layer') == 'layout' and is_bleed(s) and s.get('media'):
1551
- bg_of_layout[s['part']] = s['media']
1561
+ bg_media_of_layout[s['part']] = s['media']
1552
1562
 
1553
1563
  pages = []
1554
1564
  for part, sh in sorted(by_slide.items(), key=lambda kv: slide_no(kv[0])):
@@ -1556,7 +1566,7 @@ def draft_layouts(d, outdir, effective_alpha=None):
1556
1566
  layout_shapes = by_layout.get(layout_part) or []
1557
1567
  bg_media = top_bleed_media(sh)
1558
1568
  if bg_media is None:
1559
- bg_media = bg_of_layout.get(layout_part)
1569
+ bg_media = bg_media_of_layout.get(layout_part)
1560
1570
  rendered_bg = (composites.get(part)
1561
1571
  or composites.get(layout_part)
1562
1572
  or bg_media)
@@ -1602,7 +1612,7 @@ def draft_layouts(d, outdir, effective_alpha=None):
1602
1612
  marks.append(mark)
1603
1613
  background = next((s.get('background') for s in d.get('slides') or []
1604
1614
  if s.get('part') == part and s.get('background')), None)
1605
- background = background or bg_of_layout.get(layout_part)
1615
+ background = background or background_of_layout.get(layout_part)
1606
1616
  pages.append({'part': part, 'no': slide_no(part), 'bg_media': bg_media,
1607
1617
  'rendered_bg': rendered_bg,
1608
1618
  'bg_color': bg_of_slide.get(part), 'background': background,
@@ -1632,7 +1642,11 @@ def draft_layouts(d, outdir, effective_alpha=None):
1632
1642
  # 不替模型下结论。和首页一样,拆组只避免它被聚类代表页吞掉。
1633
1643
  groups[('__last__', -2)] = [p]
1634
1644
  continue
1635
- groups[(p['bg_media'] or p['bg_color'] or 'none', density_band(p))].append(p)
1645
+ background_key = background_identity(
1646
+ p.get('rendered_bg') or p.get('bg_media')
1647
+ or p.get('background') or p.get('bg_color')
1648
+ ) or 'none'
1649
+ groups[(background_key, density_band(p))].append(p)
1636
1650
 
1637
1651
  ranked = sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[1][0]['no']))
1638
1652
  # 首页所在的组一定收——deck 的第一页是模板的门面,孤例也不能被名额挤掉。
@@ -1654,15 +1668,9 @@ def draft_layouts(d, outdir, effective_alpha=None):
1654
1668
  leftover = sorted(p['no'] for g in ranked if g not in kept for p in g[1])
1655
1669
 
1656
1670
  archetypes = []
1657
- for gi, ((bg_raw, _band), ps) in enumerate(kept, 1):
1671
+ for gi, ((_background_key, _band), ps) in enumerate(kept, 1):
1658
1672
  rep = max(ps, key=lambda p: len(p['texts']))
1659
- if bg_raw == '__first__':
1660
- bg_raw = rep['bg_media'] or rep['bg_color'] or 'none'
1661
- elif bg_raw == '__last__':
1662
- bg_raw = rep['bg_media'] or rep['bg_color'] or 'none'
1663
- rendered_bg = rep.get('rendered_bg')
1664
- if rendered_bg:
1665
- bg_raw = rendered_bg
1673
+ bg_raw = rep.get('rendered_bg') or rep.get('bg_media')
1666
1674
  name = 'layout-%d' % gi
1667
1675
  # 标题按「位置 + 跨度」认,不按字号——big-number 类的巨号数值常比标题还大
1668
1676
  # 标题 = 该页最靠上的那批文本里最宽的一块。不按「画布前 28%」这类固定比例切:
@@ -1739,9 +1747,13 @@ def draft_layouts(d, outdir, effective_alpha=None):
1739
1747
  p['layout'] for p in ps if p.get('layout')
1740
1748
  }),
1741
1749
  '_source_backgrounds': sorted({
1742
- p.get('rendered_bg') or p.get('bg_media') or p.get('bg_color')
1750
+ background_identity(
1751
+ p.get('rendered_bg') or p.get('bg_media')
1752
+ or p.get('background') or p.get('bg_color')
1753
+ )
1743
1754
  for p in ps
1744
- if p.get('rendered_bg') or p.get('bg_media') or p.get('bg_color')
1755
+ if (p.get('rendered_bg') or p.get('bg_media')
1756
+ or p.get('background') or p.get('bg_color'))
1745
1757
  }),
1746
1758
  '_text_n': len(rep['texts']),
1747
1759
  '_last_page_candidate': rep['no'] == last_page_no,
@@ -3044,7 +3056,7 @@ def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, cusage, l
3044
3056
  '页数多于页型时,挑最接近的一个原样套用它的 slot:用不到的槽删掉,'
3045
3057
  '内容比槽多就按同类槽的间距等距加,**坐标一律沿用该页型给的那套,不要自己另起网格**。'
3046
3058
  '每个生成页面的 `<section>` 都写 `data-pptx-layout="<页型名>"`,'
3047
- '交付前据此核验 logo 只出现在该页型的资产槽中。' % sidecar,
3059
+ '交付前据此核验该页型绑定的背景与图片资产均已使用,且没有跨页型误用。' % sidecar,
3048
3060
  '3. **按页型给的形态落元素** —— 页型给 `flow` 就用流式,给 `slots` 就用绝对,'
3049
3061
  '两者只会出现一个。'
3050
3062
  '**flow**:整块用一个纵向 flex 容器,`top` 是它的起始 y,`margin` 是整块的左右边距,'
@@ -3063,7 +3075,7 @@ def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, cusage, l
3063
3075
  '`[x, y, w, h]`(%dx%d 画布上的绝对像素),机械展开成 `left/top/width/height`;'
3064
3076
  'slot 的 `css` 是模板排版属性已转译好的声明串,原样写进 style,不要另选字号、'
3065
3077
  '内边距、颜色或对齐。'
3066
- '带 `asset` 的 slot 是图片元素(logo、角标),把该资产放在它自己的 `box` 里;'
3078
+ '带 `asset` 的 slot 是固定图片元素,把该资产放在它自己的 `box` 里,不得省略或换图;'
3067
3079
  '这个页型没有 `asset` 槽,这一页就不出现该资产。' % (canvas[0], canvas[1]),
3068
3080
  '5. **铺装饰几何** —— 页型的 `decor` 是这一页的图形骨架(图标托底的圆、'
3069
3081
  '卡片、分隔线):每条渲染成一个绝对定位空元素,`box` 给位置,`css` 逐项原样写进 '
@@ -61,7 +61,8 @@ class DesignConsumerContractTest(unittest.TestCase):
61
61
  self.assertIn('确认全部页型后再开始搭页', body)
62
62
  self.assertIn('不能只看摘要、前几个页型', body)
63
63
  self.assertIn('data-pptx-layout="<页型名>"', body)
64
- self.assertIn('交付前据此核验 logo 只出现在该页型的资产槽中', body)
64
+ self.assertIn('该页型绑定的背景与图片资产均已使用', body)
65
+ self.assertIn('不得省略或换图', body)
65
66
 
66
67
 
67
68
  if __name__ == '__main__':
@@ -1185,6 +1185,85 @@ layouts:
1185
1185
  self.assertIn('value: "[0, 0, 1920, 1080]"', manifest)
1186
1186
  self.assertIn('reason: "PPT 背景铺满画布"', manifest)
1187
1187
 
1188
+ def test_sampled_layouts_group_inherited_structured_background(self):
1189
+ layout_part = 'ppt/slideLayouts/slideLayout1.xml'
1190
+ slides = [{
1191
+ 'part': 'ppt/slides/slide%d.xml' % index,
1192
+ 'layout': layout_part,
1193
+ 'background': None,
1194
+ } for index in range(1, 4)]
1195
+ data = {
1196
+ 'canvas': {'px': [1920, 1080]},
1197
+ 'form_hint': {'form': 1},
1198
+ 'layouts': [{
1199
+ 'part': layout_part,
1200
+ 'name': '内容',
1201
+ 'used_by_slides': 3,
1202
+ }],
1203
+ 'slides': slides,
1204
+ 'images': [],
1205
+ 'media': [],
1206
+ 'theme_topology': {'themes': ['single'], 'per_master': [], 'default': 'single'},
1207
+ 'reference_graph': {
1208
+ 'master_of_layout': {},
1209
+ 'layout_of_slide': {
1210
+ slide['part']: layout_part for slide in slides
1211
+ },
1212
+ },
1213
+ 'background_composites': {},
1214
+ }
1215
+ shapes = [{
1216
+ 'part': slide['part'],
1217
+ 'layer': 'slide',
1218
+ 'kind': 'sp',
1219
+ 'box': {'x': 100, 'y': 100, 'w': 600, 'h': 100},
1220
+ 'ph': {'type': 'title', 'idx': '1'},
1221
+ 'text': {'paragraphs': [{'runs': [{
1222
+ 'text': 'Title %d' % index,
1223
+ 'sz_px': 40,
1224
+ }]}]},
1225
+ } for index, slide in enumerate(slides, 1)]
1226
+
1227
+ backgrounds = [{
1228
+ 'source': 'bgPr',
1229
+ 'type': 'solid',
1230
+ 'color': {'resolved': '#FAF9F5'},
1231
+ }, {
1232
+ 'type': 'gradient',
1233
+ 'stops': [
1234
+ {'pos': 0, 'color': {'resolved': '#4B5CF5'}},
1235
+ {'pos': 100, 'color': {'resolved': '#233AFB'}},
1236
+ ],
1237
+ 'angle_deg': 0,
1238
+ }]
1239
+ for background in backgrounds:
1240
+ with self.subTest(background=background['type']):
1241
+ data['layouts'][0]['background'] = background
1242
+ with tempfile.TemporaryDirectory() as output_dir:
1243
+ os.makedirs(os.path.join(output_dir, 'ref'))
1244
+ with open(os.path.join(output_dir, 'ref', 'shapes.json'), 'w',
1245
+ encoding='utf-8') as stream:
1246
+ import json
1247
+ json.dump({'shapes': shapes}, stream)
1248
+ archetypes, pages, _ = draft_layouts(
1249
+ data, output_dir, effective_alpha={})
1250
+
1251
+ self.assertEqual([1, 2, 3], sorted(
1252
+ page for archetype in archetypes for page in archetype['pages']))
1253
+ self.assertTrue(all(page['background'] == background for page in pages))
1254
+ self.assertTrue(all(archetype['bg_raw'] is None
1255
+ for archetype in archetypes))
1256
+ self.assertTrue(all(
1257
+ any(decor.get('trace') == 'canvas-background'
1258
+ for decor in archetype['decor'])
1259
+ for archetype in archetypes
1260
+ ))
1261
+ self.assertTrue(all(
1262
+ all(isinstance(value, str)
1263
+ for value in archetype['_source_backgrounds'])
1264
+ for archetype in archetypes
1265
+ ))
1266
+
1188
1267
  def test_asset_vision_groups_fail_when_page_screenshot_is_unreadable(self):
1189
1268
  candidates = [{
1190
1269
  'id': 'asset-1',
@@ -1,16 +1,17 @@
1
1
  #!/usr/bin/env python3
2
- """Regression tests for template logo placement in generated deck HTML."""
2
+ """Regression tests for template asset placement in generated deck HTML."""
3
3
  import os
4
+ import subprocess
4
5
  import sys
5
6
  import tempfile
6
7
  import unittest
7
8
 
8
9
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
9
10
 
10
- from verify_logo_scope import validate_logo_scope
11
+ from verify_layout_assets import validate_layout_assets
11
12
 
12
13
 
13
- class LogoScopeTest(unittest.TestCase):
14
+ class LayoutAssetContractTest(unittest.TestCase):
14
15
  def write_pack(self, root):
15
16
  with open(os.path.join(root, 'design.md'), 'w', encoding='utf-8') as stream:
16
17
  stream.write(
@@ -48,6 +49,57 @@ class LogoScopeTest(unittest.TestCase):
48
49
  stream.write(content)
49
50
  return path
50
51
 
52
+ def write_texture_pack(self, root):
53
+ with open(os.path.join(root, 'design.md'), 'w', encoding='utf-8') as stream:
54
+ stream.write(
55
+ '---\n'
56
+ 'assets:\n'
57
+ ' texture-1:\n'
58
+ ' path: assets/textures/1.webp\n'
59
+ ' kind: texture\n'
60
+ 'layouts: layouts.md\n'
61
+ '---\n'
62
+ )
63
+ with open(os.path.join(root, 'layouts.md'), 'w', encoding='utf-8') as stream:
64
+ stream.write(
65
+ '---\n'
66
+ 'canvas: 1920x1080\n'
67
+ 'layouts:\n'
68
+ ' cover:\n'
69
+ ' role: cover\n'
70
+ ' slots:\n'
71
+ ' - {role: texture, box: [1142, 0, 778, 1080], type: pic, asset: texture-1}\n'
72
+ ' content:\n'
73
+ ' role: content\n'
74
+ ' slots:\n'
75
+ ' - {role: title, box: [100, 100, 800, 100], type: title}\n'
76
+ '---\n'
77
+ )
78
+
79
+ def write_background_pack(self, root):
80
+ with open(os.path.join(root, 'design.md'), 'w', encoding='utf-8') as stream:
81
+ stream.write(
82
+ '---\n'
83
+ 'assets:\n'
84
+ ' bg-content-1:\n'
85
+ ' path: assets/backgrounds/content.webp\n'
86
+ ' kind: background\n'
87
+ 'layouts: layouts.md\n'
88
+ '---\n'
89
+ )
90
+ with open(os.path.join(root, 'layouts.md'), 'w', encoding='utf-8') as stream:
91
+ stream.write(
92
+ '---\n'
93
+ 'canvas: 1920x1080\n'
94
+ 'layouts:\n'
95
+ ' content:\n'
96
+ ' role: content\n'
97
+ ' background: bg-content-1\n'
98
+ ' slots:\n'
99
+ ' - {role: title, box: [100, 100, 800, 100], type: title}\n'
100
+ '---\n'
101
+ )
102
+
51
103
  def test_logo_is_limited_to_every_archetype_with_its_slot(self):
52
104
  with tempfile.TemporaryDirectory() as root:
53
105
  self.write_pack(root)
@@ -64,7 +116,7 @@ class LogoScopeTest(unittest.TestCase):
64
116
 
65
117
  self.assertEqual(
66
118
  [],
67
- validate_logo_scope(root, html, 'assets/pptx-volcengine'),
119
+ validate_layout_assets(root, html, 'assets/pptx-volcengine'),
68
120
  )
69
121
 
70
122
  def test_logo_on_an_unowned_archetype_is_rejected(self):
@@ -78,7 +130,7 @@ class LogoScopeTest(unittest.TestCase):
78
130
  '</deck-stage>',
79
131
  )
80
132
 
81
- problems = validate_logo_scope(root, html, 'assets/pptx-volcengine')
133
+ problems = validate_layout_assets(root, html, 'assets/pptx-volcengine')
82
134
 
83
135
  self.assertEqual(1, len(problems))
84
136
  self.assertIn('content', problems[0])
@@ -96,7 +148,7 @@ class LogoScopeTest(unittest.TestCase):
96
148
 
97
149
  self.assertEqual(
98
150
  [],
99
- validate_logo_scope(root, html, 'assets/pptx-volcengine'),
151
+ validate_layout_assets(root, html, 'assets/pptx-volcengine'),
100
152
  )
101
153
 
102
154
  def test_each_slide_declares_its_template_archetype(self):
@@ -108,8 +160,8 @@ class LogoScopeTest(unittest.TestCase):
108
160
  )
109
161
 
110
162
  self.assertEqual(
111
- ['第 1 页缺少 data-pptx-layout,无法核验模板 logo 归属'],
112
- validate_logo_scope(root, html, 'assets/pptx-volcengine'),
163
+ ['第 1 页缺少 data-pptx-layout,无法核验模板资产归属'],
164
+ validate_layout_assets(root, html, 'assets/pptx-volcengine'),
113
165
  )
114
166
 
115
167
  def test_logo_in_global_css_is_rejected(self):
@@ -123,8 +175,8 @@ class LogoScopeTest(unittest.TestCase):
123
175
  )
124
176
 
125
177
  self.assertEqual(
126
- ['模板 logo logo-1 出现在 slide section 外,无法核验页型归属'],
127
- validate_logo_scope(root, html, 'assets/pptx-volcengine'),
178
+ ['模板资产 logo-1 出现在 slide section 外,无法核验页型归属'],
179
+ validate_layout_assets(root, html, 'assets/pptx-volcengine'),
128
180
  )
129
181
 
130
182
  def test_logo_in_a_slide_style_block_is_rejected(self):
@@ -139,10 +191,111 @@ class LogoScopeTest(unittest.TestCase):
139
191
  )
140
192
 
141
193
  self.assertEqual(
142
- ['模板 logo logo-1 出现在 slide section 外,无法核验页型归属'],
143
- validate_logo_scope(root, html, 'assets/pptx-volcengine'),
194
+ ['模板资产 logo-1 出现在 slide section 外,无法核验页型归属'],
195
+ validate_layout_assets(root, html, 'assets/pptx-volcengine'),
144
196
  )
145
197
 
198
+ def test_layout_must_use_its_bound_texture(self):
199
+ with tempfile.TemporaryDirectory() as root:
200
+ self.write_texture_pack(root)
201
+ html = self.write_html(
202
+ root,
203
+ '<deck-stage><section data-pptx-layout="cover">'
204
+ '<img src="assets/generated/replacement.webp"></section></deck-stage>',
205
+ )
206
+
207
+ problems = validate_layout_assets(root, html, 'assets/pptx-claude')
208
+
209
+ self.assertEqual(1, len(problems))
210
+ self.assertIn('cover', problems[0])
211
+ self.assertIn('texture-1', problems[0])
212
+ self.assertIn('必须使用', problems[0])
213
+
214
+ def test_layout_bound_texture_on_an_unowned_layout_is_rejected(self):
215
+ with tempfile.TemporaryDirectory() as root:
216
+ self.write_texture_pack(root)
217
+ html = self.write_html(
218
+ root,
219
+ '<deck-stage><section data-pptx-layout="content">'
220
+ '<img src="assets/pptx-claude/textures/1.webp"></section></deck-stage>',
221
+ )
222
+
223
+ problems = validate_layout_assets(root, html, 'assets/pptx-claude')
224
+
225
+ self.assertEqual(1, len(problems))
226
+ self.assertIn('content', problems[0])
227
+ self.assertIn('texture-1', problems[0])
228
+ self.assertIn('不得使用', problems[0])
229
+
230
+ def test_layout_must_use_its_bound_background_with_query_and_fragment(self):
231
+ with tempfile.TemporaryDirectory() as root:
232
+ self.write_background_pack(root)
233
+ html = self.write_html(
234
+ root,
235
+ '<deck-stage><section data-pptx-layout="content" '
236
+ 'style="background-image:url('
237
+ '\'assets/pptx-claude/backgrounds/content.webp?v=2#slide\')">'
238
+ '正文</section></deck-stage>',
239
+ )
240
+
241
+ self.assertEqual(
242
+ [],
243
+ validate_layout_assets(root, html, 'assets/pptx-claude'),
244
+ )
245
+
246
+ def test_repeated_asset_slots_require_repeated_placements(self):
247
+ with tempfile.TemporaryDirectory() as root:
248
+ self.write_texture_pack(root)
249
+ with open(os.path.join(root, 'layouts.md'), 'w', encoding='utf-8') as stream:
250
+ stream.write(
251
+ '---\n'
252
+ 'canvas: 1920x1080\n'
253
+ 'layouts:\n'
254
+ ' cover:\n'
255
+ ' role: cover\n'
256
+ ' slots:\n'
257
+ ' - {role: texture, box: [0, 0, 100, 100], type: pic, asset: texture-1}\n'
258
+ ' - {role: texture, box: [1800, 980, 100, 100], type: pic, asset: texture-1}\n'
259
+ '---\n'
260
+ )
261
+ html = self.write_html(
262
+ root,
263
+ '<deck-stage><section data-pptx-layout="cover">'
264
+ '<img src="assets/pptx-claude/textures/1.webp"></section></deck-stage>',
265
+ )
266
+
267
+ problems = validate_layout_assets(root, html, 'assets/pptx-claude')
268
+
269
+ self.assertEqual(1, len(problems))
270
+ self.assertIn('共 2 处', problems[0])
271
+ self.assertIn('缺少 1 处', problems[0])
272
+
273
+ def test_legacy_logo_scope_entrypoint_keeps_failure_exit_code(self):
274
+ with tempfile.TemporaryDirectory() as root:
275
+ self.write_texture_pack(root)
276
+ html = self.write_html(
277
+ root,
278
+ '<deck-stage><section data-pptx-layout="cover">'
279
+ '<img src="assets/generated/replacement.webp"></section></deck-stage>',
280
+ )
281
+
282
+ result = subprocess.run(
283
+ [
284
+ sys.executable,
285
+ os.path.join(os.path.dirname(__file__), 'verify_logo_scope.py'),
286
+ root,
287
+ html,
288
+ '--asset-prefix',
289
+ 'assets/pptx-claude',
290
+ ],
291
+ capture_output=True,
292
+ check=False,
293
+ text=True,
294
+ )
295
+
296
+ self.assertEqual(1, result.returncode)
297
+ self.assertIn('PPTX_LAYOUT_ASSETS: FAIL', result.stdout)
298
+
146
299
 
147
300
  if __name__ == '__main__':
148
301
  unittest.main()
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env python3
2
+ """Verify that generated slides honor every asset bound to their PPTX layout."""
3
+ import argparse
4
+ import posixpath
5
+ import re
6
+ import sys
7
+ from collections import Counter
8
+ from html.parser import HTMLParser
9
+ from urllib.parse import urlsplit
10
+
11
+ from check_v2 import Pack
12
+
13
+
14
+ URL_RE = re.compile(r'url\(\s*[\'"]?([^\'")\s]+)', re.I)
15
+ VOID_TAGS = {
16
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
17
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
18
+ }
19
+
20
+
21
+ def normalized_path(value):
22
+ path = urlsplit(value).path.replace('\\', '/')
23
+ return posixpath.normpath(path).lstrip('./')
24
+
25
+
26
+ def bound_asset_ids(value, known_asset_ids):
27
+ found = Counter()
28
+ if isinstance(value, dict):
29
+ for key, child in value.items():
30
+ if (key in ('asset', 'background')
31
+ and isinstance(child, str)
32
+ and child in known_asset_ids):
33
+ found[child] += 1
34
+ found.update(bound_asset_ids(child, known_asset_ids))
35
+ elif isinstance(value, list):
36
+ for child in value:
37
+ found.update(bound_asset_ids(child, known_asset_ids))
38
+ return found
39
+
40
+
41
+ def layout_asset_contract(pack):
42
+ known_asset_ids = set(pack.assets)
43
+ required = {}
44
+ owners = {}
45
+ for layout_name, (layout, _) in pack.layouts.items():
46
+ asset_counts = bound_asset_ids(layout, known_asset_ids)
47
+ required[layout_name] = asset_counts
48
+ for asset_id in asset_counts:
49
+ owners.setdefault(asset_id, set()).add(layout_name)
50
+ return required, owners
51
+
52
+
53
+ def asset_urls(pack, asset_prefix, asset_ids):
54
+ prefix = normalized_path(asset_prefix).rstrip('/')
55
+ urls = {}
56
+ for asset_id in asset_ids:
57
+ entry, _ = pack.assets.get(asset_id, (None, None))
58
+ if not isinstance(entry, dict):
59
+ continue
60
+ path = entry.get('path')
61
+ if not isinstance(path, str) or not path:
62
+ continue
63
+ relative = normalized_path(path)
64
+ if relative.startswith('assets/'):
65
+ relative = relative[len('assets/'):]
66
+ urls[posixpath.join(prefix, relative)] = asset_id
67
+ return urls
68
+
69
+
70
+ def urls_from_attrs(attrs):
71
+ urls = []
72
+ for key, value in attrs:
73
+ if not value:
74
+ continue
75
+ if key.lower() in ('src', 'href'):
76
+ urls.append(value)
77
+ elif key.lower() == 'srcset':
78
+ urls.extend(item.strip().split(' ', 1)[0] for item in value.split(','))
79
+ elif key.lower() == 'style':
80
+ urls.extend(URL_RE.findall(value))
81
+ return urls
82
+
83
+
84
+ class SlideAssetParser(HTMLParser):
85
+ def __init__(self):
86
+ super().__init__()
87
+ self.slides = []
88
+ self._tags = []
89
+ self._sections = []
90
+ self._active_slides = []
91
+ self._style_depth = 0
92
+ self.outside_urls = []
93
+
94
+ def handle_starttag(self, tag, attrs):
95
+ tag = tag.lower()
96
+ urls = urls_from_attrs(attrs)
97
+ parent = self._tags[-1] if self._tags else None
98
+ if tag == 'section':
99
+ slide = (
100
+ {'layout': dict(attrs).get('data-pptx-layout'), 'urls': urls}
101
+ if parent == 'deck-stage' else None
102
+ )
103
+ self._sections.append(slide)
104
+ if slide is not None:
105
+ self._active_slides.append(slide)
106
+ elif self._active_slides:
107
+ self._active_slides[-1]['urls'].extend(urls)
108
+ else:
109
+ self.outside_urls.extend(urls)
110
+ if tag == 'style':
111
+ self._style_depth += 1
112
+ if tag not in VOID_TAGS:
113
+ self._tags.append(tag)
114
+
115
+ def handle_startendtag(self, tag, attrs):
116
+ if self._active_slides:
117
+ self._active_slides[-1]['urls'].extend(urls_from_attrs(attrs))
118
+ else:
119
+ self.outside_urls.extend(urls_from_attrs(attrs))
120
+
121
+ def handle_endtag(self, tag):
122
+ tag = tag.lower()
123
+ if tag == 'style' and self._style_depth:
124
+ self._style_depth -= 1
125
+ if tag == 'section' and self._sections:
126
+ slide = self._sections.pop()
127
+ if slide is not None:
128
+ self.slides.append(slide)
129
+ self._active_slides.pop()
130
+ if tag not in VOID_TAGS and self._tags:
131
+ self._tags.pop()
132
+
133
+ def handle_data(self, data):
134
+ if not self._style_depth:
135
+ return
136
+ self.outside_urls.extend(URL_RE.findall(data))
137
+
138
+
139
+ def validate_layout_assets(pack_dir, html_path, asset_prefix):
140
+ """Return violations of the asset contract declared by each layout."""
141
+ pack = Pack(pack_dir)
142
+ required, owners = layout_asset_contract(pack)
143
+ known_urls = asset_urls(pack, asset_prefix, owners)
144
+ if not known_urls:
145
+ return []
146
+
147
+ with open(html_path, encoding='utf-8') as stream:
148
+ text = stream.read()
149
+ parser = SlideAssetParser()
150
+ parser.feed(text)
151
+ parser.close()
152
+
153
+ problems = []
154
+ for url in parser.outside_urls:
155
+ asset_id = known_urls.get(normalized_path(url))
156
+ if asset_id:
157
+ problems.append(
158
+ '模板资产 %s 出现在 slide section 外,无法核验页型归属' % asset_id)
159
+ for number, slide in enumerate(parser.slides, 1):
160
+ layout = slide['layout']
161
+ if not layout:
162
+ problems.append('第 %d 页缺少 data-pptx-layout,无法核验模板资产归属' % number)
163
+ continue
164
+ if layout not in pack.layouts:
165
+ problems.append('第 %d 页声明了不存在的模板页型: %s' % (number, layout))
166
+ continue
167
+ used_asset_counts = Counter(
168
+ known_urls[normalized_path(url)]
169
+ for url in slide['urls']
170
+ if normalized_path(url) in known_urls
171
+ )
172
+ for asset_id in sorted(used_asset_counts):
173
+ if layout not in owners.get(asset_id, set()):
174
+ allowed = '、'.join(sorted(owners.get(asset_id) or ())) or '(无)'
175
+ problems.append(
176
+ '第 %d 页页型 %s 不得使用 %s;只允许: %s'
177
+ % (number, layout, asset_id, allowed))
178
+ for asset_id, required_count in sorted(required.get(layout, {}).items()):
179
+ missing_count = required_count - used_asset_counts[asset_id]
180
+ if missing_count > 0:
181
+ problems.append(
182
+ '第 %d 页页型 %s 必须使用其绑定资产 %s 共 %d 处,当前缺少 %d 处'
183
+ % (number, layout, asset_id, required_count, missing_count))
184
+ return problems
185
+
186
+
187
+ def main(argv=None):
188
+ parser = argparse.ArgumentParser(
189
+ description='Verify that generated deck HTML honors PPTX layout asset bindings.')
190
+ parser.add_argument('pack_dir')
191
+ parser.add_argument('html_path')
192
+ parser.add_argument('--asset-prefix', required=True)
193
+ args = parser.parse_args(argv)
194
+
195
+ problems = validate_layout_assets(args.pack_dir, args.html_path, args.asset_prefix)
196
+ if not problems:
197
+ print('PPTX_LAYOUT_ASSETS: PASS')
198
+ return 0
199
+ print('PPTX_LAYOUT_ASSETS: FAIL count=%d' % len(problems))
200
+ for problem in problems:
201
+ print('[layoutAssets] %s' % problem)
202
+ return 1
203
+
204
+
205
+ if __name__ == '__main__':
206
+ sys.exit(main())
@@ -1,187 +1,11 @@
1
1
  #!/usr/bin/env python3
2
- """Verify that generated slides use template logos only on owning archetypes."""
3
- import argparse
4
- import posixpath
5
- import re
2
+ """Backward-compatible entrypoint for PPTX layout asset verification."""
6
3
  import sys
7
- from html.parser import HTMLParser
8
- from urllib.parse import urlsplit
9
4
 
10
- from check_v2 import Pack
5
+ from verify_layout_assets import main, validate_layout_assets
11
6
 
12
7
 
13
- URL_RE = re.compile(r'url\(\s*[\'"]?([^\'")\s]+)', re.I)
14
- VOID_TAGS = {
15
- 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
16
- 'link', 'meta', 'param', 'source', 'track', 'wbr',
17
- }
18
-
19
-
20
- def normalized_path(value):
21
- path = urlsplit(value).path.replace('\\', '/')
22
- return posixpath.normpath(path).lstrip('./')
23
-
24
-
25
- def asset_urls(pack, asset_prefix):
26
- prefix = normalized_path(asset_prefix).rstrip('/')
27
- urls = {}
28
- for asset_id, (entry, _) in pack.assets.items():
29
- if not isinstance(entry, dict) or entry.get('kind') != 'logo':
30
- continue
31
- path = entry.get('path')
32
- if not isinstance(path, str) or not path:
33
- continue
34
- relative = normalized_path(path)
35
- if relative.startswith('assets/'):
36
- relative = relative[len('assets/'):]
37
- urls[posixpath.join(prefix, relative)] = asset_id
38
- return urls
39
-
40
-
41
- def contains_asset(value, asset_id):
42
- if isinstance(value, dict):
43
- return (value.get('asset') == asset_id
44
- or any(contains_asset(child, asset_id) for child in value.values()))
45
- if isinstance(value, list):
46
- return any(contains_asset(child, asset_id) for child in value)
47
- return False
48
-
49
-
50
- def logo_owners(pack):
51
- owners = {}
52
- for asset_url, asset_id in asset_urls(pack, '').items():
53
- del asset_url
54
- owners[asset_id] = {
55
- name
56
- for name, (layout, _) in pack.layouts.items()
57
- if contains_asset(layout, asset_id)
58
- }
59
- return owners
60
-
61
-
62
- def urls_from_attrs(attrs):
63
- urls = []
64
- for key, value in attrs:
65
- if not value:
66
- continue
67
- if key.lower() in ('src', 'href'):
68
- urls.append(value)
69
- elif key.lower() == 'srcset':
70
- urls.extend(item.strip().split(' ', 1)[0] for item in value.split(','))
71
- elif key.lower() == 'style':
72
- urls.extend(URL_RE.findall(value))
73
- return urls
74
-
75
-
76
- class SlideAssetParser(HTMLParser):
77
- def __init__(self):
78
- super().__init__()
79
- self.slides = []
80
- self._tags = []
81
- self._sections = []
82
- self._active_slides = []
83
- self._style_depth = 0
84
- self.outside_urls = []
85
-
86
- def handle_starttag(self, tag, attrs):
87
- tag = tag.lower()
88
- urls = urls_from_attrs(attrs)
89
- parent = self._tags[-1] if self._tags else None
90
- if tag == 'section':
91
- slide = (
92
- {'layout': dict(attrs).get('data-pptx-layout'), 'urls': urls}
93
- if parent == 'deck-stage' else None
94
- )
95
- self._sections.append(slide)
96
- if slide is not None:
97
- self._active_slides.append(slide)
98
- elif self._active_slides:
99
- self._active_slides[-1]['urls'].extend(urls)
100
- else:
101
- self.outside_urls.extend(urls)
102
- if tag == 'style':
103
- self._style_depth += 1
104
- if tag not in VOID_TAGS:
105
- self._tags.append(tag)
106
-
107
- def handle_startendtag(self, tag, attrs):
108
- if self._active_slides:
109
- self._active_slides[-1]['urls'].extend(urls_from_attrs(attrs))
110
- else:
111
- self.outside_urls.extend(urls_from_attrs(attrs))
112
-
113
- def handle_endtag(self, tag):
114
- tag = tag.lower()
115
- if tag == 'style' and self._style_depth:
116
- self._style_depth -= 1
117
- if tag == 'section' and self._sections:
118
- slide = self._sections.pop()
119
- if slide is not None:
120
- self.slides.append(slide)
121
- self._active_slides.pop()
122
- if tag not in VOID_TAGS and self._tags:
123
- self._tags.pop()
124
-
125
- def handle_data(self, data):
126
- if not self._style_depth:
127
- return
128
- self.outside_urls.extend(URL_RE.findall(data))
129
-
130
-
131
- def validate_logo_scope(pack_dir, html_path, asset_prefix):
132
- """Return every template-logo placement that does not match the slide archetype."""
133
- pack = Pack(pack_dir)
134
- known_urls = asset_urls(pack, asset_prefix)
135
- owners = logo_owners(pack)
136
- if not known_urls:
137
- return []
138
-
139
- with open(html_path, encoding='utf-8') as stream:
140
- text = stream.read()
141
- parser = SlideAssetParser()
142
- parser.feed(text)
143
- parser.close()
144
-
145
- problems = []
146
- for url in parser.outside_urls:
147
- asset_id = known_urls.get(normalized_path(url))
148
- if asset_id:
149
- problems.append(
150
- '模板 logo %s 出现在 slide section 外,无法核验页型归属' % asset_id)
151
- for number, slide in enumerate(parser.slides, 1):
152
- layout = slide['layout']
153
- if not layout:
154
- problems.append('第 %d 页缺少 data-pptx-layout,无法核验模板 logo 归属' % number)
155
- continue
156
- if layout not in pack.layouts:
157
- problems.append('第 %d 页声明了不存在的模板页型: %s' % (number, layout))
158
- continue
159
- for url in slide['urls']:
160
- asset_id = known_urls.get(normalized_path(url))
161
- if asset_id and layout not in owners.get(asset_id, set()):
162
- allowed = '、'.join(sorted(owners.get(asset_id) or ())) or '(无)'
163
- problems.append(
164
- '第 %d 页页型 %s 不得使用 %s;只允许: %s'
165
- % (number, layout, asset_id, allowed))
166
- return problems
167
-
168
-
169
- def main(argv=None):
170
- parser = argparse.ArgumentParser(
171
- description='Verify that generated deck HTML places PPTX logos only on owning layouts.')
172
- parser.add_argument('pack_dir')
173
- parser.add_argument('html_path')
174
- parser.add_argument('--asset-prefix', required=True)
175
- args = parser.parse_args(argv)
176
-
177
- problems = validate_logo_scope(args.pack_dir, args.html_path, args.asset_prefix)
178
- if not problems:
179
- print('PPTX_LOGO_SCOPE: PASS')
180
- return 0
181
- print('PPTX_LOGO_SCOPE: FAIL count=%d' % len(problems))
182
- for problem in problems:
183
- print('[logoScope] %s' % problem)
184
- return 1
8
+ validate_logo_scope = validate_layout_assets
185
9
 
186
10
 
187
11
  if __name__ == '__main__':