@lark-apaas/coding-steering 0.1.28 → 0.1.30-alpha.20260809164221

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 (24) hide show
  1. package/package.json +1 -1
  2. package/steering/design-html/skills/animated-video/SKILL.md +1 -1
  3. package/steering/design-html/skills/charts/SKILL.md +1 -1
  4. package/steering/design-html/skills/data-viz/SKILL.md +1 -1
  5. package/steering/design-html/skills/frontend-design/SKILL.md +2 -2
  6. package/steering/design-html/skills/pptx-style-extract/SKILL.md +87 -0
  7. package/steering/design-html/skills/pptx-style-extract/font-fallback.yaml +129 -0
  8. package/steering/design-html/skills/pptx-style-extract/scripts/census.py +962 -0
  9. package/steering/design-html/skills/pptx-style-extract/scripts/check_v2.py +907 -0
  10. package/steering/design-html/skills/pptx-style-extract/scripts/draft.py +873 -0
  11. package/steering/design-html/skills/pptx-style-extract/scripts/extract.py +787 -0
  12. package/steering/design-html/skills/pptx-style-extract/scripts/ooxml.py +701 -0
  13. package/steering/design-html/skills/pptx-style-extract/scripts/package.py +935 -0
  14. package/steering/design-html/skills/pptx-style-extract/scripts/parts.py +490 -0
  15. package/steering/design-html/skills/pptx-style-extract/scripts/query.py +567 -0
  16. package/steering/design-html/skills/pptx-style-extract/scripts/render_pages.py +669 -0
  17. package/steering/design-html/skills/pptx-style-extract/scripts/verify_font.py +68 -0
  18. package/steering/design-html/skills/pptx-style-extract/v2-format-spec.md +191 -0
  19. package/steering/design-html/skills/preflight/SKILL.md +131 -26
  20. package/steering/design-html/skills/slide-deck/SKILL.md +19 -0
  21. package/steering/design-html/skills/{visual-report → visual-exposure}/SKILL.md +1 -1
  22. package/steering/design-html/skills/mini-game/SKILL.md +0 -71
  23. package/steering/design-html/skills/mini-game/references/three-js.md +0 -54
  24. package/steering/design-html/skills/preflight/scripts/probe.sh +0 -108
@@ -0,0 +1,701 @@
1
+ #!/usr/bin/env python3
2
+ """OOXML parsing primitives for stage-1 extraction (S3 color resolution + S4 shape facts).
3
+
4
+ All length quantities are normalised to px @1920-wide canvas with a single factor
5
+ (`Units.f` = 1920 / sldSz_cx), so coordinates, font sizes, letter spacing, line
6
+ spacing, insets and radii are directly comparable across samples with different
7
+ EMU canvases (方案 v0.2 §1 S4 归一化统一声明).
8
+ """
9
+ import posixpath
10
+
11
+ NS = {
12
+ 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
13
+ 'p': 'http://schemas.openxmlformats.org/presentationml/2006/main',
14
+ 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
15
+ 'rel': 'http://schemas.openxmlformats.org/package/2006/relationships',
16
+ 'ct': 'http://schemas.openxmlformats.org/package/2006/content-types',
17
+ 'p15': 'http://schemas.microsoft.com/office/powerpoint/2012/main',
18
+ 'asvg': 'http://schemas.microsoft.com/office/drawing/2016/SVG/main',
19
+ }
20
+ R_EMBED = '{%s}embed' % NS['r']
21
+ R_LINK = '{%s}link' % NS['r']
22
+ R_ID = '{%s}id' % NS['r']
23
+
24
+ EMU_PER_PT = 12700.0
25
+ CANVAS_W_PX = 1920
26
+
27
+ # clrScheme slot names vs the p:clrMap "map name" keys that point at them.
28
+ SCHEME_SLOTS = ('dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3',
29
+ 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink')
30
+ OFFICE_DEFAULT_ACCENTS = {'4472C4', 'ED7D31', 'A5A5A5', 'FFC000', '5B9BD5', '70AD47'}
31
+ OFFICE_DEFAULT_FONTS = {'Calibri', 'Calibri Light', 'Cambria', 'Aptos', 'Aptos Display'}
32
+
33
+ # Weight tokens carried in font names. Keys are lowercased and space/hyphen-stripped.
34
+ # Includes the 31-char-truncation artefacts seen in real files (SemiBol / DemiBol).
35
+ WEIGHT_TOKENS = {
36
+ 'thin': 100, 'hairline': 100,
37
+ 'extralight': 200, 'ultralight': 200, 'extralight': 200,
38
+ 'light': 300,
39
+ 'regular': 400, 'normal': 400, 'book': 400, 'roman': 400,
40
+ 'medium': 500,
41
+ 'semibold': 600, 'semibol': 600, 'demibold': 600, 'demibol': 600, 'demi': 600,
42
+ 'bold': 700,
43
+ 'extrabold': 800, 'ultrabold': 800,
44
+ 'black': 900, 'heavy': 900,
45
+ }
46
+ ITALIC_TOKENS = {'italic', 'oblique', 'it'}
47
+
48
+ # Deterministic latin<->CJK alias hints. Emitted as a separate `alias_group` field,
49
+ # never merged into counts, so the audit trail stays intact (see STAGE1-REPORT deviations).
50
+ FONT_ALIAS_GROUPS = {
51
+ 'fzlantinghei': ('方正兰亭黑', 'fzlantingheipro', 'fzlthpro', 'fzlthpros'),
52
+ 'bytesans': ('字节跳动', 'bytesans'),
53
+ }
54
+
55
+
56
+ def local(tag):
57
+ return tag.rsplit('}', 1)[-1]
58
+
59
+
60
+ def resolve_part(part, target):
61
+ """rels target (possibly '../media/x.png') -> package-absolute part name."""
62
+ if target.startswith('/'):
63
+ return target.lstrip('/')
64
+ return posixpath.normpath(posixpath.join(posixpath.dirname(part), target))
65
+
66
+
67
+ class Units:
68
+ """Single normalisation factor shared by every length quantity."""
69
+
70
+ def __init__(self, cx, cy):
71
+ self.cx, self.cy = cx, cy
72
+ self.f = CANVAS_W_PX / float(cx)
73
+ self.w = CANVAS_W_PX
74
+ self.h = round(cy * self.f)
75
+ self.emu_per_px = cx / float(CANVAS_W_PX)
76
+
77
+ def px(self, emu, nd=1):
78
+ if emu is None:
79
+ return None
80
+ return round(int(emu) * self.f, nd)
81
+
82
+ def pt100(self, v, nd=1):
83
+ """sz / spc / spcPts style values (1/100 pt) -> px."""
84
+ if v is None:
85
+ return None
86
+ return round(float(v) / 100.0 * EMU_PER_PT * self.f, nd)
87
+
88
+ def eighth_pt(self, v, nd=1):
89
+ """p15:guide pos (1/8 pt) -> px."""
90
+ if v is None:
91
+ return None
92
+ return round(float(v) / 8.0 * EMU_PER_PT * self.f, nd)
93
+
94
+
95
+ # --------------------------------------------------------------------- colour
96
+ def _lin(c):
97
+ c = c / 255.0
98
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
99
+
100
+
101
+ def _srgb(c):
102
+ c = max(0.0, min(1.0, c))
103
+ v = c * 12.92 if c <= 0.0031308 else 1.055 * (c ** (1 / 2.4)) - 0.055
104
+ return max(0, min(255, int(round(v * 255))))
105
+
106
+
107
+ def _rgb_to_hsl(r, g, b):
108
+ r, g, b = r / 255.0, g / 255.0, b / 255.0
109
+ mx, mn = max(r, g, b), min(r, g, b)
110
+ l = (mx + mn) / 2
111
+ if mx == mn:
112
+ return 0.0, 0.0, l
113
+ d = mx - mn
114
+ s = d / (2 - mx - mn) if l > 0.5 else d / (mx + mn)
115
+ if mx == r:
116
+ h = ((g - b) / d) % 6
117
+ elif mx == g:
118
+ h = (b - r) / d + 2
119
+ else:
120
+ h = (r - g) / d + 4
121
+ return h / 6, s, l
122
+
123
+
124
+ def _hue(p, q, t):
125
+ t = t % 1.0
126
+ if t < 1 / 6:
127
+ return p + (q - p) * 6 * t
128
+ if t < 1 / 2:
129
+ return q
130
+ if t < 2 / 3:
131
+ return p + (q - p) * (2 / 3 - t) * 6
132
+ return p
133
+
134
+
135
+ def _hsl_to_rgb(h, s, l):
136
+ if s == 0:
137
+ v = int(round(l * 255))
138
+ return v, v, v
139
+ q = l * (1 + s) if l < 0.5 else l + s - l * s
140
+ p = 2 * l - q
141
+ return (int(round(_hue(p, q, h + 1 / 3) * 255)),
142
+ int(round(_hue(p, q, h) * 255)),
143
+ int(round(_hue(p, q, h - 1 / 3) * 255)))
144
+
145
+
146
+ COLOR_TAGS = ('srgbClr', 'schemeClr', 'sysClr', 'prstClr', 'scrgbClr', 'hslClr')
147
+ PRST_CLR = {'black': '000000', 'white': 'FFFFFF', 'red': 'FF0000', 'green': '008000',
148
+ 'blue': '0000FF', 'gray': '808080', 'grey': '808080', 'yellow': 'FFFF00'}
149
+
150
+
151
+ def read_color(el):
152
+ """Parse one colour element into a raw, unresolved descriptor."""
153
+ if el is None:
154
+ return None
155
+ tag = local(el.tag)
156
+ if tag not in COLOR_TAGS:
157
+ return None
158
+ raw = {'type': tag}
159
+ if tag == 'sysClr':
160
+ raw['val'] = el.get('lastClr')
161
+ raw['sys'] = el.get('val')
162
+ elif tag == 'scrgbClr':
163
+ # r/g/b are linear-space percentages in 1/1000 % units.
164
+ raw['val'] = '%02X%02X%02X' % tuple(
165
+ _srgb(int(el.get(k, 0)) / 100000.0) for k in ('r', 'g', 'b'))
166
+ elif tag == 'hslClr':
167
+ r, g, b = _hsl_to_rgb(int(el.get('hue', 0)) / 21600000.0,
168
+ int(el.get('sat', 0)) / 100000.0,
169
+ int(el.get('lum', 0)) / 100000.0)
170
+ raw['val'] = '%02X%02X%02X' % (r, g, b)
171
+ elif tag == 'prstClr':
172
+ raw['val'] = PRST_CLR.get(el.get('val', ''), None)
173
+ raw['prst'] = el.get('val')
174
+ else:
175
+ raw['val'] = el.get('val')
176
+ mods = []
177
+ for m in el:
178
+ mods.append((local(m.tag), m.get('val')))
179
+ if mods:
180
+ raw['mods'] = mods
181
+ return raw
182
+
183
+
184
+ def raw_token(raw):
185
+ """Stable audit key, e.g. 'schemeClr:bg1(lumMod=60000)'."""
186
+ if not raw:
187
+ return None
188
+ t = '%s:%s' % ('schemeClr' if raw['type'] == 'schemeClr' else raw['type'], raw.get('val'))
189
+ if raw.get('mods'):
190
+ t += '(' + ','.join('%s=%s' % (k, v) for k, v in raw['mods']) + ')'
191
+ return t
192
+
193
+
194
+ def resolve_color(raw, clrmap=None, clrscheme=None, phclr=None):
195
+ """raw descriptor + master clrMap + theme clrScheme -> {hex, alpha, resolved}.
196
+
197
+ This is the schemeClr -> clrMap -> clrScheme indirection the PRD's
198
+ "do not resolve inheritance" rule does NOT cover (方案 v0.2 §3 难点 3).
199
+ """
200
+ if not raw:
201
+ return None
202
+ hexv, unresolved = None, None
203
+ if raw['type'] == 'schemeClr':
204
+ name = raw.get('val')
205
+ if name == 'phClr':
206
+ hexv = phclr
207
+ if hexv is None:
208
+ unresolved = 'phClr'
209
+ else:
210
+ slot = (clrmap or {}).get(name, name)
211
+ ent = (clrscheme or {}).get(slot)
212
+ if ent is None:
213
+ unresolved = 'no-scheme:%s' % name
214
+ else:
215
+ hexv = ent
216
+ else:
217
+ hexv = raw.get('val')
218
+ if hexv is None:
219
+ unresolved = 'unknown:%s' % raw['type']
220
+ out = {'raw': raw_token(raw), 'alpha': 100.0}
221
+ if unresolved or not hexv:
222
+ out['unresolved'] = unresolved or 'empty'
223
+ return out
224
+ hexv = hexv.lstrip('#').upper()
225
+ try:
226
+ r, g, b = int(hexv[0:2], 16), int(hexv[2:4], 16), int(hexv[4:6], 16)
227
+ except (ValueError, IndexError):
228
+ out['unresolved'] = 'bad-hex:%s' % hexv
229
+ return out
230
+ alpha = 100.0
231
+ for name, val in raw.get('mods', []):
232
+ if val is None:
233
+ continue
234
+ v = int(val)
235
+ if name == 'alpha':
236
+ alpha = v / 1000.0
237
+ elif name == 'lumMod':
238
+ h, s, l = _rgb_to_hsl(r, g, b)
239
+ r, g, b = _hsl_to_rgb(h, s, l * v / 100000.0)
240
+ elif name == 'lumOff':
241
+ h, s, l = _rgb_to_hsl(r, g, b)
242
+ r, g, b = _hsl_to_rgb(h, s, min(1.0, l + v / 100000.0))
243
+ elif name == 'satMod':
244
+ h, s, l = _rgb_to_hsl(r, g, b)
245
+ r, g, b = _hsl_to_rgb(h, min(1.0, s * v / 100000.0), l)
246
+ elif name == 'satOff':
247
+ h, s, l = _rgb_to_hsl(r, g, b)
248
+ r, g, b = _hsl_to_rgb(h, min(1.0, max(0.0, s + v / 100000.0)), l)
249
+ elif name == 'shade':
250
+ f = v / 100000.0
251
+ r, g, b = (_srgb(_lin(r) * f), _srgb(_lin(g) * f), _srgb(_lin(b) * f))
252
+ elif name == 'tint':
253
+ f = v / 100000.0
254
+ r, g, b = (_srgb(_lin(r) * f + (1 - f)), _srgb(_lin(g) * f + (1 - f)),
255
+ _srgb(_lin(b) * f + (1 - f)))
256
+ out['hex'] = '#%02X%02X%02X' % (r, g, b)
257
+ out['alpha'] = round(alpha, 1)
258
+ out['resolved'] = out['hex'] if alpha >= 100 else 'rgba(%d,%d,%d,%.3g)' % (r, g, b, alpha / 100.0)
259
+ return out
260
+
261
+
262
+ def luminance(hexv):
263
+ hexv = hexv.lstrip('#')
264
+ r, g, b = int(hexv[0:2], 16), int(hexv[2:4], 16), int(hexv[4:6], 16)
265
+ return 0.2126 * _lin(r) + 0.7152 * _lin(g) + 0.0722 * _lin(b)
266
+
267
+
268
+ # ------------------------------------------------------------------ fill/line
269
+ def describe_fill(container, ctx):
270
+ """solidFill / gradFill / blipFill / pattFill / noFill descriptor."""
271
+ if container is None:
272
+ return None
273
+ sf = container.find('a:solidFill', NS)
274
+ if sf is not None:
275
+ for ch in sf:
276
+ c = resolve_color(read_color(ch), ctx.clrmap, ctx.clrscheme)
277
+ if c:
278
+ return {'type': 'solid', 'color': c}
279
+ return {'type': 'solid'}
280
+ gf = container.find('a:gradFill', NS)
281
+ if gf is not None:
282
+ stops = []
283
+ for gs in gf.findall('a:gsLst/a:gs', NS):
284
+ c = None
285
+ for ch in gs:
286
+ c = resolve_color(read_color(ch), ctx.clrmap, ctx.clrscheme)
287
+ if c:
288
+ break
289
+ stops.append({'pos': round(int(gs.get('pos', 0)) / 1000.0, 2), 'color': c})
290
+ d = {'type': 'gradient', 'stops': stops}
291
+ lin = gf.find('a:lin', NS)
292
+ if lin is not None:
293
+ d['angle_deg'] = round(int(lin.get('ang', 0)) / 60000.0, 2)
294
+ d['scaled'] = lin.get('scaled') == '1'
295
+ path = gf.find('a:path', NS)
296
+ if path is not None:
297
+ d['path'] = path.get('path')
298
+ return d
299
+ bf = container.find('a:blipFill', NS)
300
+ if bf is not None:
301
+ blip = bf.find('a:blip', NS)
302
+ rid = blip.get(R_EMBED) if blip is not None else None
303
+ d = {'type': 'image', 'media': ctx.media_of(rid)}
304
+ sr = bf.find('a:srcRect', NS)
305
+ if sr is not None and sr.attrib:
306
+ d['crop'] = {k: round(int(v) / 1000.0, 2) for k, v in sr.attrib.items()}
307
+ if bf.find('a:tile', NS) is not None:
308
+ d['tile'] = True
309
+ return d
310
+ pf = container.find('a:pattFill', NS)
311
+ if pf is not None:
312
+ return {'type': 'pattern', 'preset': pf.get('prst')}
313
+ if container.find('a:noFill', NS) is not None:
314
+ return {'type': 'none'}
315
+ return None
316
+
317
+
318
+ def describe_line(shape_pr, ctx):
319
+ ln = shape_pr.find('a:ln', NS) if shape_pr is not None else None
320
+ if ln is None:
321
+ return None
322
+ d = {}
323
+ if ln.get('w'):
324
+ d['w_px'] = ctx.units.px(ln.get('w'), 2)
325
+ if ln.find('a:noFill', NS) is not None:
326
+ d['none'] = True
327
+ f = describe_fill(ln, ctx)
328
+ if f and f.get('type') == 'solid':
329
+ d['color'] = f.get('color')
330
+ elif f and f.get('type') == 'gradient':
331
+ d['gradient'] = f
332
+ dash = ln.find('a:prstDash', NS)
333
+ if dash is not None:
334
+ d['dash'] = dash.get('val')
335
+ for tag in ('headEnd', 'tailEnd'):
336
+ e = ln.find('a:%s' % tag, NS)
337
+ if e is not None and e.get('type') not in (None, 'none'):
338
+ d[tag] = e.get('type')
339
+ return d or None
340
+
341
+
342
+ EFFECT_LEN_ATTRS = ('blurRad', 'dist', 'sx', 'sy', 'rad')
343
+
344
+
345
+ def describe_effects(shape_pr, ctx):
346
+ if shape_pr is None:
347
+ return None
348
+ lst = shape_pr.find('a:effectLst', NS)
349
+ out = []
350
+ if lst is not None:
351
+ for e in lst:
352
+ d = {'type': local(e.tag)}
353
+ for k, v in e.attrib.items():
354
+ if k in ('blurRad', 'dist', 'rad'):
355
+ d[k + '_px'] = ctx.units.px(v, 2)
356
+ elif k == 'dir':
357
+ d['dir_deg'] = round(int(v) / 60000.0, 1)
358
+ else:
359
+ d[k] = v
360
+ for ch in e:
361
+ c = resolve_color(read_color(ch), ctx.clrmap, ctx.clrscheme)
362
+ if c:
363
+ d['color'] = c
364
+ break
365
+ out.append(d)
366
+ if shape_pr.find('a:effectDag', NS) is not None:
367
+ out.append({'type': 'effectDag'})
368
+ scene = shape_pr.find('a:scene3d', NS)
369
+ if scene is not None:
370
+ out.append({'type': 'scene3d'})
371
+ return out or None
372
+
373
+
374
+ def describe_geom(shape_pr, ctx, w_px=None, h_px=None):
375
+ if shape_pr is None:
376
+ return None, None
377
+ pg = shape_pr.find('a:prstGeom', NS)
378
+ if pg is None:
379
+ if shape_pr.find('a:custGeom', NS) is not None:
380
+ return {'prst': 'custGeom'}, None
381
+ return None, None
382
+ d = {'prst': pg.get('prst')}
383
+ adj = {}
384
+ for gd in pg.findall('a:avLst/a:gd', NS):
385
+ adj[gd.get('name')] = gd.get('fmla')
386
+ if adj:
387
+ d['adj'] = adj
388
+ radius = None
389
+ if d['prst'] in ('roundRect', 'round1Rect', 'round2SameRect', 'round2DiagRect',
390
+ 'snipRoundRect') and w_px and h_px:
391
+ fmla = adj.get('adj') or adj.get('adj1') or 'val 16667'
392
+ try:
393
+ val = float(str(fmla).split()[-1])
394
+ except (ValueError, IndexError):
395
+ val = 16667.0
396
+ radius = round(val / 100000.0 * min(w_px, h_px), 1)
397
+ return d, radius
398
+
399
+
400
+ # ------------------------------------------------------------------ text runs
401
+ def _lnspc(paragraph_pr, ctx):
402
+ if paragraph_pr is None:
403
+ return None
404
+ pct = paragraph_pr.find('a:lnSpc/a:spcPct', NS)
405
+ if pct is not None:
406
+ return {'mult': round(int(pct.get('val')) / 100000.0, 3)}
407
+ pts = paragraph_pr.find('a:lnSpc/a:spcPts', NS)
408
+ if pts is not None:
409
+ return {'px': ctx.units.pt100(pts.get('val'))}
410
+ return None
411
+
412
+
413
+ def _spc_before_after(paragraph_pr, ctx, tag):
414
+ if paragraph_pr is None:
415
+ return None
416
+ pct = paragraph_pr.find('a:%s/a:spcPct' % tag, NS)
417
+ if pct is not None:
418
+ return {'pct': round(int(pct.get('val')) / 1000.0, 2)}
419
+ pts = paragraph_pr.find('a:%s/a:spcPts' % tag, NS)
420
+ if pts is not None:
421
+ return {'px': ctx.units.pt100(pts.get('val'))}
422
+ return None
423
+
424
+
425
+ def font_weight(raw_name):
426
+ """Weight carried by the font *name*. `b="1"` is tracked separately (see
427
+ read_rpr's `bold`) because the name is the only source that distinguishes
428
+ Medium/SemiBold/DemiBold — collapsing both into one field loses the axis."""
429
+ return family_of(raw_name)[1] if raw_name else None
430
+
431
+
432
+ def family_of(raw):
433
+ """raw typeface -> (family, weight, italic). Weight is kept; only the
434
+ *family key* is stripped, so counting merges while 字重 stays readable."""
435
+ if not raw:
436
+ return None, None, False
437
+ name = raw.strip()
438
+ weight, italic = None, False
439
+ parts = name.replace('_', ' _').split(' ')
440
+ while len(parts) > 1:
441
+ tail = parts[-1].strip().lower().replace('-', '')
442
+ if tail in ITALIC_TOKENS:
443
+ italic = True
444
+ parts.pop()
445
+ continue
446
+ if tail in WEIGHT_TOKENS:
447
+ weight = WEIGHT_TOKENS[tail]
448
+ parts.pop()
449
+ continue
450
+ break
451
+ family = ' '.join(parts).replace(' _', '_').strip(' -')
452
+ return (family or name), weight, italic
453
+
454
+
455
+ def alias_group(family):
456
+ key = ''.join(ch for ch in family.lower() if ch.isalnum())
457
+ for grp, needles in FONT_ALIAS_GROUPS.items():
458
+ for n in needles:
459
+ nk = ''.join(ch for ch in n.lower() if ch.isalnum())
460
+ if nk and nk in key:
461
+ return grp
462
+ return None
463
+
464
+
465
+ def read_rpr(run_pr, ctx):
466
+ d = {}
467
+ if run_pr is None:
468
+ return d
469
+ if run_pr.get('sz'):
470
+ d['sz_px'] = ctx.units.pt100(run_pr.get('sz'))
471
+ if run_pr.get('b') == '1':
472
+ d['bold'] = True
473
+ if run_pr.get('i') == '1':
474
+ d['italic'] = True
475
+ if run_pr.get('u') and run_pr.get('u') != 'none':
476
+ d['underline'] = run_pr.get('u')
477
+ if run_pr.get('strike') and run_pr.get('strike') != 'noStrike':
478
+ d['strike'] = run_pr.get('strike')
479
+ if run_pr.get('spc'):
480
+ d['spc_px'] = ctx.units.pt100(run_pr.get('spc'), 2)
481
+ if run_pr.get('cap') and run_pr.get('cap') != 'none':
482
+ d['cap'] = run_pr.get('cap')
483
+ if run_pr.get('baseline') and run_pr.get('baseline') != '0':
484
+ d['baseline'] = int(run_pr.get('baseline')) / 1000.0
485
+ for tag in ('latin', 'ea', 'cs'):
486
+ e = run_pr.find('a:%s' % tag, NS)
487
+ if e is not None and e.get('typeface'):
488
+ d[tag] = e.get('typeface')
489
+ f = describe_fill(run_pr, ctx)
490
+ if f:
491
+ if f.get('type') == 'solid':
492
+ d['color'] = f.get('color')
493
+ else:
494
+ d['fill'] = f
495
+ ln = run_pr.find('a:ln', NS)
496
+ if ln is not None:
497
+ d['outline'] = True
498
+ w = font_weight(d.get('latin') or d.get('ea'))
499
+ if w:
500
+ d['weight'] = w
501
+ return d
502
+
503
+
504
+ def read_txbody(tx, ctx, kind='txBody'):
505
+ """Paragraphs with per-run facts + the part-local lstStyle type scale."""
506
+ if tx is None:
507
+ return None
508
+ out = {}
509
+ bp = tx.find('a:bodyPr', NS)
510
+ if bp is not None:
511
+ b = {}
512
+ for k in ('anchor', 'anchorCtr', 'vert', 'wrap', 'rot'):
513
+ if bp.get(k):
514
+ b[k] = bp.get(k)
515
+ ins = {}
516
+ for k in ('lIns', 'tIns', 'rIns', 'bIns'):
517
+ if bp.get(k) is not None:
518
+ ins[k] = ctx.units.px(bp.get(k))
519
+ if ins:
520
+ b['insets_px'] = ins
521
+ if bp.find('a:normAutofit', NS) is not None:
522
+ b['autofit'] = 'norm'
523
+ elif bp.find('a:spAutoFit', NS) is not None:
524
+ b['autofit'] = 'shape'
525
+ if b:
526
+ out['bodyPr'] = b
527
+ ls = tx.find('a:lstStyle', NS)
528
+ if ls is not None and len(ls):
529
+ lvls = {}
530
+ for lvl in ls:
531
+ p = read_lvl(lvl, ctx)
532
+ if p:
533
+ lvls[local(lvl.tag)] = p
534
+ if lvls:
535
+ out['lstStyle'] = lvls
536
+ paras = []
537
+ for p in tx.findall('a:p', NS):
538
+ paragraph_pr = p.find('a:pPr', NS)
539
+ info = {}
540
+ if paragraph_pr is not None:
541
+ for k in ('algn', 'lvl', 'rtl'):
542
+ if paragraph_pr.get(k):
543
+ info[k] = paragraph_pr.get(k)
544
+ for k in ('marL', 'marR', 'indent'):
545
+ if paragraph_pr.get(k) is not None:
546
+ info[k + '_px'] = ctx.units.px(paragraph_pr.get(k))
547
+ v = _lnspc(paragraph_pr, ctx)
548
+ if v:
549
+ info['lnSpc'] = v
550
+ for tag in ('spcBef', 'spcAft'):
551
+ v = _spc_before_after(paragraph_pr, ctx, tag)
552
+ if v:
553
+ info[tag] = v
554
+ if paragraph_pr.find('a:buNone', NS) is not None:
555
+ info['bullet'] = 'none'
556
+ bc = paragraph_pr.find('a:buChar', NS)
557
+ if bc is not None:
558
+ info['bullet'] = bc.get('char')
559
+ ba = paragraph_pr.find('a:buAutoNum', NS)
560
+ if ba is not None:
561
+ info['bullet'] = 'auto:%s' % ba.get('type', '')
562
+ # Paragraph-level run defaults. Mac Office / Keynote exports put the
563
+ # size here rather than on a:rPr, so skipping it loses the majority
564
+ # of the declared type scale on those decks.
565
+ dr = paragraph_pr.find('a:defRPr', NS)
566
+ if dr is not None:
567
+ facts = read_rpr(dr, ctx)
568
+ if facts:
569
+ info['defRPr'] = facts
570
+ runs = []
571
+ for r in list(p.findall('a:r', NS)) + list(p.findall('a:fld', NS)):
572
+ t = r.find('a:t', NS)
573
+ rec = read_rpr(r.find('a:rPr', NS), ctx)
574
+ rec['text'] = (t.text or '') if t is not None else ''
575
+ if local(r.tag) == 'fld':
576
+ rec['field'] = r.get('type')
577
+ runs.append(rec)
578
+ if not runs:
579
+ ep = p.find('a:endParaRPr', NS)
580
+ if ep is not None:
581
+ rec = read_rpr(ep, ctx)
582
+ if rec:
583
+ rec['text'] = ''
584
+ rec['empty_para'] = True
585
+ runs.append(rec)
586
+ info['runs'] = runs
587
+ paras.append(info)
588
+ out['paragraphs'] = paras
589
+ return out
590
+
591
+
592
+ def read_lvl(lvl, ctx):
593
+ """lvlNpPr / titleStyle level -> declared paragraph+run defaults (direct read,
594
+ no inheritance resolution)."""
595
+ d = {}
596
+ for k in ('algn',):
597
+ if lvl.get(k):
598
+ d[k] = lvl.get(k)
599
+ for k in ('marL', 'indent', 'defTabSz'):
600
+ if lvl.get(k) is not None:
601
+ d[k + '_px'] = ctx.units.px(lvl.get(k))
602
+ v = _lnspc(lvl, ctx)
603
+ if v:
604
+ d['lnSpc'] = v
605
+ for tag in ('spcBef', 'spcAft'):
606
+ v = _spc_before_after(lvl, ctx, tag)
607
+ if v:
608
+ d[tag] = v
609
+ dr = lvl.find('a:defRPr', NS)
610
+ if dr is not None:
611
+ d.update(read_rpr(dr, ctx))
612
+ bc = lvl.find('a:buChar', NS)
613
+ if bc is not None:
614
+ d['bullet'] = bc.get('char')
615
+ if lvl.find('a:buNone', NS) is not None:
616
+ d['bullet'] = 'none'
617
+ return d
618
+
619
+
620
+ # --------------------------------------------------------------------- shapes
621
+ def group_transform(group_shape):
622
+ """(sx, sy, dx, dy) in EMU mapping a group's child coords into parent coords."""
623
+ x = group_shape.find('p:grpSpPr/a:xfrm', NS)
624
+ if x is None:
625
+ return 1.0, 1.0, 0.0, 0.0
626
+ off, ext = x.find('a:off', NS), x.find('a:ext', NS)
627
+ child_off, child_ext = x.find('a:chOff', NS), x.find('a:chExt', NS)
628
+ if off is None or ext is None or child_off is None or child_ext is None:
629
+ return 1.0, 1.0, 0.0, 0.0
630
+ ox, oy = int(off.get('x')), int(off.get('y'))
631
+ cx, cy = int(ext.get('cx')), int(ext.get('cy'))
632
+ kx, ky = int(child_off.get('x')), int(child_off.get('y'))
633
+ ex, ey = int(child_ext.get('cx')), int(child_ext.get('cy'))
634
+ sx = cx / float(ex) if ex else 1.0
635
+ sy = cy / float(ey) if ey else 1.0
636
+ return sx, sy, ox - kx * sx, oy - ky * sy
637
+
638
+
639
+ XFRM_PATHS = {
640
+ 'sp': 'p:spPr/a:xfrm', 'pic': 'p:spPr/a:xfrm', 'cxnSp': 'p:spPr/a:xfrm',
641
+ 'grpSp': 'p:grpSpPr/a:xfrm', 'graphicFrame': 'p:xfrm',
642
+ }
643
+
644
+
645
+ def read_xfrm(el, tag):
646
+ x = el.find(XFRM_PATHS.get(tag, 'p:spPr/a:xfrm'), NS)
647
+ if x is None:
648
+ return None
649
+ off, ext = x.find('a:off', NS), x.find('a:ext', NS)
650
+ if off is None or ext is None:
651
+ return None
652
+ return {
653
+ 'x': int(off.get('x')), 'y': int(off.get('y')),
654
+ 'cx': int(ext.get('cx')), 'cy': int(ext.get('cy')),
655
+ 'rot': int(x.get('rot', 0)) / 60000.0,
656
+ 'flipH': x.get('flipH') == '1', 'flipV': x.get('flipV') == '1',
657
+ }
658
+
659
+
660
+ def rotated_bbox(x, y, w, h, rot_deg):
661
+ """Axis-aligned bounding box of a box rotated about its centre."""
662
+ import math
663
+ if not rot_deg:
664
+ return x, y, w, h
665
+ a = math.radians(rot_deg)
666
+ c, s = abs(math.cos(a)), abs(math.sin(a))
667
+ nw, nh = w * c + h * s, w * s + h * c
668
+ return x + (w - nw) / 2.0, y + (h - nh) / 2.0, nw, nh
669
+
670
+
671
+ BLEED_TOL = 0.05
672
+
673
+
674
+ def classify_box(x, y, w, h, canvas_w, canvas_h):
675
+ """完全出界 -> drop / 出血 <=5% -> bleed / >5% -> clamp + gap (方案 v0.2 §3 难点 9).
676
+
677
+ Emptiness is an actual rectangle intersection, not a `w <= 0` test: rules and
678
+ connectors are legitimately zero-extent on one axis (a horizontal divider has
679
+ h = 0) and must stay in as design evidence.
680
+ """
681
+ if w < 0 or h < 0:
682
+ return 'outside', None, None
683
+ if (max(x, 0.0) > min(x + w, float(canvas_w))
684
+ or max(y, 0.0) > min(y + h, float(canvas_h))):
685
+ return 'outside', None, None
686
+ over = {
687
+ 'left': max(0.0, -x) / canvas_w,
688
+ 'right': max(0.0, x + w - canvas_w) / canvas_w,
689
+ 'top': max(0.0, -y) / canvas_h,
690
+ 'bottom': max(0.0, y + h - canvas_h) / canvas_h,
691
+ }
692
+ worst = max(over.values())
693
+ if worst <= 0:
694
+ return 'inside', None, None
695
+ detail = {k: round(v * 100, 2) for k, v in over.items() if v > 0}
696
+ if worst <= BLEED_TOL:
697
+ return 'bleed', detail, None
698
+ cx0, cy0 = max(0.0, x), max(0.0, y)
699
+ cx1, cy1 = min(float(canvas_w), x + w), min(float(canvas_h), y + h)
700
+ return 'clamped', detail, (round(cx0, 1), round(cy0, 1),
701
+ round(cx1 - cx0, 1), round(cy1 - cy0, 1))