@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,283 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import os
5
+ import importlib.util
6
+ import sys
7
+ import stat
8
+ from pathlib import Path
9
+
10
+
11
+ DEFAULT_CONFIG_HOME = "~/.editppt"
12
+ CODEX_PPT_RUNTIME_HOME = "~/.codex-ppt-skill"
13
+ ENV_FIELDS = ("OPENAI_API_KEY", "OPENAI_BASE_URL", "IMAGE_TO_EDITABLE_PPT_IMAGE_MODEL", "PADDLE_OCR_TOKEN")
14
+ PADDLE_TOKEN_APPLY_URL = "https://aistudio.baidu.com/account/accessToken"
15
+ CODEX_PPT_ENV_MAP = {
16
+ "OPENAI_API_KEY": "OPENAI_API_KEY",
17
+ "OPENAI_BASE_URL": "OPENAI_BASE_URL",
18
+ "CODEX_PPT_IMAGE_MODEL": "IMAGE_TO_EDITABLE_PPT_IMAGE_MODEL",
19
+ }
20
+
21
+
22
+ def cli_reinstall_hint():
23
+ return "`pipx install --force --editable <path-to-image-to-editable-ppt>/cli`"
24
+
25
+
26
+ def runtime_home():
27
+ return Path(os.getenv("EDITPPT_CONFIG_HOME", DEFAULT_CONFIG_HOME)).expanduser()
28
+
29
+
30
+ def config_path(home=None):
31
+ return (home or runtime_home()) / "config.yaml"
32
+
33
+
34
+ def parse_env_file(path):
35
+ path = Path(path).expanduser()
36
+ if not path.exists():
37
+ return {}
38
+ values = {}
39
+ for raw in path.read_text(encoding="utf-8").splitlines():
40
+ line = raw.strip()
41
+ if not line or line.startswith("#") or "=" not in line:
42
+ continue
43
+ key, value = line.split("=", 1)
44
+ values[key.strip()] = value.strip().strip('"').strip("'")
45
+ return values
46
+
47
+
48
+ def read_config_file(path):
49
+ path = Path(path).expanduser()
50
+ if not path.exists():
51
+ return {}
52
+ try:
53
+ import yaml
54
+ except ImportError as exc:
55
+ raise SystemExit(
56
+ f"PyYAML is required to read editppt config. Reinstall with {cli_reinstall_hint()}."
57
+ ) from exc
58
+ with path.open("r", encoding="utf-8") as handle:
59
+ data = yaml.safe_load(handle) or {}
60
+ if not isinstance(data, dict):
61
+ raise SystemExit(f"Invalid config file: {path}")
62
+ return data
63
+
64
+
65
+ def write_config_file(path, values):
66
+ path = Path(path)
67
+ path.parent.mkdir(parents=True, exist_ok=True)
68
+ try:
69
+ import yaml
70
+ except ImportError as exc:
71
+ raise SystemExit(
72
+ f"PyYAML is required to write editppt config. Reinstall with {cli_reinstall_hint()}."
73
+ ) from exc
74
+ data = {key: values[key] for key in ENV_FIELDS if values.get(key)}
75
+ try:
76
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, stat.S_IRUSR | stat.S_IWUSR)
77
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
78
+ yaml.safe_dump(data, handle, allow_unicode=True, sort_keys=True)
79
+ except OSError:
80
+ with path.open("w", encoding="utf-8") as handle:
81
+ yaml.safe_dump(data, handle, allow_unicode=True, sort_keys=True)
82
+ try:
83
+ path.chmod(stat.S_IRUSR | stat.S_IWUSR)
84
+ except OSError:
85
+ pass
86
+
87
+
88
+ def mask_secret(value):
89
+ if not value:
90
+ return ""
91
+ if len(value) <= 8:
92
+ return "****"
93
+ return f"{value[:4]}...{value[-4:]}"
94
+
95
+
96
+ def import_codex_ppt_values(values):
97
+ codex_ppt_env = Path(os.getenv("CODEX_PPT_HOME", CODEX_PPT_RUNTIME_HOME)).expanduser() / ".env"
98
+ source = parse_env_file(codex_ppt_env)
99
+ changed = False
100
+ for source_key, target_key in CODEX_PPT_ENV_MAP.items():
101
+ if not values.get(target_key) and source.get(source_key):
102
+ values[target_key] = source[source_key]
103
+ changed = True
104
+ return changed, codex_ppt_env
105
+
106
+
107
+ def config(args):
108
+ home = runtime_home()
109
+ values = read_config_file(config_path(home))
110
+ before = dict(values)
111
+ imported = False
112
+ import_path = None
113
+ if args.import_codex_ppt:
114
+ imported, import_path = import_codex_ppt_values(values)
115
+ if (args.clear_base_url or (args.base_url is not None and
116
+ args.base_url.strip().rstrip("/") != str(values.get("OPENAI_BASE_URL", "")).rstrip("/"))):
117
+ values.pop("OPENAI_API_KEY", None)
118
+ if args.api_key:
119
+ values["OPENAI_API_KEY"] = args.api_key
120
+ if args.base_url is not None:
121
+ values["OPENAI_BASE_URL"] = args.base_url.strip()
122
+ if args.clear_base_url:
123
+ values.pop("OPENAI_BASE_URL", None)
124
+ if args.model is not None:
125
+ values["IMAGE_TO_EDITABLE_PPT_IMAGE_MODEL"] = args.model.strip()
126
+ if getattr(args, "paddle_ocr_token", None):
127
+ values["PADDLE_OCR_TOKEN"] = args.paddle_ocr_token.strip()
128
+ changed = sorted(key for key in ENV_FIELDS if before.get(key) != values.get(key))
129
+ if changed or not config_path(home).exists():
130
+ write_config_file(config_path(home), values)
131
+ state = "updated" if before else "created"
132
+ else:
133
+ state = "unchanged"
134
+ print(f"config={state} path={config_path(home)}")
135
+ if import_path:
136
+ print(f"import_codex_ppt={'yes' if imported else 'no'} source={import_path}")
137
+ if changed:
138
+ print(f"changed={', '.join(changed)}")
139
+ else:
140
+ print("changed=<none>")
141
+ for key in ENV_FIELDS:
142
+ value = values.get(key, "")
143
+ if key in ("OPENAI_API_KEY", "PADDLE_OCR_TOKEN"):
144
+ value = mask_secret(value)
145
+ print(f"{key}={value or '<unset>'}")
146
+ return 0
147
+
148
+
149
+ def current_python_has_module(module):
150
+ return importlib.util.find_spec(module) is not None
151
+
152
+
153
+ def collect_status(check_api=False):
154
+ home = runtime_home()
155
+ values = read_config_file(config_path(home))
156
+ config_values = dict(values)
157
+ for key in ENV_FIELDS:
158
+ if os.getenv(key):
159
+ values[key] = os.environ[key]
160
+ dependencies = {
161
+ module: current_python_has_module(module)
162
+ for module in ("fitz", "PIL", "openai", "yaml", "numpy", "requests")
163
+ }
164
+ from image_gen import read_channel
165
+ try:
166
+ url, model, api_key = read_channel()
167
+ except (OSError, ValueError, TypeError):
168
+ url, model, api_key = "", "", ""
169
+ cli_fallback_ready = bool(url and model)
170
+ ok = all(dependencies.values()) and (cli_fallback_ready if check_api else True)
171
+ return {
172
+ "ok": ok,
173
+ "config_home": str(home),
174
+ "config_file": str(config_path(home)),
175
+ "config_exists": config_path(home).exists(),
176
+ "cli_python": sys.executable,
177
+ "dependencies": dependencies,
178
+ "config_keys": sorted(key for key in ENV_FIELDS if config_values.get(key)),
179
+ "image_backend": {
180
+ "ready": cli_fallback_ready, "selection": "custom" if cli_fallback_ready else "missing",
181
+ "base_url": url, "model": model, "has_key": bool(api_key),
182
+ },
183
+ "text_hints": {
184
+ "selection": "paddleocr-vl" if values.get("PADDLE_OCR_TOKEN") else "builtin-ink",
185
+ "paddle_token": "set" if values.get("PADDLE_OCR_TOKEN") else "unset",
186
+ "apply_url": PADDLE_TOKEN_APPLY_URL,
187
+ "configure_command": "editppt config --paddle-ocr-token <token>",
188
+ },
189
+ "network_approval": {
190
+ "commands": [
191
+ "editppt prepare / editppt run hints when PADDLE_OCR_TOKEN is set",
192
+ "editppt image generate/edit",
193
+ ],
194
+ "justification": (
195
+ "User-requested image-to-editable-ppt conversion; uploads are limited to "
196
+ "task-local page images, prompts, masks, and references required by OCR/image backends."
197
+ ),
198
+ "paddle_rejection_guidance": (
199
+ "If PaddleOCR approval is rejected, ask the user to authorize OCR explicitly; "
200
+ "explain that OCR corrects text boxes, font sizes, and size groups so reconstructed "
201
+ "PPT text sizing stays stable."
202
+ ),
203
+ },
204
+ "next": "no action needed" if ok else (
205
+ "configure the image API in Oil Slide → 生图设置"
206
+ if check_api and not cli_fallback_ready
207
+ else cli_reinstall_hint().strip("`")
208
+ ),
209
+ }
210
+
211
+
212
+ def doctor(args):
213
+ status = collect_status(check_api=args.check_api)
214
+ if args.json:
215
+ print(json.dumps(status, ensure_ascii=False, indent=2))
216
+ return 0 if status["ok"] else 1
217
+
218
+ image_backend = status["image_backend"]
219
+ print(f"Image channel: {image_backend['selection']}, model={image_backend['model']}")
220
+ hints = status["text_hints"]
221
+ print(f"text hints={hints['selection']} (PADDLE_OCR_TOKEN {hints['paddle_token']})")
222
+ print(
223
+ "network approval: in restricted agents, request approval up front for OCR/image backend "
224
+ "commands; conversion uploads are limited to task-local page images, prompts, masks, "
225
+ "and references."
226
+ )
227
+ print(
228
+ "paddle approval rejection: ask the user to authorize OCR and explain that it corrects "
229
+ "text boxes, font sizes, and size groups so reconstructed PPT text sizing stays stable."
230
+ )
231
+ if hints["paddle_token"] == "unset":
232
+ print(
233
+ "text hints: ASK THE USER once — a free PaddleOCR token makes text hints content-aware "
234
+ "(recognized text + cleaner blocks, noticeably better text fidelity). The free personal "
235
+ "quota is currently more than enough for this skill, so applying is risk-free with no "
236
+ "extra cost. They can apply at "
237
+ "{url} and you run `{cmd}`; or they can choose to continue with the offline detector. "
238
+ "Wait for their choice before reconstructing pages, then do not ask again.".format(
239
+ url=hints["apply_url"], cmd=hints["configure_command"]
240
+ )
241
+ )
242
+ for module, module_ok in status["dependencies"].items():
243
+ print(f"python import {module}: {'ok' if module_ok else 'missing'}")
244
+ if not all(status["dependencies"].values()):
245
+ print(f"dependency install hint: run {cli_reinstall_hint()}.")
246
+ if args.check_api:
247
+ if image_backend["ready"]:
248
+ print("CLI fallback image backend check: configured (network probe not performed by doctor)")
249
+ else:
250
+ print("CLI fallback image backend check: configure the image channel in Oil Slide → 生图设置")
251
+ print(f"next: {status['next']}")
252
+ return 0 if status["ok"] else 1
253
+
254
+
255
+ def main():
256
+ parser = argparse.ArgumentParser(
257
+ prog="editppt",
258
+ description="Manage editppt API fallback configuration",
259
+ )
260
+ sub = parser.add_subparsers(required=True)
261
+ doc = sub.add_parser("doctor", help="Check Python dependencies and fallback config")
262
+ doc.add_argument(
263
+ "--check-api",
264
+ action="store_true",
265
+ help="Require an explicit Images API endpoint and model.",
266
+ )
267
+ doc.add_argument("--json", action="store_true", help="Print machine-readable JSON.")
268
+ doc.add_argument("--timeout", type=int, default=30, help="Reserved timeout value for future network probes.")
269
+ doc.set_defaults(func=doctor)
270
+ cfg = sub.add_parser("config", help="Write or update ~/.editppt/config.yaml")
271
+ cfg.add_argument("--api-key", help="OpenAI or OpenAI-compatible API key to store.")
272
+ cfg.add_argument("--base-url", help="OpenAI-compatible base URL, for example https://api.openai.com/v1.")
273
+ cfg.add_argument("--clear-base-url", action="store_true", help="Remove OPENAI_BASE_URL from the config file.")
274
+ cfg.add_argument("--model", help="Default image model for API fallback.")
275
+ cfg.add_argument("--paddle-ocr-token", help=f"PaddleOCR-VL token for content-aware text hints. Apply at {PADDLE_TOKEN_APPLY_URL}.")
276
+ cfg.add_argument("--import-codex-ppt", action="store_true", help="Import compatible values from ~/.codex-ppt-skill/.env when present.")
277
+ cfg.set_defaults(func=config)
278
+ args = parser.parse_args()
279
+ raise SystemExit(args.func(args))
280
+
281
+
282
+ if __name__ == "__main__":
283
+ main()
@@ -0,0 +1,323 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from PIL import Image, ImageDraw, ImageFilter
7
+
8
+
9
+ def parse_names(value):
10
+ if not value:
11
+ return []
12
+ return [item.strip() for item in value.split(",") if item.strip()]
13
+
14
+
15
+ NEIGHBORS = {
16
+ 4: ((1, 0), (-1, 0), (0, 1), (0, -1)),
17
+ 8: ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)),
18
+ }
19
+
20
+ # Only disregard a few nearly invisible pixels outside all ownership regions.
21
+ # Never threshold pixels within a region: detached details belong to the object.
22
+ MAX_RESIDUE_PIXELS = 4
23
+ MAX_RESIDUE_ALPHA = 8
24
+
25
+
26
+ def foreground_mask(alpha, threshold, close_radius):
27
+ mask = alpha.point(lambda p: 255 if p > threshold else 0, mode="L")
28
+ if close_radius <= 0:
29
+ return mask
30
+ size = close_radius * 2 + 1
31
+ return mask.filter(ImageFilter.MaxFilter(size)).filter(ImageFilter.MinFilter(size))
32
+
33
+
34
+ def component_boxes(mask, min_area, connectivity):
35
+ width, height = mask.size
36
+ pixels = mask.load()
37
+ seen = bytearray(width * height)
38
+ components = []
39
+ neighbors = NEIGHBORS[connectivity]
40
+
41
+ for y in range(height):
42
+ for x in range(width):
43
+ idx = y * width + x
44
+ if seen[idx] or pixels[x, y] == 0:
45
+ continue
46
+
47
+ stack = [(x, y)]
48
+ seen[idx] = 1
49
+ min_x = max_x = x
50
+ min_y = max_y = y
51
+ area = 0
52
+
53
+ while stack:
54
+ cx, cy = stack.pop()
55
+ area += 1
56
+ min_x = min(min_x, cx)
57
+ max_x = max(max_x, cx)
58
+ min_y = min(min_y, cy)
59
+ max_y = max(max_y, cy)
60
+
61
+ for dx, dy in neighbors:
62
+ nx = cx + dx
63
+ ny = cy + dy
64
+ if 0 <= nx < width and 0 <= ny < height:
65
+ nidx = ny * width + nx
66
+ if not seen[nidx] and pixels[nx, ny] != 0:
67
+ seen[nidx] = 1
68
+ stack.append((nx, ny))
69
+
70
+ if area >= min_area:
71
+ components.append({"area": area, "box": [min_x, min_y, max_x + 1, max_y + 1]})
72
+
73
+ return components
74
+
75
+
76
+ def gap_between(a, b):
77
+ ax1, ay1, ax2, ay2 = a
78
+ bx1, by1, bx2, by2 = b
79
+ dx = max(0, max(ax1, bx1) - min(ax2, bx2))
80
+ dy = max(0, max(ay1, by1) - min(ay2, by2))
81
+ return max(dx, dy)
82
+
83
+
84
+ def union_box(a, b):
85
+ return [
86
+ min(a[0], b[0]),
87
+ min(a[1], b[1]),
88
+ max(a[2], b[2]),
89
+ max(a[3], b[3]),
90
+ ]
91
+
92
+
93
+ def box_area(box):
94
+ return max(1, box[2] - box[0]) * max(1, box[3] - box[1])
95
+
96
+
97
+ def should_merge(a, b, max_gap, max_union_growth):
98
+ if gap_between(a["box"], b["box"]) > max_gap:
99
+ return False
100
+ union = union_box(a["box"], b["box"])
101
+ separate_area = box_area(a["box"]) + box_area(b["box"])
102
+ return box_area(union) / max(1, separate_area) <= max_union_growth
103
+
104
+
105
+ def merge_fragments(components, max_gap, max_union_growth):
106
+ if max_gap <= 0:
107
+ return components
108
+ merged = [dict(component, merged_count=1) for component in components]
109
+ changed = True
110
+ while changed:
111
+ changed = False
112
+ for i in range(len(merged)):
113
+ for j in range(i + 1, len(merged)):
114
+ if not should_merge(merged[i], merged[j], max_gap, max_union_growth):
115
+ continue
116
+ merged[i] = {
117
+ "area": merged[i]["area"] + merged[j]["area"],
118
+ "box": union_box(merged[i]["box"], merged[j]["box"]),
119
+ "merged_count": merged[i]["merged_count"] + merged[j]["merged_count"],
120
+ }
121
+ del merged[j]
122
+ changed = True
123
+ break
124
+ if changed:
125
+ break
126
+ return merged
127
+
128
+
129
+ def sort_components(components, mode):
130
+ if mode == "area":
131
+ return sorted(components, key=lambda item: item["area"], reverse=True)
132
+ if mode == "y":
133
+ return sorted(components, key=lambda item: (item["box"][1], item["box"][0]))
134
+ return sorted(components, key=lambda item: (item["box"][0], item["box"][1]))
135
+
136
+
137
+ def extract_component_asset(image, box, pad, square, region_box=None):
138
+ width, height = image.size
139
+ left, top, right, bottom = box
140
+ bounds = region_box or [0, 0, width, height]
141
+ left = max(bounds[0], left - pad)
142
+ top = max(bounds[1], top - pad)
143
+ right = min(bounds[2], right + pad)
144
+ bottom = min(bounds[3], bottom + pad)
145
+ component_image = image.crop((left, top, right, bottom))
146
+ if not square:
147
+ return component_image, [left, top, right, bottom]
148
+
149
+ side = max(component_image.size)
150
+ canvas = Image.new("RGBA", (side, side), (0, 0, 0, 0))
151
+ canvas.alpha_composite(
152
+ component_image,
153
+ ((side - component_image.size[0]) // 2, (side - component_image.size[1]) // 2),
154
+ )
155
+ return canvas, [left, top, right, bottom]
156
+
157
+
158
+ def region_components(image, path, warnings=None):
159
+ """Validate ownership regions before cropping, including faint detached pixels."""
160
+ data = json.loads(Path(path).read_text())
161
+ regions = data.get("regions") if isinstance(data, dict) else None
162
+ if not isinstance(regions, list) or not regions:
163
+ raise SystemExit("--regions requires a nonempty regions list")
164
+ alpha = image.getchannel("A")
165
+ uncovered = alpha.copy()
166
+ components = []
167
+ names = set()
168
+ for region in regions:
169
+ if not isinstance(region, dict):
170
+ raise SystemExit("Each region must be an object")
171
+ name, box = region.get("name"), region.get("box")
172
+ if (not isinstance(name, str) or not name or name in {".", ".."}
173
+ or any(c in name for c in ("/", "\\", "\x00"))):
174
+ raise SystemExit("Region name must be a safe filename component")
175
+ filename = name if name.lower().endswith(".png") else name + ".png"
176
+ if filename.casefold() in names:
177
+ raise SystemExit("Region names must be unique")
178
+ names.add(filename.casefold())
179
+ if (not isinstance(box, list) or len(box) != 4
180
+ or any(type(v) is not int for v in box)):
181
+ raise SystemExit("Region box must be [x, y, width, height] integer pixels")
182
+ x, y, width, height = box
183
+ if x < 0 or y < 0 or width <= 0 or height <= 0 or x + width > image.width or y + height > image.height:
184
+ raise SystemExit(f"Region {name} is outside the image or has nonpositive size")
185
+ bounds = [x, y, x + width, y + height]
186
+ for prior in components:
187
+ a, b, c, d = prior["region_box"]
188
+ if max(x, a) < min(x + width, c) and max(y, b) < min(y + height, d):
189
+ raise SystemExit(f"Region {name} overlaps another region")
190
+ local = alpha.crop(bounds)
191
+ bbox = local.getbbox()
192
+ if bbox is None:
193
+ raise SystemExit(f"Region {name} contains no foreground")
194
+ if bbox[0] == 0 or bbox[1] == 0 or bbox[2] == width or bbox[3] == height:
195
+ raise SystemExit(f"Region {name} foreground touches its boundary; expand the region")
196
+ uncovered.paste(0, bounds)
197
+ components.append({"name": filename, "region_box": bounds,
198
+ "box": [x + bbox[0], y + bbox[1], x + bbox[2], y + bbox[3]],
199
+ "area": sum(local.histogram()[1:])})
200
+ uncovered_box = uncovered.getbbox()
201
+ if uncovered_box is not None:
202
+ pixel_count = sum(uncovered.histogram()[1:])
203
+ max_alpha = uncovered.getextrema()[1]
204
+ if pixel_count > MAX_RESIDUE_PIXELS or max_alpha > MAX_RESIDUE_ALPHA:
205
+ raise SystemExit(f"Regions leave foreground uncovered: {list(uncovered_box)}")
206
+ # The blank perimeter enforced above separates these pixels from every
207
+ # owned object, including any faint stroke connected to its main body.
208
+ warning = {"code": "ignored_faint_residue", "pixel_count": pixel_count,
209
+ "max_alpha": max_alpha, "box": list(uncovered_box)}
210
+ if warnings is not None:
211
+ warnings.append(warning)
212
+ return components
213
+
214
+
215
+ def write_contact_sheet(items, out_path):
216
+ if not items:
217
+ return
218
+ thumb = 180
219
+ label_h = 28
220
+ cols = min(5, len(items))
221
+ rows = (len(items) + cols - 1) // cols
222
+ sheet = Image.new("RGB", (cols * thumb, rows * (thumb + label_h)), "white")
223
+ draw = ImageDraw.Draw(sheet)
224
+ for index, item in enumerate(items):
225
+ row, col = divmod(index, cols)
226
+ preview = item["image"].copy()
227
+ preview.thumbnail((thumb - 16, thumb - 16))
228
+ x = col * thumb + (thumb - preview.width) // 2
229
+ y = row * (thumb + label_h) + (thumb - preview.height) // 2
230
+ checker = Image.new("RGB", preview.size, "#f4f4f4")
231
+ checker.paste(preview, mask=preview.getchannel("A"))
232
+ sheet.paste(checker, (x, y))
233
+ draw.text((col * thumb + 8, row * (thumb + label_h) + thumb), item["name"], fill="black")
234
+ sheet.save(out_path)
235
+
236
+
237
+ def main():
238
+ parser = argparse.ArgumentParser(description="Split a transparent asset sheet into component PNG files.")
239
+ parser.add_argument("--input", required=True, help="RGBA asset sheet after chroma-key removal")
240
+ parser.add_argument("--out-dir", required=True, help="Directory for split PNG assets")
241
+ parser.add_argument("--regions", help="JSON {regions: [{name, box: [x,y,width,height]}]}; preserves all alpha within each region")
242
+ parser.add_argument("--names", help="Comma-separated output names in sorted component order")
243
+ parser.add_argument("--sort", choices=["x", "y", "area"], default="x")
244
+ parser.add_argument("--threshold", type=int, default=20, help="Alpha threshold for foreground pixels")
245
+ parser.add_argument("--min-area", type=int, default=1000, help="Minimum connected area to keep")
246
+ parser.add_argument("--connectivity", type=int, choices=[4, 8], default=8)
247
+ parser.add_argument("--close-radius", type=int, default=3, help="Small morphology close radius for broken strokes")
248
+ parser.add_argument("--merge-gap", type=int, default=18, help="Merge nearby fragments within this pixel gap; 0 disables")
249
+ parser.add_argument("--merge-union-growth", type=float, default=2.4, help="Maximum union-box growth allowed when merging fragments")
250
+ parser.add_argument("--pad", type=int, default=24)
251
+ parser.add_argument("--limit", type=int, help="Maximum number of components to write")
252
+ parser.add_argument("--square", action="store_true", help="Place each extracted asset on a transparent square canvas")
253
+ parser.add_argument("--manifest", help="Optional JSON report path for component boxes and outputs")
254
+ parser.add_argument("--contact-sheet", help="Optional contact sheet image for visual QA")
255
+ args = parser.parse_args()
256
+
257
+ src = Path(args.input)
258
+ out_dir = Path(args.out_dir)
259
+ out_dir.mkdir(parents=True, exist_ok=True)
260
+
261
+ image = Image.open(src).convert("RGBA")
262
+ if args.pad < 0:
263
+ raise SystemExit("--pad must be nonnegative")
264
+ warnings = []
265
+ if args.regions:
266
+ if args.names or args.limit:
267
+ raise SystemExit("--regions cannot be combined with --names or --limit")
268
+ components = region_components(image, args.regions, warnings)
269
+ else:
270
+ mask = foreground_mask(image.getchannel("A"), args.threshold, args.close_radius)
271
+ components = component_boxes(mask, 1, args.connectivity)
272
+ components = merge_fragments(components, args.merge_gap, args.merge_union_growth)
273
+ components = [item for item in components if item["area"] >= args.min_area]
274
+ components = sort_components(components, args.sort)
275
+ if args.limit:
276
+ components = components[: args.limit]
277
+
278
+ names = parse_names(args.names)
279
+ if names and len(names) != len(components):
280
+ raise SystemExit(f"--names supplied {len(names)} names, but detected {len(components)} components")
281
+
282
+ if args.regions:
283
+ for component in components:
284
+ if (out_dir / component["name"]).resolve() == src.resolve():
285
+ raise SystemExit("A region output must not overwrite the input sheet")
286
+
287
+ outputs = []
288
+ contact_items = []
289
+ for index, component in enumerate(components, start=1):
290
+ name = component.get("name") or (names[index - 1] if names else f"asset_{index:02d}.png")
291
+ if not name.lower().endswith(".png"):
292
+ name += ".png"
293
+ component_image, padded_box = extract_component_asset(image, component["box"], args.pad, args.square, component.get("region_box"))
294
+ out_path = out_dir / name
295
+ component_image.save(out_path)
296
+ entry = {
297
+ "path": str(out_path),
298
+ "source": str(src),
299
+ "box": component["box"],
300
+ "padded_box": padded_box,
301
+ "area": component["area"],
302
+ "merged_count": component.get("merged_count", 1),
303
+ "size": list(component_image.size),
304
+ }
305
+ if "region_box" in component:
306
+ entry["region_box"] = component["region_box"]
307
+ outputs.append(entry)
308
+ contact_items.append({"name": name, "image": component_image})
309
+ print(f"{name}: box={component['box']} area={component['area']} size={component_image.size}")
310
+
311
+ for warning in warnings:
312
+ print(f"Warning: {json.dumps(warning)}")
313
+ if args.manifest:
314
+ report = {"source": str(src), "assets": outputs}
315
+ if warnings:
316
+ report["warnings"] = warnings
317
+ Path(args.manifest).write_text(json.dumps(report, ensure_ascii=False, indent=2))
318
+ if args.contact_sheet:
319
+ write_contact_sheet(contact_items, Path(args.contact_sheet))
320
+
321
+
322
+ if __name__ == "__main__":
323
+ main()