@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.7

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 (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
  44. package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
  45. package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
  46. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
  47. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
  48. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
  49. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
  50. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
  51. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
  52. package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
  53. package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
  54. package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11282 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env python3
2
+ """Shared deterministic ink-analysis helpers for `editppt page snap` and `editppt page diff`.
3
+
4
+ All functions operate on grayscale numpy arrays (float or uint8, 0..255).
5
+ "Ink" means the minority pixel class inside a local crop after Otsu
6
+ thresholding — dark text on a light background or light text on a dark
7
+ background are handled symmetrically.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import numpy as np
13
+ from PIL import Image
14
+
15
+
16
+ # Minimum gray-level separation between the ink and background classes for a
17
+ # crop to be considered measurable. Below this the crop is likely a photo or
18
+ # gradient region where binarization is meaningless.
19
+ MIN_CLASS_SEPARATION = 25.0
20
+ # Ink must be a minority class: more than this fraction means the threshold
21
+ # split a texture, not text.
22
+ MAX_INK_FRACTION = 0.45
23
+ MIN_INK_PIXELS = 8
24
+
25
+
26
+ def load_gray(path) -> np.ndarray:
27
+ return np.asarray(Image.open(path).convert("L"), dtype=np.float32)
28
+
29
+
30
+ def load_rgb(path) -> np.ndarray:
31
+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32)
32
+
33
+
34
+ def otsu_threshold(gray: np.ndarray) -> tuple[float, float]:
35
+ """Return (threshold, class_separation) for a grayscale crop."""
36
+ hist, _ = np.histogram(gray, bins=256, range=(0.0, 256.0))
37
+ total = float(gray.size)
38
+ if total == 0:
39
+ return 127.5, 0.0
40
+ levels = np.arange(256, dtype=np.float64)
41
+ weight_bg = np.cumsum(hist).astype(np.float64)
42
+ weight_fg = total - weight_bg
43
+ sum_bg = np.cumsum(levels * hist)
44
+ sum_all = sum_bg[-1]
45
+ mean_bg = sum_bg / np.maximum(weight_bg, 1.0)
46
+ mean_fg = (sum_all - sum_bg) / np.maximum(weight_fg, 1.0)
47
+ between = weight_bg * weight_fg * (mean_bg - mean_fg) ** 2
48
+ index = int(np.argmax(between))
49
+ separation = abs(float(mean_fg[index]) - float(mean_bg[index]))
50
+ if weight_bg[index] == 0 or weight_fg[index] == 0:
51
+ separation = 0.0
52
+ return float(index), separation
53
+
54
+
55
+ def crop_ink_mask(gray_crop: np.ndarray) -> dict:
56
+ """Binarize a crop and return the ink mask plus reliability metadata.
57
+
58
+ Returns dict with keys: mask (bool ndarray), polarity ("dark"|"light"),
59
+ reliable (bool), separation (float), ink_fraction (float).
60
+ """
61
+ threshold, separation = otsu_threshold(gray_crop)
62
+ dark = gray_crop <= threshold
63
+ dark_fraction = float(dark.mean()) if dark.size else 0.0
64
+ if dark_fraction <= 0.5:
65
+ mask, polarity, fraction = dark, "dark", dark_fraction
66
+ else:
67
+ mask, polarity, fraction = ~dark, "light", 1.0 - dark_fraction
68
+ reliable = (
69
+ separation >= MIN_CLASS_SEPARATION
70
+ and fraction <= MAX_INK_FRACTION
71
+ and int(mask.sum()) >= MIN_INK_PIXELS
72
+ )
73
+ return {
74
+ "mask": mask,
75
+ "polarity": polarity,
76
+ "reliable": reliable,
77
+ "separation": separation,
78
+ "ink_fraction": fraction,
79
+ }
80
+
81
+
82
+ def _dilate(mask: np.ndarray) -> np.ndarray:
83
+ out = mask.copy()
84
+ out[1:, :] |= mask[:-1, :]
85
+ out[:-1, :] |= mask[1:, :]
86
+ out[:, 1:] |= mask[:, :-1]
87
+ out[:, :-1] |= mask[:, 1:]
88
+ return out
89
+
90
+
91
+ def despeckle(mask: np.ndarray) -> np.ndarray:
92
+ """Drop ink pixels that have no 8-connected ink neighbor (binarization noise)."""
93
+ if not mask.any():
94
+ return mask
95
+ padded = np.pad(mask, 1, mode="constant")
96
+ neighbors = np.zeros_like(padded, dtype=np.uint8)
97
+ for dy in (-1, 0, 1):
98
+ for dx in (-1, 0, 1):
99
+ if dy == 0 and dx == 0:
100
+ continue
101
+ neighbors += np.roll(np.roll(padded, dy, axis=0), dx, axis=1).astype(np.uint8)
102
+ return mask & (neighbors[1:-1, 1:-1] > 0)
103
+
104
+
105
+ def remove_border_components(mask: np.ndarray) -> np.ndarray:
106
+ """Remove ink components that touch the crop boundary.
107
+
108
+ Structures crossing the crop edge (card borders, dividers, neighboring
109
+ text) belong to objects outside the rough box and must not pollute the
110
+ measured text bounds.
111
+ """
112
+ if not mask.any():
113
+ return mask
114
+ reach = np.zeros_like(mask)
115
+ reach[0, :] = mask[0, :]
116
+ reach[-1, :] = mask[-1, :]
117
+ reach[:, 0] = mask[:, 0]
118
+ reach[:, -1] = mask[:, -1]
119
+ if not reach.any():
120
+ return mask
121
+ for _ in range(2 * max(mask.shape)):
122
+ grown = _dilate(reach) & mask
123
+ if np.array_equal(grown, reach):
124
+ break
125
+ reach = grown
126
+ return mask & ~reach
127
+
128
+
129
+ def tight_bbox(mask: np.ndarray):
130
+ """Return (x, y, w, h) of the ink bounding box, or None when empty."""
131
+ if not mask.any():
132
+ return None
133
+ rows = np.flatnonzero(mask.any(axis=1))
134
+ cols = np.flatnonzero(mask.any(axis=0))
135
+ top, bottom = int(rows[0]), int(rows[-1])
136
+ left, right = int(cols[0]), int(cols[-1])
137
+ return (left, top, right - left + 1, bottom - top + 1)
138
+
139
+
140
+ def line_bands(mask: np.ndarray, min_ink_px: int = 2, merge_gap: int = 2) -> list[tuple[int, int]]:
141
+ """Segment ink rows into text-line bands [(top, bottom_exclusive), ...].
142
+
143
+ Bands separated by gaps of at most merge_gap rows are merged so
144
+ antialiasing breaks do not split a line.
145
+ """
146
+ row_ink = mask.sum(axis=1)
147
+ inky = row_ink >= min_ink_px
148
+ bands: list[list[int]] = []
149
+ start = None
150
+ for y, on in enumerate(inky):
151
+ if on and start is None:
152
+ start = y
153
+ elif not on and start is not None:
154
+ bands.append([start, y])
155
+ start = None
156
+ if start is not None:
157
+ bands.append([start, len(inky)])
158
+ merged: list[list[int]] = []
159
+ for band in bands:
160
+ if merged and band[0] - merged[-1][1] <= merge_gap:
161
+ merged[-1][1] = band[1]
162
+ else:
163
+ merged.append(band)
164
+ return [(top, bottom) for top, bottom in merged if bottom - top >= 2]
165
+
166
+
167
+ def glyph_height_px(bands: list[tuple[int, int]]) -> float:
168
+ if not bands:
169
+ return 0.0
170
+ return float(np.median([bottom - top for top, bottom in bands]))
171
+
172
+
173
+ # A band this thin next to a much taller band is a horizontal rule, divider,
174
+ # or underline — not a glyph row. Container borders running through a crop
175
+ # without touching its edges are the most common real-slide pollution.
176
+ RULE_BAND_MAX_PX = 4
177
+ RULE_BAND_RATIO = 0.35
178
+
179
+
180
+ def filter_rule_bands(bands: list[tuple[int, int]]) -> list[tuple[int, int]]:
181
+ """Drop line-like bands so dividers do not skew the glyph median or bbox.
182
+
183
+ Only fires when a clearly taller band exists; a crop whose text is itself
184
+ tiny (all bands thin) is left untouched.
185
+ """
186
+ if len(bands) <= 1:
187
+ return bands
188
+ heights = [bottom - top for top, bottom in bands]
189
+ tallest = max(heights)
190
+ if tallest <= RULE_BAND_MAX_PX:
191
+ return bands
192
+ kept = [
193
+ (top, bottom)
194
+ for (top, bottom), height in zip(bands, heights)
195
+ if not (height <= RULE_BAND_MAX_PX and height < RULE_BAND_RATIO * tallest)
196
+ ]
197
+ return kept or bands
198
+
199
+
200
+ def ink_centroid(mask: np.ndarray):
201
+ """Return (cx, cy) of ink pixels, or None when empty."""
202
+ ys, xs = np.nonzero(mask)
203
+ if len(xs) == 0:
204
+ return None
205
+ return float(xs.mean()), float(ys.mean())
206
+
207
+
208
+ _CJK_RANGES = (
209
+ (0x3000, 0x30FF), # CJK punctuation, kana
210
+ (0x4E00, 0x9FFF), # CJK unified ideographs
211
+ (0xFF00, 0xFFEF), # full-width forms
212
+ )
213
+ _DESCENDER_CHARS = set("gjpqy")
214
+ _ASCENDER_CHARS = set("bdfhklt")
215
+
216
+
217
+ def contains_cjk(text: str) -> bool:
218
+ return any(any(low <= ord(ch) <= high for low, high in _CJK_RANGES) for ch in text)
219
+
220
+
221
+ def glyph_em_ratio(text: str) -> float:
222
+ """Estimated ratio of measured ink-band height to the font em size.
223
+
224
+ These are calibration constants: CJK glyphs nearly fill the em box, Latin
225
+ cap height is ~0.72 em, descenders extend the band to ~0.92 em, and
226
+ lowercase-only words without ascenders sit near the x-height (~0.50 em).
227
+ The deterministic builder's fit_text clamp and `page diff` absorb the
228
+ residual error.
229
+ """
230
+ if not text:
231
+ return 0.72
232
+ if contains_cjk(text):
233
+ return 0.95
234
+ has_descender = any(ch in _DESCENDER_CHARS for ch in text)
235
+ has_ascender = any(ch.isupper() or ch.isdigit() or ch in _ASCENDER_CHARS for ch in text)
236
+ if has_descender and has_ascender:
237
+ return 0.95
238
+ if has_descender:
239
+ return 0.78
240
+ if has_ascender:
241
+ return 0.72
242
+ return 0.50
243
+
244
+
245
+ def segment_mask(mask: np.ndarray):
246
+ """Bands → row restriction → bbox → glyph metrics for a cleaned ink mask.
247
+
248
+ Returns None when no glyph bands remain.
249
+ """
250
+ if not mask.any():
251
+ return None
252
+ bands = filter_rule_bands(line_bands(mask))
253
+ if not bands:
254
+ return None
255
+ row_selector = np.zeros(mask.shape[0], dtype=bool)
256
+ for top, bottom in bands:
257
+ row_selector[top:bottom] = True
258
+ restricted = mask & row_selector[:, None]
259
+ bbox = tight_bbox(restricted)
260
+ if bbox is None:
261
+ return None
262
+ return {
263
+ "mask": restricted,
264
+ "bbox": bbox,
265
+ "bands": bands,
266
+ "glyph_height_px": glyph_height_px(bands),
267
+ "line_count": len(bands),
268
+ }
269
+
270
+
271
+ def keep_anchored_columns(mask: np.ndarray, anchor_left: int, anchor_right: int, glyph: float) -> np.ndarray:
272
+ """Keep only column clusters that horizontally overlap the anchor range.
273
+
274
+ Ink columns are clustered with a gap threshold of ~0.8 glyph heights:
275
+ characters and word spaces within one text block sit closer than that,
276
+ while neighboring elements (icons, page numbers, other blocks) are
277
+ separated by wider gaps. The anchor is the worker's rough box — its
278
+ placement is the semantic signal for which cluster is the target text.
279
+ Clusters that never reach the anchor range are foreign objects pulled in
280
+ by the crop margin or auto-expansion, and are dropped.
281
+ """
282
+ column_ink = mask.any(axis=0)
283
+ columns = np.flatnonzero(column_ink)
284
+ if columns.size == 0:
285
+ return mask
286
+ gap_limit = max(6, int(0.8 * glyph))
287
+ clusters: list[tuple[int, int]] = []
288
+ start = previous = int(columns[0])
289
+ for column in columns[1:]:
290
+ column = int(column)
291
+ if column - previous > gap_limit:
292
+ clusters.append((start, previous))
293
+ start = column
294
+ previous = column
295
+ clusters.append((start, previous))
296
+ kept = [cluster for cluster in clusters if cluster[1] >= anchor_left and cluster[0] <= anchor_right]
297
+ if not kept:
298
+ center = (anchor_left + anchor_right) / 2
299
+ kept = [min(clusters, key=lambda cluster: abs((cluster[0] + cluster[1]) / 2 - center))]
300
+ selector = np.zeros(mask.shape[1], dtype=bool)
301
+ for start, end in kept:
302
+ selector[start : end + 1] = True
303
+ return mask & selector[None, :]
304
+
305
+
306
+ def measure_crop(gray_crop: np.ndarray, clean_border: bool = True) -> dict:
307
+ """Full measurement for one crop: mask, bbox, bands, glyph height.
308
+
309
+ Returns dict with keys: ok (bool), reason (str), mask, polarity,
310
+ bbox (x, y, w, h in crop coordinates), bands, glyph_height_px,
311
+ line_count, ink_fraction.
312
+ """
313
+ ink = crop_ink_mask(gray_crop)
314
+ if not ink["reliable"]:
315
+ return {"ok": False, "reason": "low-contrast", **ink, "bbox": None, "bands": [], "glyph_height_px": 0.0, "line_count": 0}
316
+ mask = despeckle(ink["mask"])
317
+ if clean_border:
318
+ cleaned = remove_border_components(mask)
319
+ # If border cleanup wiped almost everything, the text itself likely
320
+ # touches the crop edge (rough box too tight); fall back to the
321
+ # uncleaned mask rather than reporting an empty measurement.
322
+ if int(cleaned.sum()) >= max(MIN_INK_PIXELS, int(0.1 * mask.sum())):
323
+ mask = cleaned
324
+ segmented = segment_mask(mask)
325
+ if segmented is None:
326
+ return {"ok": False, "reason": "no-ink", **ink, "mask": mask, "bbox": None, "bands": [], "glyph_height_px": 0.0, "line_count": 0}
327
+ return {
328
+ "ok": True,
329
+ "reason": "",
330
+ "polarity": ink["polarity"],
331
+ "separation": ink["separation"],
332
+ "ink_fraction": float(segmented["mask"].mean()),
333
+ **segmented,
334
+ }
@@ -0,0 +1,174 @@
1
+ """Native path geometry and matching raster-only curve sampling."""
2
+
3
+ import math
4
+
5
+
6
+ DASH_PATTERNS = {
7
+ "solid": (), "dot": (1, 3), "dash": (4, 3), "lgDash": (8, 3),
8
+ "dashDot": (4, 3, 1, 3), "lgDashDot": (8, 3, 1, 3),
9
+ "lgDashDotDot": (8, 3, 1, 3, 1, 3), "sysDash": (3, 1),
10
+ "sysDot": (1, 1), "sysDashDot": (3, 1, 1, 1),
11
+ "sysDashDotDot": (3, 1, 1, 1, 1, 1),
12
+ }
13
+ POINT_COUNTS = {"moveTo": 1, "lnTo": 1, "quadBezTo": 2, "cubicBezTo": 3, "close": 0}
14
+
15
+
16
+ def _finite(value):
17
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
18
+
19
+
20
+ def validate_shape(item):
21
+ """Reject unsupported styles and ambiguous or malformed native paths."""
22
+ dash = item.get("dash")
23
+ if dash is not None and (not isinstance(dash, str) or dash not in DASH_PATTERNS):
24
+ raise ValueError("dash must be a supported DrawingML preset")
25
+ for field in ("start_arrow", "end_arrow"):
26
+ if item.get(field) not in (None, "none", "triangle"):
27
+ raise ValueError(f"{field} must be none or triangle")
28
+ has_arrow = any(item.get(field) == "triangle" for field in ("start_arrow", "end_arrow"))
29
+ if has_arrow and (item.get("type") not in ("line", "path") or "polygon_px" in item or "polygon" in item):
30
+ raise ValueError("arrows are supported only on lines and open paths")
31
+ if item.get("type") != "path":
32
+ if "path_px" in item:
33
+ raise ValueError("path_px requires type path")
34
+ return
35
+ for field in ("polygon_px", "polygon", "points_px", "points", "preset", "flip_h", "flip_v"):
36
+ if field in item:
37
+ raise ValueError(f"path cannot also specify {field}")
38
+ box = item.get("box_px")
39
+ if not isinstance(box, (list, tuple)) or len(box) != 4 or not all(_finite(v) for v in box) or box[2] <= 0 or box[3] <= 0:
40
+ raise ValueError("path box_px must contain finite x, y and positive width, height")
41
+ commands = item.get("path_px")
42
+ if not isinstance(commands, list) or len(commands) < 2:
43
+ raise ValueError("path_px requires moveTo followed by at least one drawing segment")
44
+ drawn = False
45
+ for index, command in enumerate(commands):
46
+ if not isinstance(command, dict):
47
+ raise ValueError("each path_px command must be an object")
48
+ op = command.get("op")
49
+ if not isinstance(op, str) or op not in POINT_COUNTS:
50
+ raise ValueError("unsupported path_px operation")
51
+ if (index == 0) != (op == "moveTo"):
52
+ raise ValueError("path_px must have exactly one moveTo at the start")
53
+ if op == "close" and index != len(commands) - 1:
54
+ raise ValueError("close is allowed only at the end of path_px")
55
+ points = command.get("points")
56
+ if not isinstance(points, list) or len(points) != POINT_COUNTS[op]:
57
+ raise ValueError(f"{op} requires {POINT_COUNTS[op]} points")
58
+ if any(not isinstance(p, (list, tuple)) or len(p) != 2 or not all(_finite(v) for v in p) for p in points):
59
+ raise ValueError("path points must be finite [x, y] coordinates")
60
+ drawn |= op in ("lnTo", "quadBezTo", "cubicBezTo")
61
+ if not drawn:
62
+ raise ValueError("path_px requires at least one drawing segment")
63
+ closed = commands[-1]["op"] == "close"
64
+ if not closed and item.get("fill") not in (None, "none"):
65
+ raise ValueError("open paths require fill none")
66
+ if closed and has_arrow:
67
+ raise ValueError("closed paths cannot have endpoint arrows")
68
+
69
+
70
+ def custom_path_geometry_xml(item):
71
+ """Encode a whole curve as one editable DrawingML custom geometry."""
72
+ validate_shape(item)
73
+ left, top, width, height = item["box_px"]
74
+ segments = []
75
+ for command in item["path_px"]:
76
+ op = command["op"]
77
+ if op == "close":
78
+ segments.append("<a:close/>")
79
+ continue
80
+ points = "".join(
81
+ f'<a:pt x="{round((x - left) / width * 21600)}" y="{round((y - top) / height * 21600)}"/>'
82
+ for x, y in command["points"]
83
+ )
84
+ segments.append(f"<a:{op}>{points}</a:{op}>")
85
+ fill = "norm" if item["path_px"][-1]["op"] == "close" else "none"
86
+ return (
87
+ '<a:custGeom><a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>'
88
+ '<a:rect l="l" t="t" r="r" b="b"/>'
89
+ f'<a:pathLst><a:path w="21600" h="21600" fill="{fill}">'
90
+ + "".join(segments) + "</a:path></a:pathLst></a:custGeom>"
91
+ )
92
+
93
+
94
+ def _flatten_curve(controls, output, depth=0):
95
+ # Control-polygon excess also catches collinear curves that double back.
96
+ length = sum(math.dist(a, b) for a, b in zip(controls, controls[1:]))
97
+ start, end = controls[0], controls[-1]
98
+ chord = math.dist(start, end)
99
+ deviation = max((abs((end[0] - start[0]) * (p[1] - start[1]) - (end[1] - start[1]) * (p[0] - start[0])) / chord for p in controls[1:-1]), default=0) if chord else length
100
+ if depth >= 16 or (length - chord <= 0.25 and deviation <= 0.25):
101
+ output.append(end)
102
+ return
103
+ levels = [controls]
104
+ while len(levels[-1]) > 1:
105
+ levels.append([((a[0] + b[0]) / 2, (a[1] + b[1]) / 2) for a, b in zip(levels[-1], levels[-1][1:])])
106
+ _flatten_curve([level[0] for level in levels], output, depth + 1)
107
+ _flatten_curve([level[-1] for level in reversed(levels)], output, depth + 1)
108
+
109
+
110
+ def preview_path_points(item, scale):
111
+ """Map absolute source pixels through the normalized box and sample curves."""
112
+ validate_shape(item)
113
+ left, top, width, height = item["box_px"]
114
+
115
+ def map_point(point):
116
+ return (
117
+ (item.get("left", 0) + (point[0] - left) / width * item.get("width", 1)) * scale,
118
+ (item.get("top", 0) + (point[1] - top) / height * item.get("height", 1)) * scale,
119
+ )
120
+
121
+ output = []
122
+ for command in item["path_px"]:
123
+ op = command["op"]
124
+ points = [map_point(point) for point in command["points"]]
125
+ if op in ("moveTo", "lnTo"):
126
+ output.extend(points)
127
+ elif op == "close":
128
+ output.append(output[0])
129
+ else:
130
+ _flatten_curve([output[-1], *points], output)
131
+ return output
132
+
133
+
134
+ def draw_styled_path(draw, points, fill, width, dash=None, start_arrow=None, end_arrow=None):
135
+ """Draw dashes continuously along arc length and arrows along end tangents."""
136
+ if not fill or fill == "none" or len(points) < 2:
137
+ return
138
+ points = [tuple(point) for point in points]
139
+ width = max(1, round(width))
140
+ pattern = [value * width for value in DASH_PATTERNS[dash or "solid"]]
141
+ if not pattern:
142
+ draw.line(points, fill=fill, width=width)
143
+ else:
144
+ index, remaining = 0, pattern[0]
145
+ for start, end in zip(points, points[1:]):
146
+ length = math.dist(start, end)
147
+ if not length:
148
+ continue
149
+ offset = 0.0
150
+ while offset < length:
151
+ step = min(remaining, length - offset)
152
+ if index % 2 == 0:
153
+ segment = [tuple(a + (b - a) * distance / length for a, b in zip(start, end)) for distance in (offset, offset + step)]
154
+ draw.line(segment, fill=fill, width=width)
155
+ offset += step
156
+ remaining -= step
157
+ if remaining <= 1e-9:
158
+ index = (index + 1) % len(pattern)
159
+ remaining = pattern[index]
160
+
161
+ def arrow(tip, candidates):
162
+ neighbor = next((p for p in candidates if p != tip), None)
163
+ if neighbor is None:
164
+ return
165
+ distance = math.dist(tip, neighbor)
166
+ dx, dy = (tip[0] - neighbor[0]) / distance, (tip[1] - neighbor[1]) / distance
167
+ length, half_width = 3 * width, 1.5 * width
168
+ base = (tip[0] - length * dx, tip[1] - length * dy)
169
+ draw.polygon([tip, (base[0] - half_width * dy, base[1] + half_width * dx), (base[0] + half_width * dy, base[1] - half_width * dx)], fill=fill)
170
+
171
+ if start_arrow == "triangle":
172
+ arrow(points[0], points[1:])
173
+ if end_arrow == "triangle":
174
+ arrow(points[-1], reversed(points[:-1]))