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

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 +90 -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 +11423 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,1709 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic, zero-credit Pillow region cropper for oil-slide reference assets.
3
+
4
+ Crops photographic, portrait, product, or character regions directly out of
5
+ reference slides (e.g. `assets/reference/s4.png`) using `1920x1080`, `native`,
6
+ or `pct` coordinates, with optional geometric alpha masks (`rect`, `circle`,
7
+ `pill`, `rounded:R`), neutral background box removal (`none`, `auto`, `white`,
8
+ `black`), background blending (`blend`), and smooth edge alpha fades
9
+ (e.g. `bottom:30,left:15`).
10
+
11
+ CLI:
12
+ python3 scripts/crop_asset.py --src assets/reference/s4.png \
13
+ --bbox 1180,140,560,720 --coord-space 1920x1080 \
14
+ --mask pill --fade-edge bottom:28 --out assets/crops/portrait.png --json
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import math
21
+ import re
22
+ import sys
23
+ from collections import deque
24
+ from collections.abc import Callable, Iterator
25
+ from pathlib import Path
26
+ from statistics import median
27
+ from typing import Any
28
+
29
+ from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageOps
30
+
31
+ CANVAS_W = 1920.0
32
+ CANVAS_H = 1080.0
33
+
34
+ _RATIO_TO_CANVAS: dict[str, tuple[float, float]] = {
35
+ "16:9": (1920.0, 1080.0),
36
+ "3:4": (1080.0, 1440.0),
37
+ "9:16": (1080.0, 1920.0),
38
+ "1:1": (1440.0, 1440.0),
39
+ "1920x1080": (1920.0, 1080.0),
40
+ "1080x1440": (1080.0, 1440.0),
41
+ "1080x1920": (1080.0, 1920.0),
42
+ "1440x1440": (1440.0, 1440.0),
43
+ }
44
+ _COORD_SPACE_CHOICES = [
45
+ "1920x1080",
46
+ "1080x1440",
47
+ "1080x1920",
48
+ "1440x1440",
49
+ "16:9",
50
+ "3:4",
51
+ "9:16",
52
+ "1:1",
53
+ "canvas",
54
+ "stage",
55
+ "native",
56
+ "pct",
57
+ ]
58
+
59
+
60
+ def infer_canvas_for_image(
61
+ src_w: int,
62
+ src_h: int,
63
+ *,
64
+ ratio: str | None = None,
65
+ ) -> tuple[float, float]:
66
+ """Resolve canvas dimensions (w, h) from an explicit ratio or image aspect ratio."""
67
+ if ratio:
68
+ tok = str(ratio).strip().lower().replace("×", "x").replace("/", ":")
69
+ if tok in _RATIO_TO_CANVAS:
70
+ return _RATIO_TO_CANVAS[tok]
71
+ m = re.fullmatch(r"(\d+)\s*x\s*(\d+)", tok)
72
+ if m and int(m.group(1)) > 0 and int(m.group(2)) > 0:
73
+ return float(m.group(1)), float(m.group(2))
74
+ raise ValueError(f"Unsupported ratio: {ratio!r}")
75
+ if (CANVAS_W, CANVAS_H) != (1920.0, 1080.0):
76
+ return float(CANVAS_W), float(CANVAS_H)
77
+ if src_w >= 256 and src_h >= 256:
78
+ aspect = float(src_w) / float(src_h)
79
+ if aspect < 0.65:
80
+ return (1080.0, 1920.0)
81
+ if aspect < 0.88:
82
+ return (1080.0, 1440.0)
83
+ if aspect <= 1.15:
84
+ return (1440.0, 1440.0)
85
+ return float(CANVAS_W), float(CANVAS_H)
86
+
87
+
88
+ def parse_bbox(raw: str | list[float] | tuple[float, ...]) -> tuple[float, float, float, float]:
89
+ if isinstance(raw, (list, tuple)):
90
+ if len(raw) != 4:
91
+ raise ValueError(f"bbox must have exactly 4 numbers (x,y,w,h), got {len(raw)}")
92
+ vals = [float(v) for v in raw]
93
+ else:
94
+ text = str(raw).strip()
95
+ parsed_seq: Any = None
96
+ if text.startswith("[") and text.endswith("]"):
97
+ try:
98
+ parsed_seq = json.loads(text)
99
+ except Exception:
100
+ parsed_seq = None
101
+ if isinstance(parsed_seq, list) and len(parsed_seq) == 4:
102
+ vals = [float(v) for v in parsed_seq]
103
+ else:
104
+ cleaned = text.strip("[]() ")
105
+ parts = [p.strip() for p in re.split(r"[,\s]+", cleaned) if p.strip()]
106
+ if len(parts) != 4:
107
+ raise ValueError(f"bbox must be 'x,y,w,h' or [x,y,w,h] (4 numbers), got {raw!r}")
108
+ vals = [float(p) for p in parts]
109
+ x, y, w, h = vals
110
+ if w <= 0 or h <= 0:
111
+ raise ValueError(f"bbox width and height must be positive, got w={w}, h={h}")
112
+ return x, y, w, h
113
+
114
+
115
+ def _resolve_crop_box(
116
+ src_w: int,
117
+ src_h: int,
118
+ bbox: tuple[float, float, float, float],
119
+ coord_space: str,
120
+ *,
121
+ ratio: str | None = None,
122
+ ) -> tuple[tuple[int, int, int, int], float]:
123
+ """Map bbox from coord_space into clamped native (x0, y0, x1, y1) pixels and return (box, radius_scale)."""
124
+ x, y, w, h = bbox
125
+ cs = (coord_space or "1920x1080").strip().lower().replace("×", "x").replace("/", ":")
126
+ if cs == "native":
127
+ x0 = round(x)
128
+ y0 = round(y)
129
+ x1 = round(x + w)
130
+ y1 = round(y + h)
131
+ r_scale = 1.0
132
+ elif cs == "pct":
133
+ x0 = round((x / 100.0) * src_w)
134
+ y0 = round((y / 100.0) * src_h)
135
+ x1 = round(((x + w) / 100.0) * src_w)
136
+ y1 = round(((y + h) / 100.0) * src_h)
137
+ r_scale = min(src_w, src_h) / 100.0
138
+ else:
139
+ if ratio:
140
+ cw, ch = infer_canvas_for_image(src_w, src_h, ratio=ratio)
141
+ elif cs in ("canvas", "stage"):
142
+ cw, ch = infer_canvas_for_image(src_w, src_h)
143
+ elif cs == "1920x1080" and (CANVAS_W, CANVAS_H) != (1920.0, 1080.0):
144
+ cw, ch = float(CANVAS_W), float(CANVAS_H)
145
+ elif cs in _RATIO_TO_CANVAS:
146
+ cw, ch = _RATIO_TO_CANVAS[cs]
147
+ else:
148
+ m = re.fullmatch(r"(\d+)\s*x\s*(\d+)", cs)
149
+ if m and int(m.group(1)) > 0 and int(m.group(2)) > 0:
150
+ cw, ch = float(m.group(1)), float(m.group(2))
151
+ else:
152
+ raise ValueError(
153
+ f"Unsupported coord_space: {coord_space!r} (expected '1920x1080', '1080x1440', '1080x1920', '1440x1440', 'canvas', 'native', or 'pct')"
154
+ )
155
+ sx = src_w / cw
156
+ sy = src_h / ch
157
+ x0 = round(x * sx)
158
+ y0 = round(y * sy)
159
+ x1 = round((x + w) * sx)
160
+ y1 = round((y + h) * sy)
161
+ r_scale = (sx + sy) * 0.5
162
+
163
+ x0 = max(0, min(src_w - 1, x0))
164
+ y0 = max(0, min(src_h - 1, y0))
165
+ x1 = max(x0 + 1, min(src_w, x1))
166
+ y1 = max(y0 + 1, min(src_h, y1))
167
+ return (x0, y0, x1, y1), r_scale
168
+
169
+
170
+ def _remove_outer_bg(rgba: Image.Image, mode: str) -> Image.Image:
171
+ """Border flood-fill removal of uniform neutral box background with anti-aliased edge feathering."""
172
+ m = (mode or "none").strip().lower()
173
+ if m == "none":
174
+ return rgba
175
+ if m not in ("auto", "white", "black"):
176
+ raise ValueError(f"Unsupported remove_bg mode: {mode!r} (expected none|auto|white|black)")
177
+
178
+ w, h = rgba.size
179
+ if w < 4 or h < 4:
180
+ return rgba
181
+
182
+ px = rgba.load()
183
+ border_pixels: list[tuple[int, int, int, int]] = []
184
+ step_x = max(1, w // 48)
185
+ step_y = max(1, h // 48)
186
+ for x in range(0, w, step_x):
187
+ border_pixels.append(px[x, 0])
188
+ border_pixels.append(px[x, h - 1])
189
+ for y in range(0, h, step_y):
190
+ border_pixels.append(px[0, y])
191
+ border_pixels.append(px[w - 1, y])
192
+
193
+ opaque_border = [p for p in border_pixels if p[3] >= 220]
194
+ if not opaque_border:
195
+ return rgba
196
+
197
+ if m == "white":
198
+ candidates = [
199
+ p for p in opaque_border
200
+ if (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) >= 205
201
+ and (max(p[:3]) - min(p[:3])) <= 32
202
+ ]
203
+ if candidates:
204
+ rs = sorted(p[0] for p in candidates)
205
+ gs = sorted(p[1] for p in candidates)
206
+ bs = sorted(p[2] for p in candidates)
207
+ mid = len(candidates) // 2
208
+ bg_r, bg_g, bg_b = rs[mid], gs[mid], bs[mid]
209
+ else:
210
+ bg_r, bg_g, bg_b = 255, 255, 255
211
+ tol = 32
212
+ elif m == "black":
213
+ candidates = [
214
+ p for p in opaque_border
215
+ if (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) <= 48
216
+ and (max(p[:3]) - min(p[:3])) <= 32
217
+ ]
218
+ if candidates:
219
+ rs = sorted(p[0] for p in candidates)
220
+ gs = sorted(p[1] for p in candidates)
221
+ bs = sorted(p[2] for p in candidates)
222
+ mid = len(candidates) // 2
223
+ bg_r, bg_g, bg_b = rs[mid], gs[mid], bs[mid]
224
+ else:
225
+ bg_r, bg_g, bg_b = 0, 0, 0
226
+ tol = 32
227
+ else: # auto
228
+ if len(opaque_border) < len(border_pixels) * 0.80:
229
+ return rgba
230
+ rs = sorted(p[0] for p in opaque_border)
231
+ gs = sorted(p[1] for p in opaque_border)
232
+ bs = sorted(p[2] for p in opaque_border)
233
+ mid = len(opaque_border) // 2
234
+ bg_r, bg_g, bg_b = rs[mid], gs[mid], bs[mid]
235
+ bg_lum = 0.2126 * bg_r + 0.7152 * bg_g + 0.0722 * bg_b
236
+ bg_chroma = max(bg_r, bg_g, bg_b) - min(bg_r, bg_g, bg_b)
237
+ if bg_chroma > 24 or not (bg_lum <= 45 or bg_lum >= 215):
238
+ return rgba
239
+ uniform_count = sum(
240
+ 1 for r, g, b, _ in opaque_border
241
+ if abs(r - bg_r) <= 24 and abs(g - bg_g) <= 24 and abs(b - bg_b) <= 24
242
+ )
243
+ if uniform_count < len(opaque_border) * 0.80:
244
+ return rgba
245
+ tol = 28
246
+
247
+ out = rgba.copy()
248
+ opx = out.load()
249
+ visited = [[False] * w for _ in range(h)]
250
+ bg_mask = [[False] * w for _ in range(h)]
251
+ q: deque[tuple[int, int]] = deque()
252
+ for x in range(w):
253
+ q.append((x, 0))
254
+ q.append((x, h - 1))
255
+ for y in range(h):
256
+ q.append((0, y))
257
+ q.append((w - 1, y))
258
+
259
+ while q:
260
+ x, y = q.popleft()
261
+ if visited[y][x]:
262
+ continue
263
+ visited[y][x] = True
264
+ r, g, b, a = opx[x, y]
265
+ if a < 20 or (abs(r - bg_r) <= tol and abs(g - bg_g) <= tol and abs(b - bg_b) <= tol):
266
+ bg_mask[y][x] = True
267
+ opx[x, y] = (0, 0, 0, 0)
268
+ for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
269
+ if 0 <= nx < w and 0 <= ny < h and not visited[ny][nx]:
270
+ q.append((nx, ny))
271
+
272
+ # Anti-alias 2-pixel boundary feathering along stripped edges
273
+ feather_max = tol + 32
274
+ ring1: list[tuple[int, int]] = []
275
+ for y in range(h):
276
+ for x in range(w):
277
+ if bg_mask[y][x]:
278
+ continue
279
+ r, g, b, a = opx[x, y]
280
+ if a == 0:
281
+ continue
282
+ adj = (
283
+ (y > 0 and bg_mask[y - 1][x])
284
+ or (y + 1 < h and bg_mask[y + 1][x])
285
+ or (x > 0 and bg_mask[y][x - 1])
286
+ or (x + 1 < w and bg_mask[y][x + 1])
287
+ )
288
+ if adj:
289
+ ring1.append((x, y))
290
+ dist = max(abs(r - bg_r), abs(g - bg_g), abs(b - bg_b))
291
+ if dist < feather_max:
292
+ factor = max(0.0, min(1.0, (dist - tol * 0.5) / max(1.0, feather_max - tol * 0.5)))
293
+ opx[x, y] = (r, g, b, int(round(a * factor)))
294
+
295
+ if ring1:
296
+ ring1_set = set(ring1)
297
+ for x, y in ring1:
298
+ for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
299
+ if 0 <= nx < w and 0 <= ny < h and not bg_mask[ny][nx] and (nx, ny) not in ring1_set:
300
+ r, g, b, a = opx[nx, ny]
301
+ dist = max(abs(r - bg_r), abs(g - bg_g), abs(b - bg_b))
302
+ if dist < tol + 18:
303
+ factor = max(0.35, min(1.0, dist / max(1.0, tol + 18)))
304
+ opx[nx, ny] = (r, g, b, int(round(a * factor)))
305
+
306
+ return out
307
+
308
+
309
+ _SIDES = ("left", "top", "right", "bottom")
310
+ _BLEND_NOISE = 4
311
+ _BLEND_FADE = 3
312
+ _Box = tuple[int, int, int, int]
313
+ _Color = tuple[int, int, int]
314
+ _Background = Callable[[int, int], _Color]
315
+
316
+
317
+ def _blend_background(rgb: Image.Image, box: _Box, limits: list[int]) -> _Background:
318
+ """Estimate a mild RGB plane from robust samples around the requested region."""
319
+ left, top, right, bottom = box
320
+ width, height = right - left, bottom - top
321
+ pixels = rgb.load()
322
+ samples = []
323
+ slopes = ([], [])
324
+ for side, edge in enumerate(box):
325
+ axis = side % 2
326
+ direction = -1 if side < 2 else 1
327
+ boundary = edge if direction < 0 else edge - 1
328
+ room = edge if direction < 0 else rgb.size[axis] - edge
329
+ # Sample beyond the allowed growth where possible, so a tight crop's
330
+ # own shadow does not set the paper color. Sample inward at image edges.
331
+ sample_at = limits[side] + min(48, limits[side] // 2)
332
+ distances = range(min(sample_at + 1, room), min(sample_at + 8, room) + 1)
333
+ if not room:
334
+ distances = range(0, -min(5, (width, height)[axis]), -1)
335
+ cross_start = (top, left)[axis]
336
+ cross_size = (height, width)[axis]
337
+ strip = []
338
+ for part in range(5):
339
+ start = cross_start + part * cross_size // 5
340
+ end = cross_start + (part + 1) * cross_size // 5
341
+ colors = []
342
+ for offset in distances:
343
+ parallel = boundary + direction * offset
344
+ for cross in range(start, end, max(1, (end - start) // 16)):
345
+ colors.append(pixels[parallel, cross] if axis == 0 else pixels[cross, parallel])
346
+ if colors:
347
+ cross_position = (start + end - 1) / 2
348
+ parallel_position = boundary + direction * (distances[0] + distances[-1]) / 2
349
+ x, y = (parallel_position, cross_position) if axis == 0 else (cross_position, parallel_position)
350
+ color = tuple(median(channel) for channel in zip(*colors))
351
+ samples.append((x, y, color))
352
+ strip.append((cross_position, color))
353
+ # Use long differences along a strip to keep texture out of the slope.
354
+ # An image-edge strip can contain the subject and is only a fallback.
355
+ if room:
356
+ for index, (start, first) in enumerate(strip):
357
+ for end, last in strip[index + 2:]:
358
+ slopes[1 - axis].append(tuple((b - a) / (end - start) for a, b in zip(first, last)))
359
+
360
+ dx, dy = [
361
+ tuple(max(-24 / span, min(24 / span, median(channel))) for channel in zip(*axis_slopes))
362
+ if axis_slopes else (0.0, 0.0, 0.0)
363
+ for axis_slopes, span in zip(slopes, (width, height))
364
+ ]
365
+ origin = tuple(median(c[i] - dx[i] * x - dy[i] * y for x, y, c in samples) for i in range(3))
366
+
367
+ def background(x: int, y: int) -> _Color:
368
+ return tuple(max(0, min(255, round(v + sx * x + sy * y))) for v, sx, sy in zip(origin, dx, dy))
369
+
370
+ background._plane = (origin, dx, dy) # type: ignore[attr-defined]
371
+ local_card_bg = _detect_local_card_background(rgb, box, background)
372
+ if local_card_bg is not None:
373
+ return local_card_bg
374
+ return background
375
+
376
+
377
+ def _detect_local_card_background(rgb: Image.Image, box: _Box, far_background: _Background) -> _Background | None:
378
+ """Detect when `box` sits inside a uniform card whose surface differs from the outer canvas.
379
+
380
+ `_blend_background` samples beyond `limits` (~50px out), which can jump across a card
381
+ border onto a differently tinted slide canvas. When >=65% of the requested box's own
382
+ 4-side perimeter (and >=60% of the immediate 2px exterior ring) shares a uniform local
383
+ surface that differs from `far_background` by >6 RGB, return a constant local-surface
384
+ background plane so we never treat the card interior as foreground.
385
+ """
386
+ left, top, right, bottom = box
387
+ width, height = right - left, bottom - top
388
+ if min(width, height) < 8:
389
+ return None
390
+ pixels = rgb.load()
391
+ room = (left, top, rgb.width - right, rgb.height - bottom)
392
+ in_pts: list[tuple[int, int, _Color]] = []
393
+ out_pts: list[_Color] = []
394
+
395
+ for side in range(4):
396
+ step = max(1, (height if side % 2 == 0 else width) // 40)
397
+ direction = -1 if side < 2 else 1
398
+ dx, dy = (direction, 0) if side % 2 == 0 else (0, direction)
399
+ for x, y in _blend_boundary(box, side, step=step):
400
+ in_pts.append((x, y, pixels[x, y]))
401
+ if room[side] >= 2:
402
+ out_pts.append(pixels[x + dx * 2, y + dy * 2])
403
+
404
+ if len(in_pts) < 12:
405
+ return None
406
+
407
+ med0: _Color = tuple(round(median(c)) for c in zip(*(p[2] for p in in_pts))) # type: ignore[assignment]
408
+ inliers = [p for p in in_pts if _color_distance(p[2], med0) <= 10]
409
+ if not inliers:
410
+ return None
411
+ local_bg: _Color = tuple(round(median(c)) for c in zip(*(p[2] for p in inliers))) # type: ignore[assignment]
412
+ inliers = [p for p in in_pts if _color_distance(p[2], local_bg) <= 10]
413
+ if (len(inliers) / float(len(in_pts))) < 0.65:
414
+ return None
415
+
416
+ # Ensure the local surface actually continues outside `box` (rejects hard-edged full-rect cards/photos).
417
+ if out_pts:
418
+ out_match = sum(1 for col in out_pts if _color_distance(col, local_bg) <= 10) / float(len(out_pts))
419
+ if out_match < 0.60:
420
+ return None
421
+
422
+ local_err = sorted(_color_distance(col, local_bg) for _, _, col in inliers)
423
+ far_err = sorted(_color_distance(col, far_background(x, y)) for x, y, col in inliers)
424
+ if not far_err:
425
+ return None
426
+ p75_local = local_err[int(0.75 * (len(local_err) - 1))]
427
+ p75_far = far_err[int(0.75 * (len(far_err) - 1))]
428
+ med_local = median(local_err)
429
+ med_far = median(far_err)
430
+ # Only override far_background with a constant local card surface when the perimeter itself
431
+ # is tightly uniform (p75 <= 5 RGB), far_background has clear error along the perimeter
432
+ # (p75 > 6 RGB), and local_bg fits strictly tighter than far_background (so smooth linear
433
+ # gradient slides preserve their fitted linear plane).
434
+ if p75_local > 5 or p75_far <= 6 or (p75_local + 4 >= p75_far) or (med_local + 2.5 >= med_far):
435
+ return None
436
+
437
+ origin = (float(local_bg[0]), float(local_bg[1]), float(local_bg[2]))
438
+ zero = (0.0, 0.0, 0.0)
439
+
440
+ def local_background(x: int, y: int) -> _Color:
441
+ return local_bg
442
+
443
+ local_background._plane = (origin, zero, zero) # type: ignore[attr-defined]
444
+ local_background._is_local_card = True # type: ignore[attr-defined]
445
+ return local_background
446
+
447
+
448
+ def _blend_boundary(box: _Box | list[int], side: int, step: int = 1) -> Iterator[tuple[int, int]]:
449
+ left, top, right, bottom = box
450
+ if side % 2 == 0:
451
+ x = left if side == 0 else right - 1
452
+ return ((x, y) for y in range(top, bottom, step))
453
+ y = top if side == 1 else bottom - 1
454
+ return ((x, y) for x in range(left, right, step))
455
+
456
+
457
+ def _color_distance(a: _Color, b: _Color) -> int:
458
+ return max(abs(r - s) for r, s in zip(a, b))
459
+
460
+
461
+ def _inspect_blend_background(rgb: Image.Image, box: _Box, limits: list[int], background: _Background) -> tuple[bool, bool]:
462
+ """Return `(can_blend, is_hard_rect)` for the requested crop border."""
463
+ pixels = rgb.load()
464
+ room = (box[0], box[1], rgb.width - box[2], rgb.height - box[3])
465
+ width, height = box[2] - box[0], box[3] - box[1]
466
+ count = matches = falls_off = 0
467
+ hard_sides = 0
468
+ for side in range(4):
469
+ if not room[side]:
470
+ continue
471
+ direction = -1 if side < 2 else 1
472
+ dx, dy = (direction, 0) if side % 2 == 0 else (0, direction)
473
+ limit = limits[side]
474
+ step = max(1, (height, width)[side % 2] // 100)
475
+ side_count = abrupt = 0
476
+ for x, y in _blend_boundary(box, side, step):
477
+ count += 1
478
+ side_count += 1
479
+ color = pixels[x, y]
480
+ distance = _color_distance(color, background(x, y))
481
+ outer = pixels[x + dx, y + dy]
482
+ adjacent_change = _color_distance(color, outer)
483
+ if adjacent_change > 9:
484
+ if room[side] == 1 or adjacent_change > 2 * _color_distance(outer, pixels[x + 2 * dx, y + 2 * dy]) + 4:
485
+ abrupt += 1
486
+ if distance <= 13:
487
+ matches += 1
488
+ elif limit and distance <= 80 and adjacent_change <= 9:
489
+ end_x, end_y = x + dx * limit, y + dy * limit
490
+ if _color_distance(pixels[end_x, end_y], background(end_x, end_y)) <= 13:
491
+ falls_off += 1
492
+ if abrupt >= 0.55 * side_count:
493
+ hard_sides += 1
494
+ # Straight transitions across several sides indicate a full rectangular image.
495
+ if not count or hard_sides >= 2:
496
+ return False, hard_sides >= 2
497
+ can_blend = matches >= 0.15 * count or matches + falls_off >= 0.5 * count
498
+ return can_blend, False
499
+
500
+
501
+ def _has_blend_background(rgb: Image.Image, box: _Box, limits: list[int], background: _Background) -> bool:
502
+ """Look for paper or a smooth falloff into paper at the requested border."""
503
+ can_blend, _ = _inspect_blend_background(rgb, box, limits, background)
504
+ return can_blend
505
+
506
+
507
+ def _blend_exterior(rgb: Image.Image, background: Image.Image) -> tuple[bytearray, bytes]:
508
+ """Flood through smoothly varying background, shadow and glow pixels."""
509
+ width, height = rgb.size
510
+ total = width * height
511
+ differences = ImageChops.difference(rgb, background)
512
+ r, g, b = differences.split()
513
+ distance = ImageChops.lighter(ImageChops.lighter(r, g), b).tobytes()
514
+ source = rgb.tobytes()
515
+ paper = background.tobytes()
516
+ r, g, b = rgb.split()
517
+ white_core = ImageChops.darker(ImageChops.darker(r, g), b).filter(ImageFilter.MinFilter(3)).tobytes()
518
+ exterior = bytearray(total)
519
+ queue: deque[int] = deque()
520
+ q_append = queue.append
521
+ q_popleft = queue.popleft
522
+ noise = _BLEND_NOISE
523
+
524
+ def _seed(index: int) -> None:
525
+ if exterior[index] or distance[index] > 80:
526
+ return
527
+ cur = index * 3
528
+ s0 = source[cur]
529
+ s1 = source[cur + 1]
530
+ s2 = source[cur + 2]
531
+ p0 = paper[cur]
532
+ p1 = paper[cur + 1]
533
+ p2 = paper[cur + 2]
534
+ if white_core[index] >= 253 and s0 - p0 >= 2 and s1 - p1 >= 2 and s2 - p2 >= 2:
535
+ return
536
+ if distance[index] > noise:
537
+ if (s0 if s0 < s1 else s1) >= 250 and s2 >= 250 and (s0 + s1 + s2) - (p0 + p1 + p2) >= 12:
538
+ return
539
+ exterior[index] = 255
540
+ q_append(index)
541
+
542
+ for side in range(4):
543
+ for x, y in _blend_boundary((0, 0, width, height), side):
544
+ index = y * width + x
545
+ if distance[index] <= 10:
546
+ _seed(index)
547
+
548
+ last_row_start = total - width
549
+ w_minus_1 = width - 1
550
+ while queue:
551
+ index = q_popleft()
552
+ x = index % width
553
+ prev_dist = distance[index]
554
+ prev_off = index * 3
555
+ pr = source[prev_off]
556
+ pg = source[prev_off + 1]
557
+ pb = source[prev_off + 2]
558
+
559
+ # Inline 4-connected neighbors to avoid per-neighbor function-call/slice overhead.
560
+ n0 = index - 1 if x else -1
561
+ n1 = index + 1 if x < w_minus_1 else -1
562
+ n2 = index - width if index >= width else -1
563
+ n3 = index + width if index < last_row_start else -1
564
+ for nb in (n0, n1, n2, n3):
565
+ if nb < 0 or exterior[nb]:
566
+ continue
567
+ d_nb = distance[nb]
568
+ if d_nb > 80:
569
+ continue
570
+ cur = nb * 3
571
+ s0 = source[cur]
572
+ s1 = source[cur + 1]
573
+ s2 = source[cur + 2]
574
+ if white_core[nb] >= 253:
575
+ if s0 - paper[cur] >= 2 and s1 - paper[cur + 1] >= 2 and s2 - paper[cur + 2] >= 2:
576
+ continue
577
+ if d_nb > noise or prev_dist > noise:
578
+ if s0 >= 250 and s1 >= 250 and s2 >= 250:
579
+ if (s0 + s1 + s2) - (paper[cur] + paper[cur + 1] + paper[cur + 2]) >= 12:
580
+ continue
581
+ dr = s0 - pr
582
+ if dr < 0:
583
+ dr = -dr
584
+ dg = s1 - pg
585
+ if dg < 0:
586
+ dg = -dg
587
+ db = s2 - pb
588
+ if db < 0:
589
+ db = -db
590
+ if dr > 9 or dg > 9 or db > 9 or (dr + dg + db) > 17:
591
+ continue
592
+ exterior[nb] = 255
593
+ q_append(nb)
594
+
595
+ if exterior.count(255) > 0.75 * total:
596
+ # Low-contrast subjects can leak at a short gap in their outline.
597
+ # Keep interiors enclosed once those gaps are closed, without using
598
+ # the outlines themselves as part of the opaque subject.
599
+ closed = _enclosed_blend_interior(rgb)
600
+ exterior = bytearray(ImageChops.subtract(Image.frombytes("L", rgb.size, bytes(exterior)), closed).tobytes())
601
+ return exterior, distance
602
+
603
+
604
+ def _floodfill_l_seeds(
605
+ img: Image.Image,
606
+ seeds: list[tuple[int, int]],
607
+ target: int,
608
+ fill: int,
609
+ ) -> Image.Image:
610
+ """Fast flat-bytearray 4-connected floodfill on an 'L' image (10-100x faster than PIL.ImageDraw.floodfill)."""
611
+ w, h = img.size
612
+ buf = bytearray(img.tobytes())
613
+ q: deque[int] = deque()
614
+ q_append = q.append
615
+ q_popleft = q.popleft
616
+ for sx, sy in seeds:
617
+ if 0 <= sx < w and 0 <= sy < h:
618
+ idx = sy * w + sx
619
+ if buf[idx] == target:
620
+ buf[idx] = fill
621
+ q_append(idx)
622
+ total = w * h
623
+ last_row = total - w
624
+ w_minus_1 = w - 1
625
+ while q:
626
+ idx = q_popleft()
627
+ x = idx % w
628
+ if x and buf[idx - 1] == target:
629
+ buf[idx - 1] = fill
630
+ q_append(idx - 1)
631
+ if x < w_minus_1 and buf[idx + 1] == target:
632
+ buf[idx + 1] = fill
633
+ q_append(idx + 1)
634
+ if idx >= w and buf[idx - w] == target:
635
+ buf[idx - w] = fill
636
+ q_append(idx - w)
637
+ if idx < last_row and buf[idx + w] == target:
638
+ buf[idx + w] = fill
639
+ q_append(idx + w)
640
+ return Image.frombytes("L", (w, h), bytes(buf))
641
+
642
+
643
+ def _enclosed_blend_interior(rgb: Image.Image) -> Image.Image:
644
+ width, height = rgb.size
645
+ smoothed = rgb.filter(ImageFilter.GaussianBlur(0.55))
646
+ edges = []
647
+ for dx, dy in ((2, 0), (0, 2)):
648
+ shifted = ImageChops.offset(smoothed, dx, dy)
649
+ opposite = ImageChops.offset(smoothed, -dx, -dy)
650
+ r, g, b = ImageChops.difference(shifted, opposite).split()
651
+ strength = ImageChops.add(ImageChops.add(r, g), b)
652
+ contour = strength.point(lambda value: 255 if value >= 15 else 0)
653
+ # Suppress gradients caused by the wrapping offset at the image boundary.
654
+ if dx:
655
+ contour.paste(0, (0, 0, dx, height))
656
+ contour.paste(0, (width - dx, 0, width, height))
657
+ else:
658
+ contour.paste(0, (0, 0, width, dy))
659
+ contour.paste(0, (0, height - dy, width, height))
660
+ edges.append(contour)
661
+ contour = ImageChops.lighter(*edges).filter(ImageFilter.MaxFilter(7)).filter(ImageFilter.MinFilter(7))
662
+ padded = ImageOps.expand(contour, border=1, fill=0)
663
+ padded = _floodfill_l_seeds(padded, [(0, 0)], 0, 128)
664
+ inside = padded.crop((1, 1, width + 1, height + 1)).point(lambda value: 255 if value == 0 else 0)
665
+ return inside.filter(ImageFilter.MinFilter(9)).filter(ImageFilter.MaxFilter(9))
666
+
667
+
668
+ def _blend_color(source: _Color, background: _Color) -> tuple[int, int, int, int]:
669
+ """Uncomposite the pixel with the least alpha that keeps RGB in gamut."""
670
+ differences = [color - base for color, base in zip(source, background)]
671
+ distance = max(map(abs, differences))
672
+ if distance <= _BLEND_NOISE:
673
+ return 0, 0, 0, 0
674
+ # Suppress paper grain without introducing a jump at the noise threshold.
675
+ strength = min(1.0, (distance - _BLEND_NOISE) / _BLEND_NOISE)
676
+ delta = [change * strength for change in differences]
677
+ alpha = math.ceil(255 * max(
678
+ change / (255 - base) if change > 0 else -change / base if change < 0 else 0
679
+ for change, base in zip(delta, background)
680
+ ))
681
+ color = tuple(max(0, min(255, round(base + change * 255 / alpha))) for base, change in zip(background, delta))
682
+ return (*color, alpha)
683
+
684
+
685
+ def _grow_blend_box(rgb: Image.Image, original: _Box, limits: list[int], background: _Background) -> _Box:
686
+ # Grow independently and leave room for the final taper past the last
687
+ # coherent non-background run on each side, stopping before card borders
688
+ # or disconnected neighboring marks (such as card titles) across quiet gaps.
689
+ smoothed = rgb.filter(ImageFilter.BoxBlur(1)).load()
690
+ is_local_card = bool(getattr(background, "_is_local_card", False))
691
+ grown = list(original)
692
+ for side, limit in enumerate(limits):
693
+ if not limit:
694
+ continue
695
+ direction = -1 if side < 2 else 1
696
+ quiet = 0
697
+ prev_non_bg_frac = 0.0
698
+ for amount in range(limit + 1):
699
+ probe = list(original)
700
+ probe[side] += direction * amount
701
+ run = 0
702
+ has_run = False
703
+ side_len = 0
704
+ non_bg_count = 0
705
+ border_shift_count = 0
706
+ for x, y in _blend_boundary(probe, side):
707
+ side_len += 1
708
+ distance = _color_distance(smoothed[x, y], background(x, y))
709
+ if distance > _BLEND_NOISE + 1:
710
+ non_bg_count += 1
711
+ if distance > _BLEND_NOISE + 2:
712
+ border_shift_count += 1
713
+ run += 1
714
+ if run >= 4:
715
+ has_run = True
716
+ else:
717
+ run = 0
718
+
719
+ non_bg_frac = non_bg_count / float(max(1, side_len))
720
+ border_shift_frac = border_shift_count / float(max(1, side_len))
721
+
722
+ # Stop BEFORE a sudden broad surface shift (card border / container edge).
723
+ if amount >= 1 and border_shift_frac >= 0.40:
724
+ if border_shift_frac > prev_non_bg_frac + 0.15 or (is_local_card and amount >= 2 and prev_non_bg_frac < 0.35):
725
+ break
726
+
727
+ if has_run:
728
+ # Once we have exited the subject through a clean quiet gap, never re-enter
729
+ # a disconnected mark (e.g. neighboring card text or adjacent illustration).
730
+ if quiet >= 1:
731
+ break
732
+ quiet = 0
733
+ else:
734
+ quiet += 1
735
+ if quiet == 1 and amount == 0:
736
+ break
737
+
738
+ grown[side] = probe[side]
739
+ prev_non_bg_frac = non_bg_frac
740
+ if quiet > _BLEND_FADE:
741
+ break
742
+
743
+ return tuple(grown)
744
+
745
+
746
+ def _blend_margin_fill(
747
+ src_bytes: bytes,
748
+ known_bytes: bytes,
749
+ width: int,
750
+ height: int,
751
+ x: int,
752
+ y: int,
753
+ background: _Color,
754
+ ) -> _Color:
755
+ """Interpolate nearby exterior colors across a removed mark in the margin."""
756
+ w_sum = 0.0
757
+ r_sum = 0.0
758
+ g_sum = 0.0
759
+ b_sum = 0.0
760
+ for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
761
+ for distance in range(1, 49):
762
+ nx = x + dx * distance
763
+ ny = y + dy * distance
764
+ if nx < 0 or nx >= width or ny < 0 or ny >= height:
765
+ break
766
+ n_idx = ny * width + nx
767
+ if known_bytes[n_idx]:
768
+ inv = 1.0 / distance
769
+ off = n_idx * 3
770
+ r_sum += src_bytes[off] * inv
771
+ g_sum += src_bytes[off + 1] * inv
772
+ b_sum += src_bytes[off + 2] * inv
773
+ w_sum += inv
774
+ break
775
+ if w_sum <= 0.0:
776
+ return background
777
+ return (round(r_sum / w_sum), round(g_sum / w_sum), round(b_sum / w_sum))
778
+
779
+
780
+ def _render_background_plane(background: _Background, box: _Box) -> Image.Image:
781
+ """Render linear RGB plane over `box` in C via exact float bilinear resize (<=1 LSB everywhere incl. borders)."""
782
+ x0, y0, x1, y1 = box
783
+ width, height = x1 - x0, y1 - y0
784
+ plane = getattr(background, "_plane", None)
785
+ if plane is not None:
786
+ origin, dx, dy = plane
787
+ o0, o1, o2 = origin
788
+ dx0, dx1, dx2 = dx
789
+ dy0, dy1, dy2 = dy
790
+ if dx0 == 0.0 and dx1 == 0.0 and dx2 == 0.0 and dy0 == 0.0 and dy1 == 0.0 and dy2 == 0.0:
791
+ c0 = max(0, min(255, round(o0)))
792
+ c1 = max(0, min(255, round(o1)))
793
+ c2 = max(0, min(255, round(o2)))
794
+ return Image.new("RGB", (width, height), (c0, c1, c2))
795
+ if width >= 2 and height >= 2:
796
+ # Map output pixel centers x=0..width-1 strictly onto input centers 0.5..1.5 so edges never clamp.
797
+ bx0 = 0.5 - 0.5 / (width - 1)
798
+ bx1 = 1.5 + 0.5 / (width - 1)
799
+ by0 = 0.5 - 0.5 / (height - 1)
800
+ by1 = 1.5 + 0.5 / (height - 1)
801
+ xa, xb = float(x0), float(x1 - 1)
802
+ ya, yb = float(y0), float(y1 - 1)
803
+ bands: list[Image.Image] = []
804
+ for o_c, sx_c, sy_c in ((o0, dx0, dy0), (o1, dx1, dy1), (o2, dx2, dy2)):
805
+ if sx_c == 0.0 and sy_c == 0.0:
806
+ bands.append(Image.new("L", (width, height), max(0, min(255, round(o_c)))))
807
+ continue
808
+ im_f = Image.new("F", (2, 2))
809
+ im_f.putdata(
810
+ [
811
+ o_c + sx_c * xa + sy_c * ya,
812
+ o_c + sx_c * xb + sy_c * ya,
813
+ o_c + sx_c * xa + sy_c * yb,
814
+ o_c + sx_c * xb + sy_c * yb,
815
+ ]
816
+ )
817
+ resized = im_f.resize((width, height), Image.Resampling.BILINEAR, box=(bx0, by0, bx1, by1))
818
+ bands.append(resized.point(lambda v: v + 0.5).convert("L"))
819
+ return Image.merge("RGB", bands)
820
+ background_bytes = bytearray(width * height * 3)
821
+ pos = 0
822
+ for y in range(y0, y1):
823
+ for x in range(x0, x1):
824
+ c0, c1, c2 = background(x, y)
825
+ background_bytes[pos] = c0
826
+ background_bytes[pos + 1] = c1
827
+ background_bytes[pos + 2] = c2
828
+ pos += 3
829
+ return Image.frombytes("RGB", (width, height), bytes(background_bytes))
830
+
831
+
832
+ def _blend_crop_with_meta(raw: Image.Image, original: _Box) -> tuple[Image.Image, _Box, str | None]:
833
+ """Crop against the surrounding page and return (image, final_box, skip_reason)."""
834
+ left, top, right, bottom = original
835
+ width, height = right - left, bottom - top
836
+ crop = raw.crop(original)
837
+ if min(width, height) < 4 or crop.convert("RGBA").getchannel("A").getextrema()[0] < 255:
838
+ return crop, original, None
839
+
840
+ rgb = raw.convert("RGB")
841
+ room = (left, top, rgb.width - right, rgb.height - bottom)
842
+ limits = [min(96, round(span * 0.15), space) for span, space in zip((width, height, width, height), room)]
843
+ background = _blend_background(rgb, original, limits)
844
+ can_blend, is_hard_rect = _inspect_blend_background(rgb, original, limits, background)
845
+ if not can_blend:
846
+ # A full-rectangle photo or screenshot has hard edges on >=2 sides and should keep its box;
847
+ # a gradient/textured non-hard-rect region can safely fall back to soft edge feathering.
848
+ return crop, original, ("hard_rect" if is_hard_rect else "non_uniform_bg")
849
+
850
+ final = _grow_blend_box(rgb, original, limits, background)
851
+ local = rgb.crop(final)
852
+ paper = _render_background_plane(background, final)
853
+ exterior, distances = _blend_exterior(local, paper)
854
+ if not any(exterior):
855
+ return crop, original, "non_uniform_bg"
856
+
857
+ width, height = local.size
858
+ detached = None
859
+ known_bytes: bytes = b""
860
+ if final != original:
861
+ # Discard unrelated marks that enter the grown margin without touching
862
+ # the requested box (for example, neighboring slide text).
863
+ solids = ImageChops.invert(Image.frombytes("L", local.size, bytes(exterior)))
864
+ rx0, ry0, rx1, ry1 = left - final[0], top - final[1], right - final[0], bottom - final[1]
865
+ requested = (rx0, ry0, rx1, ry1)
866
+ solids.paste(128, requested)
867
+ # Seed only the 1px exterior ring bordering `requested` so we never re-flood the interior.
868
+ margin_seeds: list[tuple[int, int]] = []
869
+ if ry0 > 0:
870
+ margin_seeds.extend((x, ry0 - 1) for x in range(rx0, rx1))
871
+ if ry1 < height:
872
+ margin_seeds.extend((x, ry1) for x in range(rx0, rx1))
873
+ if rx0 > 0:
874
+ margin_seeds.extend((rx0 - 1, y) for y in range(ry0, ry1))
875
+ if rx1 < width:
876
+ margin_seeds.extend((rx1, y) for y in range(ry0, ry1))
877
+ if margin_seeds:
878
+ solids = _floodfill_l_seeds(solids, margin_seeds, 255, 128)
879
+ detached = solids.point(lambda value: 255 if value == 255 else 0).filter(ImageFilter.MaxFilter(7))
880
+ detached.paste(0, requested)
881
+ if detached.getbbox():
882
+ # Interpolate the surrounding halo through excluded marks so the
883
+ # transparent result does not have text-shaped holes.
884
+ known = ImageChops.multiply(
885
+ Image.frombytes("L", local.size, bytes(exterior)), ImageChops.invert(detached)
886
+ )
887
+ known_bytes = known.tobytes()
888
+
889
+ out = local.convert("RGBA")
890
+ rgba_buf = bytearray(out.tobytes())
891
+ src_bytes = local.tobytes()
892
+ base_bytes = paper.tobytes()
893
+ has_excluded = bool(known_bytes and detached is not None)
894
+ excluded = detached.tobytes() if has_excluded else b""
895
+ noise = _BLEND_NOISE
896
+
897
+ if has_excluded:
898
+ for index in range(width * height):
899
+ if excluded[index]:
900
+ y, x = divmod(index, width)
901
+ off3 = index * 3
902
+ b_col = (base_bytes[off3], base_bytes[off3 + 1], base_bytes[off3 + 2])
903
+ fill = _blend_margin_fill(src_bytes, known_bytes, width, height, x, y, b_col)
904
+ r, g, b, a = _blend_color(fill, b_col)
905
+ off4 = index * 4
906
+ rgba_buf[off4] = r
907
+ rgba_buf[off4 + 1] = g
908
+ rgba_buf[off4 + 2] = b
909
+ rgba_buf[off4 + 3] = a
910
+ elif exterior[index]:
911
+ off4 = index * 4
912
+ if distances[index] <= noise:
913
+ rgba_buf[off4] = 0
914
+ rgba_buf[off4 + 1] = 0
915
+ rgba_buf[off4 + 2] = 0
916
+ rgba_buf[off4 + 3] = 0
917
+ else:
918
+ off3 = index * 3
919
+ r, g, b, a = _blend_color(
920
+ (src_bytes[off3], src_bytes[off3 + 1], src_bytes[off3 + 2]),
921
+ (base_bytes[off3], base_bytes[off3 + 1], base_bytes[off3 + 2]),
922
+ )
923
+ rgba_buf[off4] = r
924
+ rgba_buf[off4 + 1] = g
925
+ rgba_buf[off4 + 2] = b
926
+ rgba_buf[off4 + 3] = a
927
+ else:
928
+ for index in range(width * height):
929
+ if not exterior[index]:
930
+ continue
931
+ off4 = index * 4
932
+ if distances[index] <= noise:
933
+ rgba_buf[off4] = 0
934
+ rgba_buf[off4 + 1] = 0
935
+ rgba_buf[off4 + 2] = 0
936
+ rgba_buf[off4 + 3] = 0
937
+ else:
938
+ off3 = index * 3
939
+ r, g, b, a = _blend_color(
940
+ (src_bytes[off3], src_bytes[off3 + 1], src_bytes[off3 + 2]),
941
+ (base_bytes[off3], base_bytes[off3 + 1], base_bytes[off3 + 2]),
942
+ )
943
+ rgba_buf[off4] = r
944
+ rgba_buf[off4 + 1] = g
945
+ rgba_buf[off4 + 2] = b
946
+ rgba_buf[off4 + 3] = a
947
+
948
+ out = Image.frombytes("RGBA", (width, height), bytes(rgba_buf))
949
+ pixels = out.load()
950
+
951
+ for side, edge in enumerate(final):
952
+ if edge == (0, 0, rgb.width, rgb.height)[side]:
953
+ continue
954
+ direction = 1 if side < 2 else -1
955
+ # A capped halo can still be visible at the edge. Ease its falloff
956
+ # within the added margin, keeping the three-pixel taper on solids.
957
+ growth = abs(edge - original[side])
958
+ soft_span = max(_BLEND_FADE, min(growth // 2, 24)) if growth == limits[side] else _BLEND_FADE
959
+ for offset in range(min(soft_span, (width, height)[side % 2])):
960
+ strip = [0, 0, width, height]
961
+ strip[side] += direction * offset
962
+ for x, y in _blend_boundary(strip, side):
963
+ r, g, b, a = pixels[x, y]
964
+ idx_xy = y * width + x
965
+ if exterior[idx_xy] or (has_excluded and excluded[idx_xy]):
966
+ factor = offset / soft_span
967
+ factor = factor * factor * (3 - 2 * factor)
968
+ else:
969
+ factor = min(1.0, offset / _BLEND_FADE)
970
+ pixels[x, y] = (r, g, b, round(a * factor))
971
+ return out, final, None
972
+
973
+
974
+ def _blend_crop(raw: Image.Image, original: _Box) -> tuple[Image.Image, _Box]:
975
+ """Crop against the surrounding page and return the crop and final box."""
976
+ out, final, _ = _blend_crop_with_meta(raw, original)
977
+ return out, final
978
+
979
+
980
+ def _apply_shape_mask(rgba: Image.Image, mask_spec: str, r_scale: float) -> Image.Image:
981
+ """Apply anti-aliased 4x supersampled geometric alpha mask (`rect|circle|pill|rounded:R`)."""
982
+ spec = (mask_spec or "rect").strip().lower()
983
+ if spec == "rect":
984
+ return rgba
985
+
986
+ w, h = rgba.size
987
+ ss = 4
988
+ sw, sh = w * ss, h * ss
989
+ mask_hi = Image.new("L", (sw, sh), 0)
990
+ draw = ImageDraw.Draw(mask_hi)
991
+
992
+ if spec == "circle":
993
+ diam = min(sw, sh)
994
+ x0 = (sw - diam) // 2
995
+ y0 = (sh - diam) // 2
996
+ draw.ellipse([x0, y0, x0 + diam - 1, y0 + diam - 1], fill=255)
997
+ elif spec == "pill":
998
+ # True stadium capsule: radius = min(w, h) / 2 on BOTH top and bottom (and left/right)
999
+ radius = min(sw, sh) / 2.0
1000
+ draw.rounded_rectangle([0, 0, sw - 1, sh - 1], radius=radius, fill=255)
1001
+ elif spec.startswith("rounded:"):
1002
+ raw_r = spec.split(":", 1)[1].strip()
1003
+ try:
1004
+ r_val = float(raw_r)
1005
+ except ValueError as exc:
1006
+ raise ValueError(f"Invalid rounded mask radius in {mask_spec!r}") from exc
1007
+ if r_val < 0:
1008
+ raise ValueError(f"Rounded mask radius must be >= 0, got {r_val}")
1009
+ radius = min(min(sw, sh) / 2.0, r_val * r_scale * ss)
1010
+ draw.rounded_rectangle([0, 0, sw - 1, sh - 1], radius=radius, fill=255)
1011
+ else:
1012
+ raise ValueError(f"Unsupported mask: {mask_spec!r} (expected rect|circle|pill|rounded:R)")
1013
+
1014
+ shape_alpha = mask_hi.resize((w, h), Image.Resampling.LANCZOS)
1015
+ existing_alpha = rgba.getchannel("A")
1016
+ combined_alpha = ImageChops.multiply(existing_alpha, shape_alpha)
1017
+ out = rgba.copy()
1018
+ out.putalpha(combined_alpha)
1019
+ return out
1020
+
1021
+
1022
+ def _apply_fade_edges(rgba: Image.Image, fade_spec: str | None) -> Image.Image:
1023
+ """Smoothly fade alpha to 0 over outer percentage of specified edges (e.g. 'bottom:30,left:15')."""
1024
+ if not fade_spec or not str(fade_spec).strip():
1025
+ return rgba
1026
+
1027
+ edges: list[tuple[str, float]] = []
1028
+ for chunk in str(fade_spec).split(","):
1029
+ part = chunk.strip()
1030
+ if not part:
1031
+ continue
1032
+ if ":" not in part:
1033
+ raise ValueError(f"Invalid fade-edge token {part!r}; expected '<side>:<pct>' e.g. 'bottom:30'")
1034
+ side, pct_s = part.split(":", 1)
1035
+ side = side.strip().lower()
1036
+ if side not in ("top", "bottom", "left", "right"):
1037
+ raise ValueError(f"Invalid fade-edge side {side!r}; expected top|bottom|left|right")
1038
+ pct = float(pct_s.strip().rstrip("%"))
1039
+ if pct <= 0 or pct > 100:
1040
+ raise ValueError(f"fade-edge percentage must be in (0, 100], got {pct}")
1041
+ edges.append((side, pct))
1042
+
1043
+ if not edges:
1044
+ return rgba
1045
+
1046
+ w, h = rgba.size
1047
+ row_mult = [1.0] * h
1048
+ col_mult = [1.0] * w
1049
+
1050
+ def _smoothstep(t: float) -> float:
1051
+ t = max(0.0, min(1.0, t))
1052
+ return t * t * (3.0 - 2.0 * t)
1053
+
1054
+ for side, pct in edges:
1055
+ if side in ("top", "bottom"):
1056
+ span = max(1, int(round(h * (pct / 100.0))))
1057
+ denom = max(1.0, float(span - 1)) if span > 1 else 1.0
1058
+ for i in range(span):
1059
+ t = (i / denom) if span > 1 else 0.0
1060
+ f = _smoothstep(t)
1061
+ y = i if side == "top" else (h - 1 - i)
1062
+ row_mult[y] *= f
1063
+ else:
1064
+ span = max(1, int(round(w * (pct / 100.0))))
1065
+ denom = max(1.0, float(span - 1)) if span > 1 else 1.0
1066
+ for i in range(span):
1067
+ t = (i / denom) if span > 1 else 0.0
1068
+ f = _smoothstep(t)
1069
+ x = i if side == "left" else (w - 1 - i)
1070
+ col_mult[x] *= f
1071
+
1072
+ alpha = rgba.getchannel("A")
1073
+ row_img = Image.frombytes("L", (1, h), bytes(int(round(m * 255)) for m in row_mult)).resize(
1074
+ (w, h), Image.Resampling.NEAREST
1075
+ )
1076
+ col_img = Image.frombytes("L", (w, 1), bytes(int(round(m * 255)) for m in col_mult)).resize(
1077
+ (w, h), Image.Resampling.NEAREST
1078
+ )
1079
+ fade_mask = ImageChops.multiply(row_img, col_img)
1080
+ new_alpha = ImageChops.multiply(alpha, fade_mask)
1081
+ out = rgba.copy()
1082
+ out.putalpha(new_alpha)
1083
+ return out
1084
+
1085
+
1086
+ def _detect_bleed_edges(work: Image.Image, crop_px: _Box, src_w: int, src_h: int) -> list[str]:
1087
+ """Return canvas edges ('top','bottom','left','right') where the crop is flush-clipped at the source border."""
1088
+ x0, y0, x1, y1 = crop_px
1089
+ touched: list[str] = []
1090
+ if y0 <= 2:
1091
+ touched.append("top")
1092
+ if y1 >= src_h - 2:
1093
+ touched.append("bottom")
1094
+ if x0 <= 2:
1095
+ touched.append("left")
1096
+ if x1 >= src_w - 2:
1097
+ touched.append("right")
1098
+ if not touched or work.mode != "RGBA":
1099
+ return touched
1100
+
1101
+ w, h = work.size
1102
+ if w < 8 or h < 8:
1103
+ return []
1104
+ alpha = work.getchannel("A")
1105
+ px = alpha.load()
1106
+ bleed: list[str] = []
1107
+ for side in touched:
1108
+ if side == "top":
1109
+ vals = [int(px[x, 0]) for x in range(w)]
1110
+ elif side == "bottom":
1111
+ vals = [int(px[x, h - 1]) for x in range(w)]
1112
+ elif side == "left":
1113
+ vals = [int(px[0, y]) for y in range(h)]
1114
+ else:
1115
+ vals = [int(px[w - 1, y]) for y in range(h)]
1116
+ max_run = 0
1117
+ cur = 0
1118
+ for a in vals:
1119
+ if a >= 160:
1120
+ cur += 1
1121
+ if cur > max_run:
1122
+ max_run = cur
1123
+ else:
1124
+ cur = 0
1125
+ if max_run >= 16 and (max_run / float(max(1, len(vals)))) >= 0.08:
1126
+ bleed.append(side)
1127
+ return bleed
1128
+
1129
+
1130
+ def detect_residual_crop_text(img: Image.Image) -> dict[str, Any]:
1131
+ """Detect detached horizontal text-glyph bands near the top or bottom edge of a transparent crop.
1132
+
1133
+ Pure-Pillow, zero-OCR detector designed to catch neighboring slide titles/captions
1134
+ accidentally sliced into transparent/blended cutouts (`<= 22%` height band separated
1135
+ by a `>= 3px` transparent gap from the main visual body, with `>= 3` horizontally
1136
+ aligned opaque glyph-like components of height `7-44px`).
1137
+ """
1138
+ clean: dict[str, Any] = {"has_residual_text": False, "edges": [], "bands": []}
1139
+ if "A" not in img.getbands() and "transparency" not in img.info:
1140
+ return clean
1141
+ rgba = img if img.mode == "RGBA" else img.convert("RGBA")
1142
+ w, h = rgba.size
1143
+ if w < 60 or h < 60:
1144
+ return clean
1145
+
1146
+ alpha = rgba.getchannel("A")
1147
+ min_a, max_a = alpha.getextrema()
1148
+ if min_a >= 245 or max_a < 128:
1149
+ return clean
1150
+
1151
+ ink_bytes = alpha.point(lambda v: 255 if v >= 128 else 0).tobytes()
1152
+ gray_bytes = rgba.convert("L").tobytes()
1153
+ row_counts = [ink_bytes[y * w : (y + 1) * w].count(255) for y in range(h)]
1154
+
1155
+ min_row_px = min(4, max(2, int(w * 0.003)))
1156
+ raw_bands: list[tuple[int, int]] = []
1157
+ y = 0
1158
+ while y < h:
1159
+ if row_counts[y] >= min_row_px:
1160
+ y0 = y
1161
+ while y < h and row_counts[y] >= min_row_px:
1162
+ y += 1
1163
+ y1 = y
1164
+ if raw_bands and (y0 - raw_bands[-1][1]) <= 2:
1165
+ raw_bands[-1] = (raw_bands[-1][0], y1)
1166
+ else:
1167
+ raw_bands.append((y0, y1))
1168
+ else:
1169
+ y += 1
1170
+
1171
+ bands = [
1172
+ (y0, y1)
1173
+ for (y0, y1) in raw_bands
1174
+ if (y1 - y0) >= 3 or sum(row_counts[y0:y1]) >= 12
1175
+ ]
1176
+ if len(bands) < 2:
1177
+ return clean
1178
+
1179
+ oy0, oy1 = bands[0][0], bands[-1][1]
1180
+ if (oy1 - oy0) < 40:
1181
+ return clean
1182
+
1183
+ band_inks = [sum(row_counts[y0:y1]) for y0, y1 in bands]
1184
+ dom_idx = max(range(len(bands)), key=lambda i: (bands[i][1] - bands[i][0], band_inks[i]))
1185
+
1186
+ max_band_h = min(52, int(h * 0.22))
1187
+ flagged_edges: list[str] = []
1188
+ flagged_bands: list[dict[str, Any]] = []
1189
+
1190
+ candidates: list[tuple[str, tuple[int, int], int, int, int, int]] = []
1191
+ if dom_idx > 0:
1192
+ candidates.append(
1193
+ (
1194
+ "top",
1195
+ bands[0],
1196
+ bands[1][0] - bands[0][1],
1197
+ oy1 - bands[1][0],
1198
+ band_inks[0],
1199
+ sum(band_inks[1:]),
1200
+ )
1201
+ )
1202
+ if dom_idx < len(bands) - 1:
1203
+ candidates.append(
1204
+ (
1205
+ "bottom",
1206
+ bands[-1],
1207
+ bands[-1][0] - bands[-2][1],
1208
+ bands[-2][1] - oy0,
1209
+ band_inks[-1],
1210
+ sum(band_inks[:-1]),
1211
+ )
1212
+ )
1213
+
1214
+ for edge_name, (by0, by1), gap_px, rest_h, band_ink, rest_ink in candidates:
1215
+ bh = by1 - by0
1216
+ if gap_px < 3 or bh < 7 or bh > max_band_h:
1217
+ continue
1218
+ if edge_name == "top" and (by0 > int(h * 0.16) or by1 > int(h * 0.28)):
1219
+ continue
1220
+ if edge_name == "bottom" and ((h - by1) > int(h * 0.16) or (h - by0) > int(h * 0.28)):
1221
+ continue
1222
+ if rest_h < max(32, int(bh * 1.8)) or rest_ink < max(160, int(band_ink * 1.3)):
1223
+ continue
1224
+
1225
+ # Segment glyph-like components via column projection within the detached band
1226
+ comps: list[tuple[int, int, int, int, int]] = []
1227
+ in_run = False
1228
+ cx0 = 0
1229
+ ymin = by1
1230
+ ymax = by0
1231
+ cnt = 0
1232
+ for x in range(w):
1233
+ first_y = -1
1234
+ last_y = -1
1235
+ col_cnt = 0
1236
+ for yy in range(by0, by1):
1237
+ if ink_bytes[yy * w + x] == 255:
1238
+ if first_y < 0:
1239
+ first_y = yy
1240
+ last_y = yy
1241
+ col_cnt += 1
1242
+ if col_cnt:
1243
+ if not in_run:
1244
+ in_run = True
1245
+ cx0 = x
1246
+ ymin = first_y
1247
+ ymax = last_y
1248
+ cnt = col_cnt
1249
+ else:
1250
+ if first_y < ymin:
1251
+ ymin = first_y
1252
+ if last_y > ymax:
1253
+ ymax = last_y
1254
+ cnt += col_cnt
1255
+ elif in_run:
1256
+ comps.append((cx0, x, ymin, ymax + 1, cnt))
1257
+ in_run = False
1258
+ if in_run:
1259
+ comps.append((cx0, w, ymin, ymax + 1, cnt))
1260
+
1261
+ glyphs: list[dict[str, Any]] = []
1262
+ for x0, x1, gy0, gy1, px_cnt in comps:
1263
+ cw = x1 - x0
1264
+ ch = gy1 - gy0
1265
+ if not (7 <= ch <= 44):
1266
+ continue
1267
+ if cw < 2 or cw > max(48, int(ch * 3.0)):
1268
+ continue
1269
+ if (cw / float(ch)) > 3.2:
1270
+ continue
1271
+ area = cw * ch
1272
+ if px_cnt < max(8, int(area * 0.10)):
1273
+ continue
1274
+ # Count rows/cols with >=2 disjoint ink runs (holes, concavities, or multi-strokes).
1275
+ # When exterior flood-fill (e.g. remove-bg blend) leaves trapped paper inside closed
1276
+ # glyph counters ('O', 'D', '日', '田', '国'), recover internal counters via luminance
1277
+ # contrast against the component's outer stroke ink.
1278
+ border_lums: list[int] = []
1279
+ comp_min_lum = 255
1280
+ comp_max_lum = 0
1281
+ for yy in range(gy0, gy1):
1282
+ row_off = yy * w
1283
+ for xx in range(x0, x1):
1284
+ idx_p = row_off + xx
1285
+ if ink_bytes[idx_p] != 255:
1286
+ continue
1287
+ lv = gray_bytes[idx_p]
1288
+ if lv < comp_min_lum:
1289
+ comp_min_lum = lv
1290
+ if lv > comp_max_lum:
1291
+ comp_max_lum = lv
1292
+ if (
1293
+ xx == x0
1294
+ or xx == x1 - 1
1295
+ or yy == gy0
1296
+ or yy == gy1 - 1
1297
+ or ink_bytes[idx_p - 1] == 0
1298
+ or ink_bytes[idx_p + 1] == 0
1299
+ or ink_bytes[idx_p - w] == 0
1300
+ or ink_bytes[idx_p + w] == 0
1301
+ ):
1302
+ border_lums.append(lv)
1303
+ use_lum_counter = (comp_max_lum - comp_min_lum) >= 70 and bool(border_lums)
1304
+ stroke_lum = int(median(border_lums)) if use_lum_counter else 0
1305
+
1306
+ def _is_stroke_px(idx_p: int) -> bool:
1307
+ if ink_bytes[idx_p] != 255:
1308
+ return False
1309
+ if use_lum_counter and abs(gray_bytes[idx_p] - stroke_lum) >= 55:
1310
+ return False
1311
+ return True
1312
+
1313
+ stroke_px_cnt = 0
1314
+ multi_h_rows = 0
1315
+ for yy in range(gy0, gy1):
1316
+ row_off = yy * w
1317
+ r_runs = 0
1318
+ prev_on = False
1319
+ for xx in range(x0, x1):
1320
+ on = _is_stroke_px(row_off + xx)
1321
+ if on:
1322
+ stroke_px_cnt += 1
1323
+ if not prev_on:
1324
+ r_runs += 1
1325
+ prev_on = on
1326
+ if r_runs >= 2:
1327
+ multi_h_rows += 1
1328
+ multi_v_cols = 0
1329
+ for xx in range(x0, x1):
1330
+ c_runs = 0
1331
+ prev_on = False
1332
+ for yy in range(gy0, gy1):
1333
+ on = _is_stroke_px(yy * w + xx)
1334
+ if on and not prev_on:
1335
+ c_runs += 1
1336
+ prev_on = on
1337
+ if c_runs >= 2:
1338
+ multi_v_cols += 1
1339
+ eff_fill = (stroke_px_cnt / float(area)) if use_lum_counter else (px_cnt / float(area))
1340
+ glyphs.append(
1341
+ {
1342
+ "x0": x0,
1343
+ "x1": x1,
1344
+ "y0": gy0,
1345
+ "y1": gy1,
1346
+ "w": cw,
1347
+ "h": ch,
1348
+ "px": px_cnt,
1349
+ "fill": eff_fill,
1350
+ "mid_y": (gy0 + gy1) * 0.5,
1351
+ "has_strokes": (multi_h_rows >= 2 or multi_v_cols >= 2),
1352
+ }
1353
+ )
1354
+
1355
+ if len(glyphs) < 3:
1356
+ continue
1357
+
1358
+ runs: list[list[dict[str, Any]]] = []
1359
+ for g in glyphs:
1360
+ if not runs:
1361
+ runs.append([g])
1362
+ continue
1363
+ prev = runs[-1][-1]
1364
+ gap_x = g["x0"] - prev["x1"]
1365
+ ref_h = max(prev["h"], g["h"])
1366
+ if gap_x <= max(18, int(ref_h * 1.45)):
1367
+ runs[-1].append(g)
1368
+ else:
1369
+ runs.append([g])
1370
+
1371
+ for run in runs:
1372
+ if len(run) < 3:
1373
+ continue
1374
+ med_h = float(median(g["h"] for g in run))
1375
+ if not (7.0 <= med_h <= 44.0):
1376
+ continue
1377
+ consistent = [g for g in run if 0.55 * med_h <= g["h"] <= 1.55 * med_h]
1378
+ if len(consistent) < 3:
1379
+ continue
1380
+ # Reject uniform wide solid horizontal dashed rules
1381
+ if all(g["w"] > g["h"] * 1.9 and g["fill"] > 0.88 for g in consistent):
1382
+ continue
1383
+ # Tighten inter-glyph spacing for 3-component runs so widely spaced decorative stars/dots don't pass
1384
+ gaps = [consistent[i + 1]["x0"] - consistent[i]["x1"] for i in range(len(consistent) - 1)]
1385
+ if len(consistent) == 3 and max(gaps) > max(14, int(med_h * 1.15)):
1386
+ continue
1387
+ # Require genuine multi-stroke / concave / hollow glyph structure (rejects solid circles, squares, diamonds, 4-point sparkles)
1388
+ complex_count = sum(1 for g in consistent if g["has_strokes"])
1389
+ med_fill = float(median(g["fill"] for g in consistent))
1390
+ if complex_count < max(2, math.ceil(len(consistent) * 0.20)):
1391
+ continue
1392
+ if med_fill >= 0.72 and complex_count < math.ceil(len(consistent) * 0.50):
1393
+ continue
1394
+ mids = [g["mid_y"] for g in consistent]
1395
+ if (max(mids) - min(mids)) > max(10.0, med_h * 0.75):
1396
+ continue
1397
+ span_w = consistent[-1]["x1"] - consistent[0]["x0"]
1398
+ if span_w < max(28.0, med_h * 1.6):
1399
+ continue
1400
+ run_ink = sum(g["px"] for g in consistent)
1401
+ if band_ink > 0 and (run_ink / float(band_ink)) < 0.25:
1402
+ continue
1403
+ flagged_edges.append(edge_name)
1404
+ flagged_bands.append(
1405
+ {
1406
+ "edge": edge_name,
1407
+ "y0": by0,
1408
+ "y1": by1,
1409
+ "band_height": bh,
1410
+ "gap_px": gap_px,
1411
+ "glyph_count": len(consistent),
1412
+ "median_glyph_h": round(med_h, 1),
1413
+ "span_px": span_w,
1414
+ }
1415
+ )
1416
+ break
1417
+
1418
+ return {
1419
+ "has_residual_text": bool(flagged_edges),
1420
+ "edges": flagged_edges,
1421
+ "bands": flagged_bands,
1422
+ }
1423
+
1424
+
1425
+ def _parse_hex_rgb(raw: str) -> tuple[int, int, int]:
1426
+ """Parse '#RGB' or '#RRGGBB' (with or without leading '#') into an (R, G, B) tuple."""
1427
+ s = str(raw or "").strip().lstrip("#")
1428
+ if len(s) == 3 and all(c in "0123456789abcdefABCDEF" for c in s):
1429
+ s = "".join(c * 2 for c in s)
1430
+ if len(s) != 6 or not all(c in "0123456789abcdefABCDEF" for c in s):
1431
+ raise ValueError(f"Invalid --matte-bg hex color {raw!r}; expected '#RRGGBB' or '#RGB'")
1432
+ return (int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
1433
+
1434
+
1435
+ def crop_asset(
1436
+ src_path: Path | str,
1437
+ bbox: str | list[float] | tuple[float, ...],
1438
+ out_path: Path | str,
1439
+ *,
1440
+ coord_space: str = "1920x1080",
1441
+ ratio: str | None = None,
1442
+ mask: str = "rect",
1443
+ remove_bg: str = "none",
1444
+ fade_edge: str | None = None,
1445
+ matte_bg: str | None = None,
1446
+ output_format: str = "auto",
1447
+ quality: int = 88,
1448
+ ) -> dict[str, Any]:
1449
+ """Crop a region from a reference image and save as PNG, WebP, or opaque JPEG with optional mask/bg-removal/edge-fade/matte."""
1450
+ src_abs = Path(src_path).resolve()
1451
+ if not src_abs.is_file():
1452
+ raise FileNotFoundError(f"Source image not found: {src_abs}")
1453
+
1454
+ bbox_tuple = parse_bbox(bbox)
1455
+ out_abs = Path(out_path).resolve()
1456
+ fmt_tok = (output_format or "auto").strip().lower()
1457
+ if fmt_tok == "jpeg":
1458
+ fmt_tok = "jpg"
1459
+ if fmt_tok not in ("auto", "png", "webp", "jpg"):
1460
+ raise ValueError(f"Unsupported output format: {output_format!r} (expected auto|png|webp|jpg)")
1461
+ ext_low = out_abs.suffix.lower()
1462
+ use_webp = fmt_tok == "webp" or (fmt_tok == "auto" and ext_low == ".webp")
1463
+ use_jpg = fmt_tok == "jpg" or (fmt_tok == "auto" and ext_low in (".jpg", ".jpeg"))
1464
+ if use_webp and ext_low != ".webp":
1465
+ out_abs = out_abs.with_suffix(".webp")
1466
+ elif use_jpg and ext_low not in (".jpg", ".jpeg"):
1467
+ out_abs = out_abs.with_suffix(".jpg")
1468
+ out_abs.parent.mkdir(parents=True, exist_ok=True)
1469
+
1470
+ matte_rgb = _parse_hex_rgb(matte_bg) if (matte_bg and str(matte_bg).strip()) else None
1471
+ matte_hex = f"#{matte_rgb[0]:02X}{matte_rgb[1]:02X}{matte_rgb[2]:02X}" if matte_rgb is not None else None
1472
+
1473
+ bg_mode = (remove_bg or "none").strip().lower()
1474
+ needs_alpha = (
1475
+ (mask or "rect").strip().lower() != "rect"
1476
+ or bg_mode not in ("none", "blend")
1477
+ or bool(fade_edge and str(fade_edge).strip())
1478
+ )
1479
+
1480
+ with Image.open(src_abs) as raw:
1481
+ src_w, src_h = raw.size
1482
+ src_has_alpha = ("A" in raw.getbands()) or ("transparency" in raw.info)
1483
+ crop_px, r_scale = _resolve_crop_box(src_w, src_h, bbox_tuple, coord_space, ratio=ratio)
1484
+ original_px = crop_px
1485
+ blend_skip_reason: str | None = None
1486
+ if bg_mode == "blend":
1487
+ cropped, crop_px, blend_skip_reason = _blend_crop_with_meta(raw, crop_px)
1488
+ if src_has_alpha and crop_px != original_px:
1489
+ original_alpha = raw.crop(crop_px).convert("RGBA").getchannel("A")
1490
+ cropped.putalpha(ImageChops.multiply(cropped.getchannel("A"), original_alpha))
1491
+ else:
1492
+ cropped = raw.crop(crop_px)
1493
+ work = cropped.convert("RGBA") if (needs_alpha or src_has_alpha or cropped.mode == "RGBA") else cropped.convert("RGB")
1494
+
1495
+ blend_fallback: str | None = None
1496
+ applied_fade_edge: str | None = None
1497
+ if work.mode == "RGBA":
1498
+ if bg_mode not in ("none", "blend"):
1499
+ work = _remove_outer_bg(work, remove_bg)
1500
+ if (mask or "rect").strip().lower() != "rect":
1501
+ work = _apply_shape_mask(work, mask, r_scale)
1502
+ if fade_edge and str(fade_edge).strip():
1503
+ work = _apply_fade_edges(work, fade_edge)
1504
+ applied_fade_edge = str(fade_edge).strip()
1505
+
1506
+ has_alpha = False
1507
+ if work.mode == "RGBA":
1508
+ min_a, _ = work.getchannel("A").getextrema()
1509
+ has_alpha = bool(min_a < 255)
1510
+
1511
+ # Automatic soft fade-edge fallback when blend background removal could not separate a
1512
+ # gradient/textured background (never applied to hard-edged photos/screenshots or when mask/fade_edge was explicit).
1513
+ if (
1514
+ bg_mode == "blend"
1515
+ and not has_alpha
1516
+ and (mask or "rect").strip().lower() == "rect"
1517
+ and not (fade_edge and str(fade_edge).strip())
1518
+ ):
1519
+ if blend_skip_reason == "hard_rect":
1520
+ blend_fallback = "kept_hard_rect"
1521
+ elif blend_skip_reason == "non_uniform_bg":
1522
+ x0, y0, x1, y1 = crop_px
1523
+ auto_sides: list[str] = []
1524
+ if x0 > 4:
1525
+ auto_sides.append("left:10")
1526
+ if y0 > 4:
1527
+ auto_sides.append("top:10")
1528
+ if x1 < src_w - 4:
1529
+ auto_sides.append("right:10")
1530
+ if y1 < src_h - 4:
1531
+ auto_sides.append("bottom:10")
1532
+ if auto_sides:
1533
+ auto_fade = ",".join(auto_sides)
1534
+ work = _apply_fade_edges(work.convert("RGBA"), auto_fade)
1535
+ min_a, _ = work.getchannel("A").getextrema()
1536
+ has_alpha = bool(min_a < 255)
1537
+ blend_fallback = "fade_edge"
1538
+ applied_fade_edge = auto_fade
1539
+
1540
+ # Optional solid canvas matte flatten (eliminates alpha halos on uniform solid slide backgrounds)
1541
+ if matte_rgb is not None:
1542
+ if work.mode == "RGBA":
1543
+ bg_canvas = Image.new("RGBA", work.size, (*matte_rgb, 255))
1544
+ work = Image.alpha_composite(bg_canvas, work).convert("RGB")
1545
+ else:
1546
+ work = work.convert("RGB")
1547
+ has_alpha = False
1548
+
1549
+ if use_jpg:
1550
+ if has_alpha:
1551
+ raise ValueError(
1552
+ "JPEG output does not support alpha transparency; pass --matte-bg '#RRGGBB' to flatten onto a canvas color, or use .png/.webp."
1553
+ )
1554
+ q = max(40, min(100, int(quality)))
1555
+ work.convert("RGB").save(out_abs, format="JPEG", quality=q, optimize=True)
1556
+ elif use_webp:
1557
+ q = max(40, min(100, int(quality)))
1558
+ work.save(out_abs, format="WEBP", quality=q, method=4)
1559
+ elif bg_mode == "none" and not needs_alpha and (work.width * work.height) <= 250_000:
1560
+ work.save(out_abs, format="PNG", optimize=True)
1561
+ else:
1562
+ work.save(out_abs, format="PNG", compress_level=1)
1563
+ bleed_edges = (
1564
+ _detect_bleed_edges(work, crop_px, src_w, src_h)
1565
+ if has_alpha and (mask or "rect").strip().lower() == "rect"
1566
+ else []
1567
+ )
1568
+ residual_text = (
1569
+ detect_residual_crop_text(work)
1570
+ if has_alpha
1571
+ else {"has_residual_text": False, "edges": [], "bands": []}
1572
+ )
1573
+ result = {
1574
+ "ok": True,
1575
+ "path": str(out_abs),
1576
+ "size": [work.width, work.height],
1577
+ "mode": work.mode,
1578
+ "has_alpha": has_alpha,
1579
+ "src_size": [src_w, src_h],
1580
+ "crop_px": list(crop_px),
1581
+ }
1582
+ if matte_hex is not None:
1583
+ result["matte_bg"] = matte_hex
1584
+ if applied_fade_edge and bg_mode != "blend":
1585
+ result["applied_fade_edge"] = applied_fade_edge
1586
+ if bleed_edges:
1587
+ result["bleed_edges"] = bleed_edges
1588
+ result["anchor_css"] = " ".join(f"{s}: 0;" for s in bleed_edges)
1589
+ if residual_text["has_residual_text"]:
1590
+ result["residual_text_edges"] = residual_text["edges"]
1591
+ edge_str = "/".join(residual_text["edges"])
1592
+ result["residual_text_warning"] = (
1593
+ f"Detached glyph-like text band detected near {edge_str} edge; "
1594
+ "tighten --bbox away from neighboring slide text or re-extract cleanly."
1595
+ )
1596
+ if bg_mode == "blend":
1597
+ result["grown_px"] = dict(zip(_SIDES, (abs(a - b) for a, b in zip(crop_px, original_px))))
1598
+ if blend_fallback:
1599
+ result["blend_fallback"] = blend_fallback
1600
+ if applied_fade_edge:
1601
+ result["applied_fade_edge"] = applied_fade_edge
1602
+ return result
1603
+
1604
+
1605
+ def _configure_utf8_stdio() -> None:
1606
+ for stream in (sys.stdout, sys.stderr):
1607
+ if stream is not None:
1608
+ try:
1609
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
1610
+ stream.reconfigure(encoding="utf-8", errors="replace")
1611
+ except Exception:
1612
+ pass
1613
+
1614
+
1615
+ def main() -> int:
1616
+ _configure_utf8_stdio()
1617
+ parser = argparse.ArgumentParser(
1618
+ description="Deterministic zero-credit Pillow cropper for extracting visual assets from reference slides."
1619
+ )
1620
+ parser.add_argument("--src", required=True, type=Path, help="Input image path (e.g. assets/reference/s4.png)")
1621
+ parser.add_argument("--bbox", required=True, type=str, help="Crop bounding box 'x,y,w,h'")
1622
+ parser.add_argument(
1623
+ "--coord-space",
1624
+ default="1920x1080",
1625
+ choices=_COORD_SPACE_CHOICES,
1626
+ help="Coordinate system for --bbox (default: 1920x1080; also accepts 1080x1440, 1080x1920, 1440x1440, 16:9, 3:4, 9:16, 1:1, canvas, native, pct)",
1627
+ )
1628
+ parser.add_argument(
1629
+ "--ratio",
1630
+ "--aspect-ratio",
1631
+ dest="ratio",
1632
+ default=None,
1633
+ type=str,
1634
+ help="Optional canvas aspect ratio override (16:9, 3:4, 9:16, 1:1)",
1635
+ )
1636
+ parser.add_argument("--out", required=True, type=Path, help="Output PNG path")
1637
+ parser.add_argument(
1638
+ "--mask",
1639
+ default="rect",
1640
+ type=str,
1641
+ help="Alpha shape mask: rect | circle | pill | rounded:R (default: rect)",
1642
+ )
1643
+ parser.add_argument(
1644
+ "--remove-bg",
1645
+ default="none",
1646
+ choices=["none", "auto", "white", "black", "blend"],
1647
+ help="Remove a neutral border or blend the surrounding page into transparency (default: none)",
1648
+ )
1649
+ parser.add_argument(
1650
+ "--fade-edge",
1651
+ default=None,
1652
+ type=str,
1653
+ help="Optional comma-separated edge alpha fade, e.g. 'bottom:30' or 'bottom:28,left:15'",
1654
+ )
1655
+ parser.add_argument(
1656
+ "--matte-bg",
1657
+ default=None,
1658
+ type=str,
1659
+ help="Optional solid canvas hex color (e.g. '#F5F7FA') to composite alpha onto, producing an opaque RGB image without Keynote/PowerPoint alpha halos",
1660
+ )
1661
+ parser.add_argument(
1662
+ "--format",
1663
+ dest="output_format",
1664
+ default="auto",
1665
+ choices=["auto", "png", "webp", "jpg", "jpeg"],
1666
+ help="Output image format: auto (follows --out extension), png, webp, or jpg (default: auto)",
1667
+ )
1668
+ parser.add_argument(
1669
+ "--quality",
1670
+ default=88,
1671
+ type=int,
1672
+ help="Encoding quality 40-100 when saving .webp or .jpg (default: 88)",
1673
+ )
1674
+ parser.add_argument("--json", action="store_true", help="Print JSON result to stdout")
1675
+ args = parser.parse_args()
1676
+
1677
+ try:
1678
+ res = crop_asset(
1679
+ src_path=args.src,
1680
+ bbox=args.bbox,
1681
+ out_path=args.out,
1682
+ coord_space=args.coord_space,
1683
+ ratio=args.ratio,
1684
+ mask=args.mask,
1685
+ remove_bg=args.remove_bg,
1686
+ fade_edge=args.fade_edge,
1687
+ matte_bg=args.matte_bg,
1688
+ output_format=args.output_format,
1689
+ quality=args.quality,
1690
+ )
1691
+ except Exception as exc:
1692
+ if args.json:
1693
+ print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False))
1694
+ else:
1695
+ print(f"Error: {exc}", file=sys.stderr)
1696
+ return 1
1697
+
1698
+ if args.json:
1699
+ print(json.dumps(res, ensure_ascii=False))
1700
+ else:
1701
+ print(
1702
+ f"crop_asset: ok=True size={res['size'][0]}x{res['size'][1]} "
1703
+ f"mode={res['mode']} has_alpha={res['has_alpha']} out={res['path']}"
1704
+ )
1705
+ return 0
1706
+
1707
+
1708
+ if __name__ == "__main__":
1709
+ raise SystemExit(main())