@lark-apaas/coding-steering 0.1.18-dev.21ea0ba → 0.1.18-dev.22911a7

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.
@@ -38,7 +38,7 @@ L 层判断单 schema(<l-out-dir> 四个文件,这段就是填写说明书
38
38
  assets: # 可选;无资产包可整段省略
39
39
  - id: bg-cover # 必填。命名规则 <kind 前缀>-<语义名>,
40
40
  # logo- / slogan- / bg- / texture- / icon-
41
- source_media: image-1-1.jpeg # media-out/ 里的**原图**文件名(不是压缩版)
41
+ source_media: <原图文件名> # media-out/ 里的**原图**文件名(不是压缩版)
42
42
  kind: background # logo|slogan|background|texture|icon
43
43
  role: cover # background/icon 用;封闭枚举见规范 §2
44
44
  theme: dark # 双主题包按需
@@ -80,9 +80,9 @@ L 层判断单 schema(<l-out-dir> 四个文件,这段就是填写说明书
80
80
 
81
81
  colors:
82
82
  surface: "#FFFFFF"
83
- primary: "#2D5A8E"
83
+ primary: "#RRGGBB"
84
84
  safe-area:
85
- content: {top: 60, right: 90, bottom: 113, left: 90, applies-to: [content]}
85
+ content: {top: <px>, right: <px>, bottom: <px>, left: <px>, applies-to: [content]}
86
86
  confidence: medium
87
87
 
88
88
  --------------------------------------------------------------------------------
@@ -98,7 +98,7 @@ L 层判断单 schema(<l-out-dir> 四个文件,这段就是填写说明书
98
98
  role: cover
99
99
  background: bg-cover
100
100
  slots:
101
- - {role: title, box: [257, 313, 1406, 130], type: title}
101
+ - {role: title, box: [<x>, <y>, <w>, <h>], type: title}
102
102
  confidence: high
103
103
 
104
104
  可选 `body:` 块标量 —— 追加到 layouts.md frontmatter 之后作为说明正文。
@@ -139,9 +139,11 @@ ASSET_CONSUMER_FIELDS = ['path', 'url', 'color', 'full', 'kind', 'role',
139
139
  ASSET_AUDIT_FIELDS = ['boxes', 'aspect', 'mark', 'confidence']
140
140
  KIND_PREFIX = {'background': 'bg', 'logo': 'logo', 'slogan': 'slogan',
141
141
  'texture': 'texture', 'icon': 'icon'}
142
- # stage1 ref/ 里随包分发的审计件(其余如 shapes.json 体量大、不进包)
143
- REF_CARRY = ('color-freq-raw.json', 'font-clusters.json', 's5-acceptance.json',
144
- 'content-clusters.json', 'notes.md')
142
+ # 交付包的 ref/ 只留 audit.yaml(人复核数值出处用,几 KB)。
143
+ # 频次原表、聚类原始数据、extract.json、重建图、logo 候选图全部留在 stage1 抽取目录,
144
+ # 不拷进包——规范原本指望「下发时链路剥离」,但链路上没有环节真的剥离,结果
145
+ # 审计材料带着「别读我」一起进消费上下文,还占掉包体的大头。
146
+ REF_CARRY = ()
145
147
 
146
148
 
147
149
  class Fail(SystemExit):
@@ -272,6 +274,10 @@ def truthy(v):
272
274
  return str(v).strip().lower() in ('1', 'true', 'yes', 'on')
273
275
 
274
276
 
277
+ # 浏览器能解码的图片格式。落进包的资产必须在此列,否则消费端引用到就是一张空白图。
278
+ WEB_SAFE_EXT = {'png', 'jpg', 'jpeg', 'webp', 'gif', 'svg', 'avif'}
279
+
280
+
275
281
  def asset_ext(name):
276
282
  return name.rsplit('.', 1)[-1].lower() if '.' in name else ''
277
283
 
@@ -351,12 +357,25 @@ def place_assets(manifest, extract, stage1, pack):
351
357
  entry['path'] = 'assets/%ss/%s.%s' % (kind, base, cext)
352
358
  if truthy(a.get('use_full')):
353
359
  oext = asset_ext(row['out'])
354
- fdst = os.path.join(sub, '%s@full.%s' % (base, oext))
355
- shutil.copy2(orig_path, fdst)
356
- copied.append(fdst)
357
- entry['full'] = 'assets/%ss/%s@full.%s' % (kind, base, oext)
360
+ if oext.lower() in WEB_SAFE_EXT:
361
+ fdst = os.path.join(sub, '%s@full.%s' % (base, oext))
362
+ shutil.copy2(orig_path, fdst)
363
+ copied.append(fdst)
364
+ entry['full'] = 'assets/%ss/%s@full.%s' % (kind, base, oext)
365
+ else:
366
+ # 原图是浏览器不解码的格式(tiff/bmp 之类)。落进包并在 design.md
367
+ # 里声明成可用资源,消费端引用它就是一张空白图——实测踩过一次,
368
+ # 封面与结束页因此空白。压缩版已经带着全部像素,full 不给。
369
+ print(' ⚠ %s 的原图是 .%s,浏览器不解码,只给压缩版' % (aid, oext))
358
370
  else:
359
371
  oext = asset_ext(row['out'])
372
+ if oext.lower() not in WEB_SAFE_EXT:
373
+ # 转码两条路(Pillow / sips)都没成,原图又是浏览器不解码的格式。
374
+ # 照落进去就是把一张永远显示不出来的图当资产下发——实测封面因此空白。
375
+ raise Fail('%s: 原图是 .%s,浏览器不解码,而转码没有产物'
376
+ '(extract.json 里看 transcode_blocked 的原因)。'
377
+ '装上 Pillow 重跑抽取,或把这条资产从 manifest 删掉'
378
+ '并在 gaps 写明。' % (aid, oext))
360
379
  dst = os.path.join(sub, '%s.%s' % (base, oext))
361
380
  shutil.copy2(orig_path, dst)
362
381
  copied.append(dst)
@@ -382,7 +401,7 @@ def place_assets(manifest, extract, stage1, pack):
382
401
  if boxes:
383
402
  au['boxes'] = boxes
384
403
  # aspect 取**未取整**的 box —— 从取整后的整数反算会明显偏
385
- # (volcano logo 224.1/47.8=4.688,用 224/48 算成 4.667)。
404
+ # 先取整再相除,误差会落到小数点后两位,logo 这种细长框尤其明显。
386
405
  raw = clusters[0]['box']
387
406
  if raw.get('h'):
388
407
  au['aspect'] = round(raw['w'] / float(raw['h']), 3)
@@ -406,6 +425,27 @@ def _pages_of(extract, source_media):
406
425
  return sorted(pages)
407
426
 
408
427
 
428
+ def _archetypes_using(layouts_text, aid, key='asset'):
429
+ """layouts.yaml 里哪些 archetype 引用了这个资产。
430
+
431
+ key='asset' 查 slots 里的图片槽;key='background' 查页型底图。
432
+ """
433
+ out, cur, sect = [], None, None
434
+ for line in (layouts_text or '').split('\n'):
435
+ if re.match(r'^\w[\w-]*:\s*$', line):
436
+ sect = line.split(':')[0]
437
+ continue
438
+ if sect != 'layouts':
439
+ continue
440
+ m = re.match(r'^ ([\w-]+):\s*$', line)
441
+ if m:
442
+ cur = m.group(1)
443
+ continue
444
+ if cur and re.search(r'%s:\s*%s\b' % (key, re.escape(aid)), line) and cur not in out:
445
+ out.append(cur)
446
+ return out
447
+
448
+
409
449
  def expand_placeholders(body, manifest, consumer, audit, extract, layouts_text):
410
450
  """body.md 里的 `{{ASSET_TABLE}}` / `{{LAYOUT_LIST}}` 由本脚本按落盘真值渲染——
411
451
  路径与页型清单是打包期才确定的事实,不该由 L 层手抄(抄错就是死链)。"""
@@ -415,18 +455,19 @@ def expand_placeholders(body, manifest, consumer, audit, extract, layouts_text):
415
455
  for aid, e in consumer.items():
416
456
  pages = _pages_of(extract, src_of.get(aid))
417
457
  box = (audit.get(aid) or {}).get('boxes') or []
418
- if e['kind'] == 'background' and e.get('role') == 'cover':
419
- when = '封面页整幅铺满,必用'
420
- elif e['kind'] == 'background':
421
- when = '内容页整幅铺满——哪个页型用哪张见 `layouts.md` 的 `background`'
422
- elif box:
423
- b = box[0]
424
- when = '固定位 (%d, %d),尺寸 %dx%d px' % tuple(b)
425
- when += (',全 %d 页里只出现在第 %s 页' % (extract['counts']['slides'],
426
- '、'.join(map(str, pages)))
427
- if pages and len(pages) <= 4 else ',每页固定放一次')
458
+ # 单元格保持短句:哪个页型用哪张由 `background` 字段决定,
459
+ # 那句说明放在表格前一次即可,逐行重复只是把同一句抄 N 遍。
460
+ if e['kind'] == 'background':
461
+ users = _archetypes_using(layouts_text, aid, key='background')
462
+ when = ('%s 用它' % '/'.join('`%s`' % o for o in users[:6])
463
+ if users else '未被任何页型引用')
428
464
  else:
429
- when = '按 `%s` 的语义使用' % e['kind']
465
+ # 位置逐页型不同(同一 logo 常在封面左上、内容页右上,尺寸也不同),
466
+ # 所以这里只给归属,坐标一律交给 layouts.md 的 slots。
467
+ owners = _archetypes_using(layouts_text, aid)
468
+ when = ('%s 这 %d 个页型带它' % ('/'.join('`%s`' % o for o in owners[:6]),
469
+ len(owners))
470
+ if owners else '⚠ 没有页型声明它的位置,本包不使用它')
430
471
  f = '`%s`' % e['path'] if e.get('path') else (
431
472
  '`%s`' % e['url'] if e.get('url') else '纯色 `%s`' % e.get('color'))
432
473
  if e.get('full'):
@@ -604,6 +645,47 @@ def _box_hit(box, idx):
604
645
  % (best[0], best[1], best[2], best[3], best[4], bestd))
605
646
 
606
647
 
648
+ # 判断产物:L 层看着背景图划出来的区域,本就不该命中普查值——整键豁免,
649
+ # 不要求写 derived。逼它们走 derived 只会把整段豁免掉,机检反而更弱。
650
+ JUDGEMENT_KEYS = frozenset(('avoid', 'text_safe', 'pairing_rule'))
651
+
652
+
653
+ def media_integrity(stage1, extract):
654
+ """extract.json 记录的尺寸,必须和磁盘上那个文件真实的尺寸一致。
655
+
656
+ 这条挡的是「记录全对、文件被顶替」——两个 media 的输出名撞车时,后写的覆盖先写的,
657
+ extract.json 里各自的记录都还是对的,任何只读记录的检查都发现不了;只有把记录和
658
+ 文件本身对一遍才抓得到。实测某模板因此把一张 109x109 的图当成了整页背景。
659
+ """
660
+ try:
661
+ from PIL import Image
662
+ except Exception:
663
+ return [] # 没有 Pillow 就量不了,跳过而不是假装通过
664
+ bad, seen = [], {}
665
+ for m in extract.get('media') or []:
666
+ for key, rel in (('source_px', m.get('out')),
667
+ ('compressed_px', m.get('compressed_out'))):
668
+ rec = m.get(key)
669
+ if not rel or not rec:
670
+ continue
671
+ path = os.path.join(stage1, rel)
672
+ if not os.path.exists(path):
673
+ bad.append('%s 的 %s 指向 %s,文件不存在' % (m['media'], key, rel))
674
+ continue
675
+ try:
676
+ with Image.open(path) as im:
677
+ real = list(im.size)
678
+ except Exception:
679
+ continue
680
+ if real != list(rec):
681
+ bad.append('%s 的 %s 记录 %s,但 %s 实际是 %s'
682
+ % (m['media'], key, rec, rel, real))
683
+ if rel in seen and seen[rel] != m['media']:
684
+ bad.append('%s 与 %s 都写到 %s' % (seen[rel], m['media'], rel))
685
+ seen[rel] = m['media']
686
+ return bad
687
+
688
+
607
689
  def trace_check(pack, extract, shapes, derived_values, derived_tokens, factor):
608
690
  """产物里每个 hex / 字号 / slot 坐标都必须可追溯到普查值或 derived 声明。"""
609
691
  idx = build_trace_index(extract, shapes)
@@ -614,6 +696,9 @@ def trace_check(pack, extract, shapes, derived_values, derived_tokens, factor):
614
696
  if not text:
615
697
  continue
616
698
  for lineno, path, raw in _scan_keyed(text):
699
+ if JUDGEMENT_KEYS & set(path):
700
+ checked['judgement'] += 1
701
+ continue
617
702
  exempt_token = any(k in derived_tokens for k in path)
618
703
  for m in HEX_RE.finditer(raw):
619
704
  val = '#' + m.group(1).upper()
@@ -762,106 +847,6 @@ def build_package_manifest(manifest, consumer, audit, extract, pack):
762
847
  return {k: v for k, v in pkg.items() if v is not None}
763
848
 
764
849
 
765
- def layout_fast_index(layouts_blocks, max_slots=4):
766
- if not layouts_blocks:
767
- return []
768
- blocks = {k: (inline, lines) for k, inline, lines in layouts_blocks}
769
- if 'layouts' not in blocks:
770
- return []
771
- items = []
772
- cur = None
773
- for line in blocks['layouts'][1]:
774
- m = re.match(r'^ ([\w-]+):\s*$', line)
775
- if m:
776
- cur = {'id': m.group(1), 'name': '', 'role': '', 'background': '', 'slots': []}
777
- items.append(cur)
778
- continue
779
- if not cur:
780
- continue
781
- m = re.match(r'^ (name|role|background):\s*(.+?)\s*$', line)
782
- if m:
783
- cur[m.group(1)] = unquote(m.group(2))
784
- continue
785
- m = re.match(r'^\s{6}-\s*\{(.+)\}\s*$', line)
786
- if m and len(cur['slots']) < max_slots:
787
- raw = m.group(1)
788
- role = re.search(r'role:\s*([^,}]+)', raw)
789
- box = re.search(r'box:\s*\[([^\]]+)\]', raw)
790
- typ = re.search(r'type:\s*([^,}]+)', raw)
791
- if role and box:
792
- label = unquote(role.group(1).strip())
793
- if typ:
794
- label += '/' + unquote(typ.group(1).strip())
795
- cur['slots'].append('%s [%s]' % (label, box.group(1).strip()))
796
- out = []
797
- for item in items:
798
- parts = ['`%s`' % item['id']]
799
- if item.get('name'):
800
- parts.append(item['name'])
801
- if item.get('role'):
802
- parts.append(item['role'])
803
- if item.get('background'):
804
- parts.append('背景 `%s`' % item['background'])
805
- slots = ';'.join(item['slots'])
806
- out.append('%s:%s' % (' / '.join(parts), slots or '按最接近用途套用'))
807
- return out
808
-
809
-
810
- def render_fast_path(manifest, consumer, has_sidecar, canvas, layouts_index=None):
811
- """Render the small consumer-first block that keeps runtime agents out of ref/."""
812
- cover = next((aid for aid, a in consumer.items()
813
- if a.get('kind') == 'background' and a.get('role') == 'cover'), None)
814
- content_bgs = [aid for aid, a in consumer.items()
815
- if a.get('kind') == 'background' and a.get('role') == 'content']
816
- logos = [aid for aid, a in consumer.items() if a.get('kind') in ('logo', 'slogan')]
817
- assets = []
818
- for aid, a in consumer.items():
819
- path = a.get('path') or a.get('color') or a.get('url')
820
- role = a.get('role') or a.get('kind')
821
- if path:
822
- assets.append('`%s` -> `%s` (%s)' % (aid, path, role))
823
- if len(assets) > 8:
824
- assets = assets[:8] + ['其余资产见 frontmatter `assets`,不要去 `ref/` 里临时挑图。']
825
-
826
- lines = [
827
- '## Agent Fast Path',
828
- '',
829
- '消费本风格时先读这一节;它是给生成 Agent 的短路径,目标是把风格理解控制在 1 分钟内,避免把审计材料重新理解一遍。',
830
- '',
831
- '- **时间预算**:风格导入最多做 1 次 `read_file design.md`。本节已经内联常用坐标,读完后必须直接开始生成,不要再探索风格包。',
832
- '- **只读入口**:常规生成只需要 `design.md`。只有本节的版式索引无法覆盖目标页时,才打开 %s。'
833
- % ('`layouts.md`' if has_sidecar else '`design.md` 里的 `layouts`'),
834
- '- **附件/zip 兜底**:如果当前内容来自 zip 附件的文本摘要,直接使用摘要中 `design.md` / `layouts.md` 的文本;不要尝试修复 zip、解析二进制、搜索附件目录或重建压缩包。',
835
- '- **禁止动作**:不要读取 `ref/color-freq-raw.json`、`ref/font-clusters.json`、`ref/extract.json`、`ref/rebuild/`、`ref/rebuild/png/*`;不要 summarize / view 参考页;不要重新统计颜色、字体或版式。',
836
- '- **信息来源优先级**:本节 > `## Usage` > frontmatter `assets` / `colors` / `typography` > `layouts.md`。除此之外的文件只用于人工审计,不用于生成。',
837
- '- **缺信息时降级**:如果某个细节本节没有写,用 frontmatter token 和最接近的 `layouts.md` archetype 推断;不要打开审计文件补证。',
838
- ]
839
- if canvas:
840
- lines.append('- **画布**:所有坐标按 `%dx%d` 绝对像素理解。' % tuple(canvas))
841
- if cover:
842
- lines.append('- **封面背景**:优先使用 `%s`;整幅铺满画布,禁止自造渐变替代。' % cover)
843
- if content_bgs:
844
- lines.append('- **内容页背景**:按 `layouts.md` 中 archetype 的 `background` 字段取;常用内容背景为 %s。'
845
- % '、'.join('`%s`' % x for x in content_bgs[:4]))
846
- if cover or content_bgs:
847
- lines.append('- **背景安全区**:背景图和版式必须配对。按 archetype 的 `background`、`text_safe`、`avoid` 一起放文字和卡片;标题、正文、关键数字、图表、卡片、时间线及其容器的外接矩形都不得压到背景视觉主体、强光斑、深色透明区上,透明容器也不能跨进禁放区。')
848
- if logos:
849
- lines.append('- **标识资产**:只使用 %s;不得重画、不得改比例。'
850
- % '、'.join('`%s`' % x for x in logos))
851
- lines += [
852
- '- **配色与字体**:颜色只取 frontmatter `colors`;字体/字号只取 frontmatter `typography`;内容主题不得引入新色相。',
853
- '- **版式**:优先使用下面内联版式索引;需要更多 slot 时才读 `layouts.md`;不要用 `ref/rebuild/png` 反推坐标。',
854
- ]
855
- if layouts_index:
856
- lines += ['', '内联版式索引(先用这里,不要为了选页型再读文件):']
857
- lines += ['- ' + x for x in layouts_index]
858
- if assets:
859
- lines += ['', '关键资产:']
860
- lines += ['- ' + a for a in assets]
861
- lines.append('')
862
- return '\n'.join(lines) + '\n'
863
-
864
-
865
850
  def strip_agent_fast_path(body):
866
851
  if '## Agent Fast Path' not in body:
867
852
  return body
@@ -869,8 +854,7 @@ def strip_agent_fast_path(body):
869
854
  count=1, flags=re.S).lstrip('\n')
870
855
 
871
856
 
872
- def build_design(manifest, l_frontmatter, consumer, body, has_sidecar, canvas,
873
- layouts_index=None):
857
+ def build_design(manifest, l_frontmatter, consumer, body, has_sidecar, canvas):
874
858
  blocks = {k: (inline, lines) for k, inline, lines in l_frontmatter}
875
859
  bad = set(blocks) - L_FRONTMATTER_KEYS
876
860
  if bad:
@@ -908,9 +892,9 @@ def build_design(manifest, l_frontmatter, consumer, body, has_sidecar, canvas,
908
892
  out.append('canvas: %dx%d' % tuple(canvas))
909
893
  out.append('---')
910
894
  text = '\n'.join(out) + '\n'
895
+ # Fast Path 已废弃:它是 Usage / Hard Rules / 资产表 / 页型清单的第二份副本。
896
+ # 规则的唯一出处是正文各段,这里只负责把历史产物里的残留剥掉。
911
897
  body = strip_agent_fast_path(body)
912
- text += '\n' + render_fast_path(manifest, consumer, has_sidecar, canvas,
913
- layouts_index=layouts_index)
914
898
  if body:
915
899
  text += body if body.startswith('\n') else '\n' + body
916
900
  if not text.endswith('\n'):
@@ -918,26 +902,137 @@ def build_design(manifest, l_frontmatter, consumer, body, has_sidecar, canvas,
918
902
  return text
919
903
 
920
904
 
905
+ def shrink_safe_area(lines):
906
+ """text_safe 与 avoid 相交时把安全区收掉重叠的那部分。
907
+
908
+ text_safe 是脚本按「该背景各页型的槽位并集」算的,而模板里的槽位本身可能就压在
909
+ 主视觉上;avoid 是看图的人填的。两者从不同来源来,会直接打架——实测一张背景的
910
+ text_safe 有 34% 落在 avoid 里,消费端按 text_safe 把标题放进了禁放区,正好压在
911
+ 背景的山峰主体上。这里以 avoid 为准收缩:能不能放字是看图的人说了算。
912
+ """
913
+ def parse_box(s):
914
+ m = re.findall(r'-?\d+', s)
915
+ return [int(x) for x in m[:4]] if len(m) >= 4 else None
916
+
917
+ ts_i = ts = None
918
+ avoids = []
919
+ for i, ln in enumerate(lines):
920
+ st = ln.strip()
921
+ if st.startswith('text_safe:'):
922
+ ts_i, ts = i, parse_box(st.split(':', 1)[1].split('#')[0])
923
+ elif st.startswith('avoid:'):
924
+ for chunk in re.findall(r'box:\s*\[[^\]]*\]', st):
925
+ b = parse_box(chunk)
926
+ if b:
927
+ avoids.append(b)
928
+ if ts is None or not avoids:
929
+ return lines, None
930
+ x0, y0, x1, y1 = ts[0], ts[1], ts[0] + ts[2], ts[1] + ts[3]
931
+ for a in avoids:
932
+ ax0, ay0, ax1, ay1 = a[0], a[1], a[0] + a[2], a[1] + a[3]
933
+ if ax1 <= x0 or ax0 >= x1 or ay1 <= y0 or ay0 >= y1:
934
+ continue # 不相交
935
+ # 从被侵占得最少的一边切:优先保留面积最大的剩余矩形
936
+ cands = []
937
+ if ax0 > x0:
938
+ cands.append((x0, y0, ax0, y1))
939
+ if ax1 < x1:
940
+ cands.append((ax1, y0, x1, y1))
941
+ if ay0 > y0:
942
+ cands.append((x0, y0, x1, ay0))
943
+ if ay1 < y1:
944
+ cands.append((x0, ay1, x1, y1))
945
+ if not cands:
946
+ return lines, 'text_safe 被 avoid 完全覆盖,这张背景没有可放文字的区域'
947
+ x0, y0, x1, y1 = max(cands, key=lambda c: (c[2] - c[0]) * (c[3] - c[1]))
948
+ new = [x0, y0, x1 - x0, y1 - y0]
949
+ if new == ts:
950
+ return lines, None
951
+ lines = list(lines)
952
+ lines[ts_i] = ' text_safe: [%d, %d, %d, %d] # 已按 avoid 收缩(原 %s)' % (
953
+ new[0], new[1], new[2], new[3], ts)
954
+ return lines, None
955
+
956
+
921
957
  def build_layouts_md(layouts_blocks, canvas):
922
958
  blocks = {k: (inline, lines) for k, inline, lines in layouts_blocks}
923
959
  if 'canvas' in blocks:
924
960
  raise Fail('layouts.yaml 不要写 canvas —— 脚本从 extract.json 取')
925
961
  if 'layouts' not in blocks:
926
962
  raise Fail('layouts.yaml 缺顶层键 `layouts:`')
927
- # `names:` 是给 L 层集中改中文页型名的一块——在这里并回各 archetype,不进产物
928
- names = {}
929
- for line in blocks.get('names', ('', []))[1]:
930
- m = re.match(r'^\s{2}([\w-]+):\s*(.+?)\s*$', line)
963
+ # `names:` / `bg_rules:` 是给 L 层集中填判断的两块扁平区——在这里并回各
964
+ # archetype,本身不进产物。让 L 层只改扁平键值,别去动 layouts 里的
965
+ # slots/confidence 结构(嵌套结构手改极易破坏缩进,进而静默改变语义)。
966
+ names, roles = {}, {}
967
+ for key, sink in (('names', names), ('roles', roles)):
968
+ for line in blocks.get(key, ('', []))[1]:
969
+ m = re.match(r'^\s{2}([\w-]+):\s*(.+?)\s*$', line)
970
+ if m:
971
+ sink[m.group(1)] = unquote(m.group(2))
972
+ bg_rules, cur = {}, None
973
+ for line in blocks.get('bg_rules', ('', []))[1]:
974
+ # 键后面允许行内注释(草案会标「用它的页型:…」)
975
+ m = re.match(r'^\s{2}([\w-]+):\s*(?:#.*)?$', line)
931
976
  if m:
932
- names[m.group(1)] = unquote(m.group(2))
933
- out = ['---', 'canvas: %dx%d' % tuple(canvas), 'layouts:']
977
+ cur = m.group(1)
978
+ bg_rules[cur] = []
979
+ continue
980
+ if cur and line.strip():
981
+ bg_rules[cur].append(' ' + line.strip())
982
+ out = ['---', 'canvas: %dx%d' % tuple(canvas)]
983
+ # 禁放区是背景的属性,按背景写一次;页型只留 `background:` 指针。
984
+ # 合并进每个页型会把同一句话按页型数复制 N 遍。
985
+ if bg_rules:
986
+ out.append('backgrounds:')
987
+ for bg, lines in bg_rules.items():
988
+ lines, err = shrink_safe_area(lines)
989
+ if err:
990
+ raise Fail('%s: %s' % (bg, err))
991
+ out.append(' %s:' % bg)
992
+ out += lines
993
+ out.append('layouts:')
934
994
  for line in blocks['layouts'][1]:
995
+ # 判断单里的结构事实(栅格、间距序列、样张字数、命中配方)是给 L 层判断用的,
996
+ # 不进产物——消费端要的是结论,不是推导过程。
997
+ if line.lstrip().startswith('#'):
998
+ continue
935
999
  out.append(line)
936
1000
  m = re.match(r'^ ([\w-]+):\s*$', line)
937
1001
  if m and m.group(1) in names:
938
1002
  out.append(' name: "%s"' % names.pop(m.group(1)))
1003
+ if m and m.group(1) in roles:
1004
+ out.append(' role: %s' % roles.pop(m.group(1)))
939
1005
  if names:
940
1006
  raise Fail('names 里这些页型在 layouts 下找不到:%s' % ', '.join(sorted(names)))
1007
+ if roles:
1008
+ raise Fail('roles 里这些页型在 layouts 下找不到:%s' % ', '.join(sorted(roles)))
1009
+ missing_role = [k for k in re.findall(r'^ ([\w-]+):\s*$', '\n'.join(blocks['layouts'][1]), re.M)
1010
+ if not re.search(r'^ %s:\s*$(?:\n(?! \S).*)*?\n role:' % re.escape(k),
1011
+ '\n'.join(out), re.M)]
1012
+ if missing_role:
1013
+ raise Fail('这些页型没有 role(在 layouts.yaml 的 roles 段填):%s' % ', '.join(missing_role))
1014
+ # flow 与 slots 二选一:两份都留下,消费端不知道该听哪份坐标——design.md 正文与
1015
+ # layouts.md 打架就是这么来的,别重演。
1016
+ both, cur, has = [], None, {}
1017
+ for line in blocks['layouts'][1]:
1018
+ m = re.match(r'^ ([\w-]+):\s*$', line)
1019
+ if m:
1020
+ if cur and has.get('flow') and has.get('slots'):
1021
+ both.append(cur)
1022
+ cur, has = m.group(1), {}
1023
+ continue
1024
+ m = re.match(r'^ (flow|slots):\s*$', line)
1025
+ if m:
1026
+ has[m.group(1)] = True
1027
+ if cur and has.get('flow') and has.get('slots'):
1028
+ both.append(cur)
1029
+ if both:
1030
+ raise Fail('这些页型同时留了 flow 和 slots,二选一删掉另一个:%s' % ', '.join(both))
1031
+ declared = set(re.findall(r'^ background:\s*(\S+)\s*$',
1032
+ '\n'.join(blocks['layouts'][1]), re.M))
1033
+ stray = set(bg_rules) - declared
1034
+ if stray:
1035
+ raise Fail('backgrounds 段里这些背景没有任何页型在用:%s' % ', '.join(sorted(stray)))
941
1036
  out.append('---')
942
1037
  text = '\n'.join(out) + '\n'
943
1038
  if 'body' in blocks:
@@ -993,6 +1088,12 @@ def main(argv=None):
993
1088
  if left:
994
1089
  raise Fail('判断单还有 %d 处草案占位没改(TODO 是 draft.py 留给 L 层的判断点):\n %s'
995
1090
  % (len(left), '\n '.join(left)))
1091
+ mdesc = re.search(r'^description:\s*[|>]?\s*\n((?:\s+\S.*\n?)+)',
1092
+ open(os.path.join(lout, 'manifest.yaml'), encoding='utf-8').read(), re.M)
1093
+ if mdesc and len(re.sub(r'\s+', '', mdesc.group(1))) < 20:
1094
+ raise Fail('manifest 的 description 只有 %d 个字符——它是消费模型定调的唯一入口,'
1095
+ '写清底色/主色/字形/版面骨架,不要留占位'
1096
+ % len(re.sub(r'\s+', '', mdesc.group(1))))
996
1097
 
997
1098
  manifest = read_manifest(os.path.join(lout, 'manifest.yaml'))
998
1099
  if args.style_name:
@@ -1016,34 +1117,23 @@ def main(argv=None):
1016
1117
 
1017
1118
  lay_text = open(lay_path, encoding='utf-8').read() if os.path.exists(lay_path) else ''
1018
1119
  body = expand_placeholders(body, manifest, consumer, audit, extract, lay_text)
1019
- layouts_index = layout_fast_index(layouts_blocks)
1020
1120
  design = build_design(manifest, l_fm, consumer, body,
1021
- has_sidecar=layouts_blocks is not None, canvas=canvas,
1022
- layouts_index=layouts_index)
1121
+ has_sidecar=layouts_blocks is not None, canvas=canvas)
1023
1122
  with open(os.path.join(pack, 'design.md'), 'w', encoding='utf-8') as f:
1024
1123
  f.write(design)
1025
1124
  if layouts_blocks is not None:
1026
1125
  with open(os.path.join(pack, 'layouts.md'), 'w', encoding='utf-8') as f:
1027
1126
  f.write(build_layouts_md(layouts_blocks, canvas))
1028
1127
 
1029
- ref = os.path.join(pack, 'ref')
1128
+ # 审计记录写回**抽取工作目录**,不进交付包:包是消费产物,`ref/` 里的东西
1129
+ # 没有任何门禁读、消费模型也用不上,放进去只会让「别读我」和「几 MB 材料」同时下发。
1130
+ ref = os.path.join(stage1, 'ref')
1030
1131
  os.makedirs(ref, exist_ok=True)
1031
- with open(os.path.join(ref, 'audit.yaml'), 'w', encoding='utf-8') as f:
1132
+ audit_path = os.path.join(ref, 'audit.yaml')
1133
+ with open(audit_path, 'w', encoding='utf-8') as f:
1032
1134
  f.write(render_audit(manifest, extract, audit))
1033
1135
  carried = []
1034
- for name in REF_CARRY:
1035
- srcf = os.path.join(stage1, 'ref', name)
1036
- if os.path.exists(srcf):
1037
- shutil.copy2(srcf, os.path.join(ref, name))
1038
- carried.append(name)
1039
- shutil.copy2(ex_path, os.path.join(ref, 'extract.json'))
1040
- carried.append('extract.json')
1041
- for sub in ('rebuild', 'logo-candidates'):
1042
- s = os.path.join(stage1, 'ref', sub)
1043
- if os.path.isdir(s):
1044
- shutil.copytree(s, os.path.join(ref, sub), dirs_exist_ok=True)
1045
- carried.append(sub + '/')
1046
- # L 层自备的 ref 补充件(判断理由、版式溯源等)原样带入
1136
+ # L 层自备的 ref 补充件(判断理由、版式溯源等)也归到抽取目录
1047
1137
  l_ref = os.path.join(lout, 'ref')
1048
1138
  if os.path.isdir(l_ref):
1049
1139
  shutil.copytree(l_ref, ref, dirs_exist_ok=True)
@@ -1061,7 +1151,9 @@ def main(argv=None):
1061
1151
  print(' assets %d 条目 / %d 文件落盘' % (len(consumer), len(copied)))
1062
1152
  for d in copied:
1063
1153
  print(' %-52s %8d B' % (os.path.relpath(d, pack), os.path.getsize(d)))
1064
- print(' ref/ %s' % ', '.join(carried))
1154
+ print(' 审计记录 -> %s%s(不进交付包)'
1155
+ % (os.path.relpath(audit_path, os.path.dirname(stage1)),
1156
+ ' ' + ', '.join(carried) if carried else ''))
1065
1157
 
1066
1158
  # ---- 数值可追溯机检:产物里每个色值/字号/坐标都得能指回普查值
1067
1159
  derived_values, derived_tokens = set(), set()
@@ -1079,9 +1171,17 @@ def main(argv=None):
1079
1171
  shapes = json.load(open(sp, encoding='utf-8'))['shapes'] if os.path.exists(sp) else []
1080
1172
  problems, checked = trace_check(pack, extract, shapes,
1081
1173
  derived_values, derived_tokens, factor)
1174
+ integrity = media_integrity(stage1, extract)
1175
+ if integrity:
1176
+ print('\n--- 媒体产物完整性 ---')
1177
+ for b in integrity:
1178
+ print(' FAIL ' + b)
1179
+ raise Fail('media-out 里的文件和 extract.json 的记录对不上(%d 处)' % len(integrity))
1082
1180
  print('\n--- 数值可追溯机检 ---')
1083
- print(' 受检 hex %d / fontSize %d / slot box %d;derived 豁免 %d%s'
1181
+ print(' 受检 hex %d / fontSize %d / slot box %d;derived 豁免 %d%s%s'
1084
1182
  % (checked['hex'], checked['size'], checked['box'], checked['exempt'],
1183
+ ';判断键跳过 %d 行(avoid/text_safe/pairing_rule)' % checked['judgement']
1184
+ if checked['judgement'] else '',
1085
1185
  ';rebase_factor=%g' % factor if factor else ''))
1086
1186
  if not shapes:
1087
1187
  print(' ⚠ 未找到 %s,slot 坐标一项无法校验' % sp)
@@ -1108,6 +1208,7 @@ def main(argv=None):
1108
1208
  print('check_v1: 未探测到($DSM_V1_DIR / 同级 skill / 开发机路径均无)—— v1 门禁未跑,交付前必须补跑')
1109
1209
  if args.check_v1:
1110
1210
  print('\n--- check_v1 ---')
1211
+ sys.stdout.flush()
1111
1212
  r1 = subprocess.run([sys.executable, args.check_v1,
1112
1213
  os.path.join(pack, 'design.md'), 'slide'])
1113
1214
  rc = rc or r1.returncode
@@ -39,15 +39,15 @@ class Package:
39
39
  self.masters = sorted((n for n in self.names if MASTER_RE.match(n)), key=_num)
40
40
  self.themes, self.theme_discovery = self._find_themes(ct)
41
41
  # zip directory entries ('ppt/media/') must not be counted as assets —
42
- # 03 recon counted one, which is why its media totals run one high.
42
+ # they inflate media totals by one.
43
43
  self.media = sorted(n for n in self.names
44
44
  if n.startswith('ppt/media/') and not n.endswith('/'))
45
45
 
46
46
  def _find_themes(self, ct):
47
47
  """Theme parts come from [Content_Types].xml, not from a path pattern.
48
48
 
49
- Compressors relocate them — 飞书压缩版 puts them at
50
- ppt/slideMasters/theme/themeN.xml — and a `ppt/theme/` regex then finds
49
+ Compressors relocate them — some rewrite them under
50
+ ppt/slideMasters/theme/ — and a `ppt/theme/` regex then finds
51
51
  nothing to bind the masters to, so every schemeClr resolves to
52
52
  UNRESOLVED:no-scheme. The path regex stays as the fallback for packages
53
53
  whose content types are unreadable.
@@ -393,6 +393,9 @@ def walk_tree(el, ctx, out, path=(), xf=(1.0, 1.0, 0.0, 0.0), depth=0):
393
393
  blip = sp.find('p:blipFill/a:blip', NS)
394
394
  if blip is not None:
395
395
  rec['media'] = ctx.media_of(blip.get(R_EMBED)) or ctx.media_of(blip.get(R_LINK))
396
+ alpha = blip.find('a:alphaModFix', NS)
397
+ if alpha is not None and alpha.get('amt') is not None:
398
+ rec['opacity'] = round(int(alpha.get('amt')) / 100000.0, 6)
396
399
  svg = blip.find('a:extLst//asvg:svgBlip', NS)
397
400
  if svg is not None:
398
401
  rec['media_svg'] = ctx.media_of(svg.get(R_EMBED))
@@ -266,8 +266,8 @@ def _recipe_css(fill, line, radii, effects):
266
266
 
267
267
  def _sig(fill, line, effects):
268
268
  """分组键 = 填充 + 描边 + 效果。**不含圆角**——OOXML 圆角是 min(w,h) 的百分比,
269
- 同一配方在不同尺寸的卡上绝对 px 必然不同(feishu 三张 glassCard 实测 10.8/12.8/19.5),
270
- 把它计入键会把一个配方拆成三组;归一到哪一档是 L11 的判断,脚本只报区间。"""
269
+ 同一配方在不同尺寸的卡上绝对 px 必然不同,把它计入键会把一个配方拆成多组;
270
+ 归一到哪一档是判断,脚本只报区间。"""
271
271
  f = 'none'
272
272
  if isinstance(fill, dict):
273
273
  if fill.get('type') == 'solid':