alchemypose 1.0.0__py3-none-any.whl

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 (45) hide show
  1. alchemypose/__init__.py +26 -0
  2. alchemypose/__main__.py +5 -0
  3. alchemypose/cli.py +372 -0
  4. alchemypose/core/__init__.py +0 -0
  5. alchemypose/core/h36m.py +93 -0
  6. alchemypose/core/presets.py +68 -0
  7. alchemypose/core/schema.py +127 -0
  8. alchemypose/core/serialize.py +173 -0
  9. alchemypose/core/topology.py +177 -0
  10. alchemypose/errors.py +14 -0
  11. alchemypose/gui/__init__.py +20 -0
  12. alchemypose/gui/app.py +24 -0
  13. alchemypose/gui/bridge.py +94 -0
  14. alchemypose/gui/canvas/__init__.py +8 -0
  15. alchemypose/gui/canvas/interaction.py +78 -0
  16. alchemypose/gui/canvas/items.py +116 -0
  17. alchemypose/gui/canvas/lod.py +96 -0
  18. alchemypose/gui/canvas/scene.py +533 -0
  19. alchemypose/gui/canvas/view.py +184 -0
  20. alchemypose/gui/export.py +116 -0
  21. alchemypose/gui/main_window.py +534 -0
  22. alchemypose/gui/panels/__init__.py +7 -0
  23. alchemypose/gui/panels/inspector.py +56 -0
  24. alchemypose/gui/panels/layers.py +143 -0
  25. alchemypose/gui/panels/people.py +61 -0
  26. alchemypose/gui/panels/presets.py +52 -0
  27. alchemypose/gui/reporting.py +33 -0
  28. alchemypose/gui/theme.py +66 -0
  29. alchemypose/inference/__init__.py +0 -0
  30. alchemypose/inference/detector.py +148 -0
  31. alchemypose/inference/engine.py +20 -0
  32. alchemypose/inference/rtmw.py +148 -0
  33. alchemypose/inference/session.py +162 -0
  34. alchemypose/inference/simcc.py +116 -0
  35. alchemypose/inference/weights.py +293 -0
  36. alchemypose/inference/worker.py +123 -0
  37. alchemypose/media/__init__.py +0 -0
  38. alchemypose/media/image.py +24 -0
  39. alchemypose/py.typed +0 -0
  40. alchemypose-1.0.0.dist-info/METADATA +492 -0
  41. alchemypose-1.0.0.dist-info/RECORD +45 -0
  42. alchemypose-1.0.0.dist-info/WHEEL +5 -0
  43. alchemypose-1.0.0.dist-info/entry_points.txt +2 -0
  44. alchemypose-1.0.0.dist-info/licenses/LICENSE +21 -0
  45. alchemypose-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,26 @@
1
+ """Whole-body human pose visualisation.
2
+
3
+ ``App`` is resolved lazily so that importing this package never pulls in Qt:
4
+ ``core`` and ``inference`` must stay importable on headless machines and in CI.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ #: The one place the version is written. ``pyproject.toml`` declares the version
10
+ #: dynamic and reads it back from here, so the distribution metadata and this
11
+ #: attribute cannot disagree — and ``tests/unit/test_package.py`` fails loudly if
12
+ #: an installed copy ever proves otherwise.
13
+ __version__ = "1.0.0"
14
+
15
+ if TYPE_CHECKING: # pragma: no cover
16
+ from alchemypose.gui.app import App
17
+
18
+ __all__ = ["App", "__version__"]
19
+
20
+
21
+ def __getattr__(name: str) -> Any:
22
+ if name == "App":
23
+ from alchemypose.gui.app import App as _App
24
+
25
+ return _App
26
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,5 @@
1
+ # src/alchemypose/__main__.py
2
+ from alchemypose.cli import app
3
+
4
+ if __name__ == "__main__":
5
+ app()
alchemypose/cli.py ADDED
@@ -0,0 +1,372 @@
1
+ # src/alchemypose/cli.py
2
+ """The command line. ``alchemypose`` is the app; the rest is for scripting."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ from collections.abc import Callable, Iterator
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING
11
+
12
+ import typer
13
+
14
+ from alchemypose import __version__
15
+ from alchemypose.errors import AlchemyPoseError
16
+ from alchemypose.inference import weights
17
+
18
+ if TYPE_CHECKING: # imported for real only when a download actually starts
19
+ from rich.progress import Progress, TaskID
20
+
21
+ app = typer.Typer(
22
+ help="Whole-body human pose visualisation. With no command, opens the window.",
23
+ # Deliberately *not* ``no_args_is_help=True``, and written out rather than
24
+ # left to the default because the default is the whole mechanism. click
25
+ # checks this flag in ``Group.parse_args``, which runs before
26
+ # ``invoke_without_command`` is ever consulted, so with both set a bare
27
+ # ``alchemypose`` prints the help and exits 2 and the callback below never
28
+ # runs at all. Re-adding the flag would silently take the window away from
29
+ # the bare command.
30
+ no_args_is_help=False,
31
+ )
32
+ models_app = typer.Typer(help="Manage cached ONNX model files.")
33
+ app.add_typer(models_app, name="models")
34
+
35
+ #: Derived, never typed out. A hand-written copy is how ``--help`` ends up
36
+ #: advertising three presets while the rejection message names four.
37
+ _PRESET_HELP = " | ".join(weights.PRESETS)
38
+
39
+
40
+ def _stderr_is_a_terminal() -> bool:
41
+ """Whether stderr is something a moving bar belongs on.
42
+
43
+ Wrapped rather than inlined because every part of it can be untrue at once:
44
+ ``sys.stderr`` is ``None`` under a windowed interpreter, closed by the time
45
+ an atexit path runs, and a plain object with no ``isatty`` under some test
46
+ harnesses. None of those are worth an exception on the way to deciding how
47
+ to print a sentence.
48
+ """
49
+ stream = sys.stderr
50
+ try:
51
+ return stream is not None and bool(stream.isatty())
52
+ except (AttributeError, ValueError):
53
+ return False
54
+
55
+
56
+ class _DownloadFeedback:
57
+ """Says what is being downloaded, on stderr, for as long as it takes.
58
+
59
+ ``alchemypose image photo.jpg`` on a cold cache printed nothing at all
60
+ until the result appeared, a few hundred megabytes and several minutes
61
+ later — from the outside, indistinguishable from a command that had hung.
62
+ This fills that silence, and is built to be invisible the rest of the time:
63
+
64
+ * Nothing is constructed and nothing is printed until bytes actually start
65
+ moving. ``weights.ensure`` calls back only once it has decided to fetch,
66
+ so a warm cache — the common case, and the one that has to stay fast and
67
+ quiet — gets exactly the output it always had: none.
68
+ * Everything goes to **stderr**, so ``alchemypose image photo.jpg > out.json``
69
+ still puts nothing but JSON in the file.
70
+ * The bar is drawn only when stderr is a terminal. Piped or redirected, the
71
+ same facts arrive as one plain sentence per model with not one escape
72
+ sequence in it, because the other end of that pipe is usually a log.
73
+ rich's own handling of a non-terminal console is no substitute, and was
74
+ measured rather than assumed: it renders the bar once, in box-drawing
75
+ characters, when the transfer is already *over* — the one moment at which
76
+ the number has stopped being any use.
77
+ """
78
+
79
+ def __init__(self) -> None:
80
+ self._interactive = _stderr_is_a_terminal()
81
+ self._announced: set[str] = set()
82
+ self._said_where = False
83
+ self._bars: Progress | None = None
84
+ self._tasks: dict[str, TaskID] = {}
85
+
86
+ def for_model(self, key: str) -> Callable[[int, int], None]:
87
+ """The ``progress=`` callable to hand ``weights.ensure(key)``.
88
+
89
+ One per model, because the key is the half of the message ``ensure``
90
+ does not pass on — the callback is told bytes, not which file they
91
+ belong to.
92
+ """
93
+
94
+ def report(done: int, total: int) -> None:
95
+ if key not in self._announced:
96
+ self._announce(key, total)
97
+ self._advance(key, done)
98
+
99
+ return report
100
+
101
+ def close(self) -> None:
102
+ """Give the terminal back. A no-op when nothing was ever drawn.
103
+
104
+ Called between models as well as at the end: a live region and any
105
+ other writer sharing one terminal is how a line ends up half
106
+ overwritten, and ``models fetch`` prints between downloads.
107
+ """
108
+ bars, self._bars = self._bars, None
109
+ self._tasks.clear() # a TaskID belongs to the Progress that issued it
110
+ if bars is not None:
111
+ bars.stop()
112
+
113
+ # ----------------------------------------------------------------- detail
114
+
115
+ def _announce(self, key: str, total: int) -> None:
116
+ """The one line that has to arrive *before* the wait, not after it."""
117
+ self._announced.add(key)
118
+ if not self._said_where:
119
+ # Where they land, and that this is not a per-run cost, are the two
120
+ # questions the first sight of a 213 MB download raises. Once.
121
+ self._said_where = True
122
+ typer.echo(f"Model weights are downloaded once and kept in {weights.cache_dir()}.", err=True)
123
+
124
+ headline = f"Downloading {key} ({weights.human_size(total)})"
125
+ if not self._interactive:
126
+ typer.echo(f"{headline} ...", err=True)
127
+ return
128
+ self._tasks[key] = self._open_bars().add_task(headline, total=total or None)
129
+
130
+ def _advance(self, key: str, done: int) -> None:
131
+ task = self._tasks.get(key)
132
+ if task is not None and self._bars is not None:
133
+ self._bars.update(task, completed=done)
134
+
135
+ def _open_bars(self) -> Progress:
136
+ """The rich import happens here, and so only on a cold cache.
137
+
138
+ Every other invocation — ``--version``, a warm ``image``, a rejected
139
+ preset — never touches this method, and so never pays for importing
140
+ rich to decide it had nothing to draw.
141
+ """
142
+ if self._bars is None:
143
+ from rich.console import Console
144
+ from rich.progress import (
145
+ BarColumn,
146
+ Progress,
147
+ TaskProgressColumn,
148
+ TextColumn,
149
+ TimeRemainingColumn,
150
+ TransferSpeedColumn,
151
+ )
152
+
153
+ self._bars = Progress(
154
+ TextColumn("{task.description}"),
155
+ BarColumn(),
156
+ TaskProgressColumn(),
157
+ TransferSpeedColumn(),
158
+ TimeRemainingColumn(),
159
+ # A Console of its own, never ``rich.get_console()``: that one
160
+ # is a process-wide singleton pointed at stdout, and stdout is
161
+ # where the JSON goes. ``stderr=True`` re-reads ``sys.stderr``
162
+ # on every write rather than capturing it now, which is what a
163
+ # harness that swaps the stream out from under the command
164
+ # needs.
165
+ console=Console(stderr=True),
166
+ )
167
+ self._bars.start()
168
+ return self._bars
169
+
170
+
171
+ @contextmanager
172
+ def _download_feedback() -> Iterator[_DownloadFeedback]:
173
+ """Scope the terminal hand-over: however this ends, the bar is closed."""
174
+ feedback = _DownloadFeedback()
175
+ try:
176
+ yield feedback
177
+ finally:
178
+ feedback.close()
179
+
180
+
181
+ def _fetch_weights(preset: str) -> None:
182
+ """Put the preset's models on disk before anything slow and silent wants them.
183
+
184
+ ``RTMWEngine`` calls ``weights.ensure`` itself and would do it without a
185
+ word; fetching here first means the download happens in the one place that
186
+ knows whether a terminal is watching. A model already cached costs one
187
+ checksum and prints nothing, and the engine's own ``ensure`` a moment later
188
+ costs a second one — a tenth of a second across the largest preset, against
189
+ a download this exists to narrate.
190
+ """
191
+ with _download_feedback() as feedback:
192
+ for key in weights.PRESETS[preset]:
193
+ weights.ensure(key, progress=feedback.for_model(key))
194
+ feedback.close()
195
+
196
+
197
+ def _fail(message: str) -> typer.Exit:
198
+ """Print a one-line error and build the exit to raise.
199
+
200
+ A mistyped flag is a user error, not a defect, and must never reach the
201
+ terminal as a traceback.
202
+ """
203
+ typer.echo(f"Error: {message}", err=True)
204
+ return typer.Exit(1)
205
+
206
+
207
+ def _checked_preset(preset: str) -> str:
208
+ """Return ``preset`` if it names one, else exit with the valid choices.
209
+
210
+ ``weights.PRESETS`` is the single source of truth, so a preset added there
211
+ needs no second edit here — which an ``Enum`` on the option would have.
212
+ ``_PRESET_HELP`` is built from the same dict, so ``--help`` and this message
213
+ cannot come to name different sets.
214
+ """
215
+ if preset not in weights.PRESETS:
216
+ raise _fail(f"unknown preset {preset!r}. Choose one of: {', '.join(weights.PRESETS)}.")
217
+ return preset
218
+
219
+
220
+ def _checked_output(path: Path | None, flag: str) -> Path | None:
221
+ """Reject an output path whose directory is missing, before anything runs.
222
+
223
+ Inference costs seconds and a model download costs minutes; discovering the
224
+ destination does not exist only once there is a result to write throws all
225
+ of that away.
226
+ """
227
+ if path is not None and not path.parent.is_dir():
228
+ raise _fail(f"{flag} directory {path.parent} does not exist.")
229
+ return path
230
+
231
+
232
+ @app.command()
233
+ def gui() -> None:
234
+ """Open the AlchemyPose window."""
235
+ from alchemypose.gui.app import main
236
+
237
+ raise typer.Exit(main())
238
+
239
+
240
+ def _version_and_exit(ctx: typer.Context, value: bool) -> bool:
241
+ """Answer ``--version`` during parsing, before any command can run.
242
+
243
+ ``is_eager`` is what makes it "during parsing": the version is printed and
244
+ the process stops before the callback below gets as far as deciding whether
245
+ to open a window, which matters now that deciding nothing is what opens one.
246
+
247
+ ``resilient_parsing`` is set while click is computing a shell completion.
248
+ Writing to stdout in that pass would put the version string into the list of
249
+ completions the shell is reading.
250
+ """
251
+ if value and not ctx.resilient_parsing:
252
+ typer.echo(__version__)
253
+ raise typer.Exit()
254
+ return value
255
+
256
+
257
+ @app.callback(invoke_without_command=True)
258
+ def _default(
259
+ ctx: typer.Context,
260
+ show_version: bool = typer.Option(
261
+ False,
262
+ "--version",
263
+ "-V",
264
+ help="Print the version and exit.",
265
+ is_eager=True,
266
+ callback=_version_and_exit,
267
+ ),
268
+ ) -> None:
269
+ """Open the window when no subcommand is given.
270
+
271
+ ``alchemypose`` on its own is what a person types straight after
272
+ ``pip install alchemypose``, and a page of help is not what they came for.
273
+ ``invoke_without_command`` is what lets this run with no subcommand at all;
274
+ the guard below is what stops it running *ahead* of one, because click
275
+ invokes a group callback for every subcommand too. Without the guard,
276
+ ``alchemypose image photo.jpg`` opens a window and never analyses the
277
+ photograph at all — ``gui()`` exits with the window's status, and click
278
+ never reaches the subcommand it already resolved. Measured on exactly that
279
+ edit: exit code 43 from a stubbed window, and no output whatsoever.
280
+
281
+ A mistyped subcommand does not reach here either, and that is click's doing
282
+ rather than this function's: ``Group.invoke`` resolves the name and fails on
283
+ an unknown one *before* it invokes the group callback, so
284
+ ``alchemypose imagee`` exits 2 with a usage message instead of opening a
285
+ window over a typo. ``tests/unit/test_cli.py`` pins that, because it is the
286
+ part of this arrangement that a later refactor could quietly lose.
287
+
288
+ ``gui()`` is called rather than reimplemented so the bare command and
289
+ ``alchemypose gui`` cannot come to mean different things.
290
+ """
291
+ if ctx.invoked_subcommand is not None:
292
+ return
293
+ gui()
294
+
295
+
296
+ @app.command()
297
+ def image(
298
+ path: Path = typer.Argument(..., help="Image to analyse."),
299
+ preset: str = typer.Option("performance", help=_PRESET_HELP),
300
+ json_out: Path | None = typer.Option(None, "--json", help="Write the result here instead of stdout."),
301
+ csv_out: Path | None = typer.Option(None, "--csv", help="Also write a flat CSV here."),
302
+ ) -> None:
303
+ """Run pose estimation on one image and print the result as JSON."""
304
+ preset = _checked_preset(preset)
305
+ if not path.exists():
306
+ raise _fail(f"{path} not found.")
307
+ json_out = _checked_output(json_out, "--json")
308
+ csv_out = _checked_output(csv_out, "--csv")
309
+
310
+ from alchemypose.core.serialize import to_csv, to_json
311
+ from alchemypose.inference.rtmw import RTMWEngine
312
+ from alchemypose.media.image import load_image
313
+
314
+ try:
315
+ _fetch_weights(preset)
316
+ result = RTMWEngine(preset=preset).infer(load_image(path), source=str(path))
317
+ except AlchemyPoseError as exc:
318
+ raise _fail(str(exc)) from exc
319
+
320
+ payload = to_json(result)
321
+ if json_out is not None:
322
+ json_out.write_text(payload)
323
+ typer.echo(f"Wrote {json_out}")
324
+ else:
325
+ typer.echo(payload)
326
+ if csv_out is not None:
327
+ csv_out.write_text(to_csv(result))
328
+ typer.echo(f"Wrote {csv_out}")
329
+
330
+
331
+ @models_app.command("list")
332
+ def models_list() -> None:
333
+ """Show the presets, their models, and whether they are cached."""
334
+ typer.echo(f"Cache: {weights.cache_dir()}")
335
+ for preset, keys in weights.PRESETS.items():
336
+ typer.echo(f"\n{preset}:")
337
+ for key in keys:
338
+ spec = weights.REGISTRY[key]
339
+ state = "cached" if (weights.cache_dir() / spec.filename).exists() else "not downloaded"
340
+ typer.echo(f" {key:<22} {state}")
341
+
342
+
343
+ @models_app.command("fetch")
344
+ def models_fetch(preset: str = typer.Option("performance", help=_PRESET_HELP)) -> None:
345
+ """Download a preset's models now, rather than on first use."""
346
+ preset = _checked_preset(preset)
347
+ with _download_feedback() as feedback:
348
+ for key in weights.PRESETS[preset]:
349
+ # Named on stdout whether or not it turns out to need fetching —
350
+ # this is the command whose whole subject is the cache, so "nothing
351
+ # to do for this one" is an answer, not noise. The size and the bar
352
+ # come from the feedback on stderr, and only if bytes move.
353
+ typer.echo(f"Fetching {key} ...")
354
+ weights.ensure(key, progress=feedback.for_model(key))
355
+ feedback.close()
356
+ typer.echo("Done.")
357
+
358
+
359
+ @models_app.command("clear")
360
+ def models_clear() -> None:
361
+ """Delete every cached model file."""
362
+ removed = 0
363
+ for file in weights.cache_dir().glob("*.onnx"):
364
+ file.unlink()
365
+ removed += 1
366
+ typer.echo(f"Removed {removed} file(s).")
367
+
368
+
369
+ @app.command()
370
+ def version() -> None:
371
+ """Print the version."""
372
+ typer.echo(__version__)
File without changes
@@ -0,0 +1,93 @@
1
+ """COCO-WholeBody -> Human3.6M 17-joint conversion.
2
+
3
+ Nothing in v1 calls this. It exists because every monocular 2D->3D lifting model
4
+ (MotionBERT, MotionAGFormer, VideoPose3D) consumes H36M-17, and COCO has no
5
+ pelvis, thorax, spine or head-top joint — they must be synthesised. Writing the
6
+ mapping now pins the conventions while they are still cheap to change.
7
+
8
+ Convention: input is source-image pixels, origin top-left, y down. Output is the
9
+ same. Normalisation into a lifter's expected range is that lifter's business.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+ from numpy.typing import NDArray
16
+
17
+ from alchemypose.core.schema import PersonPose
18
+ from alchemypose.core.topology import KEYPOINT_NAMES
19
+
20
+ F32 = NDArray[np.float32]
21
+
22
+ H36M_NAMES: tuple[str, ...] = (
23
+ "pelvis", "right_hip", "right_knee", "right_ankle",
24
+ "left_hip", "left_knee", "left_ankle",
25
+ "spine", "thorax", "neck", "head",
26
+ "left_shoulder", "left_elbow", "left_wrist",
27
+ "right_shoulder", "right_elbow", "right_wrist",
28
+ )
29
+
30
+ #: Interpolation weight from thorax toward head for the neck joint. H36M's neck sits at the
31
+ #: base of the cervical spine, close to the thorax — not halfway to the head. COCO offers no
32
+ #: neck-base point, so we interpolate a short way from thorax toward nose. A midpoint would
33
+ #: land around chin level; 0.25 is a defensible approximation of the real anatomical offset.
34
+ NECK_FROM_THORAX = 0.25
35
+
36
+ #: H36M joints that are a straight copy of a COCO joint.
37
+ _DIRECT: dict[str, str] = {
38
+ "right_hip": "right_hip", "right_knee": "right_knee", "right_ankle": "right_ankle",
39
+ "left_hip": "left_hip", "left_knee": "left_knee", "left_ankle": "left_ankle",
40
+ "left_shoulder": "left_shoulder", "left_elbow": "left_elbow", "left_wrist": "left_wrist",
41
+ "right_shoulder": "right_shoulder", "right_elbow": "right_elbow", "right_wrist": "right_wrist",
42
+ "head": "nose",
43
+ }
44
+
45
+ _C: dict[str, int] = {
46
+ name: KEYPOINT_NAMES.index(name)
47
+ for name in set(_DIRECT.values()) | {"left_hip", "right_hip", "left_shoulder", "right_shoulder", "nose"}
48
+ }
49
+
50
+
51
+ def to_h36m17(person: PersonPose) -> tuple[F32, F32]:
52
+ """Return ``(keypoints (17, 2), scores (17,))`` in H36M joint order.
53
+
54
+ Synthesised joints take the *minimum* confidence of their parents, so a joint
55
+ derived from one unreliable parent is itself marked unreliable.
56
+ """
57
+ kp = person.keypoints
58
+ sc = person.scores
59
+
60
+ out_kp = np.zeros((17, 2), dtype=np.float32)
61
+ out_sc = np.zeros((17,), dtype=np.float32)
62
+
63
+ for h_name, c_name in _DIRECT.items():
64
+ i = H36M_NAMES.index(h_name)
65
+ j = _C[c_name]
66
+ out_kp[i] = kp[j]
67
+ out_sc[i] = sc[j]
68
+
69
+ def mid(a: str, b: str) -> tuple[F32, np.float32]:
70
+ ia, ib = _C[a], _C[b]
71
+ return ((kp[ia] + kp[ib]) / 2.0).astype(np.float32), np.minimum(sc[ia], sc[ib])
72
+
73
+ pelvis_xy, pelvis_s = mid("left_hip", "right_hip")
74
+ thorax_xy, thorax_s = mid("left_shoulder", "right_shoulder")
75
+
76
+ out_kp[H36M_NAMES.index("pelvis")], out_sc[H36M_NAMES.index("pelvis")] = pelvis_xy, pelvis_s
77
+ out_kp[H36M_NAMES.index("thorax")], out_sc[H36M_NAMES.index("thorax")] = thorax_xy, thorax_s
78
+
79
+ spine_xy = ((pelvis_xy + thorax_xy) / 2.0).astype(np.float32)
80
+ out_kp[H36M_NAMES.index("spine")] = spine_xy
81
+ out_sc[H36M_NAMES.index("spine")] = min(pelvis_s, thorax_s)
82
+
83
+ # H36M's neck sits at the base of the cervical spine, close to the thorax — not
84
+ # halfway to the head. COCO offers no neck-base point, so interpolate a short way
85
+ # from the thorax toward the nose. A midpoint lands around chin level; a quarter is
86
+ # a defensible approximation of the real offset. Confidence still takes the minimum
87
+ # of the two parents, since it is derived from both regardless of the weighting.
88
+ nose_i = _C["nose"]
89
+ neck_xy = (thorax_xy * (1.0 - NECK_FROM_THORAX) + kp[nose_i] * NECK_FROM_THORAX).astype(np.float32)
90
+ out_kp[H36M_NAMES.index("neck")] = neck_xy
91
+ out_sc[H36M_NAMES.index("neck")] = min(thorax_s, sc[nose_i])
92
+
93
+ return out_kp, out_sc
@@ -0,0 +1,68 @@
1
+ """Named visibility presets.
2
+
3
+ Presets are not a mode. Each one is a set of render-group names; the UI applies
4
+ one by setting the layer tree's check states, so the tree always shows the truth
5
+ about what is drawn. ``matching_preset`` is the inverse, letting the UI light up
6
+ a chip when hand-toggling happens to land on it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Iterable
12
+
13
+ from alchemypose.core.schema import KeypointSelection
14
+ from alchemypose.core.topology import RENDER_GROUPS
15
+
16
+ _ALL_GROUPS = tuple(RENDER_GROUPS)
17
+
18
+ #: preset name -> the render groups it turns on
19
+ PRESETS: dict[str, tuple[str, ...]] = {
20
+ "full_body": ("torso_head", "left_arm", "right_arm", "left_leg", "right_leg", "left_foot", "right_foot"),
21
+ "upper": ("torso_head", "left_arm", "right_arm", "left_hand", "right_hand"),
22
+ "lower": ("left_leg", "right_leg", "left_foot", "right_foot"),
23
+ "left_side": ("left_arm", "left_leg", "left_foot", "left_hand"),
24
+ "right_side": ("right_arm", "right_leg", "right_foot", "right_hand"),
25
+ "hands": ("left_hand", "right_hand"),
26
+ "face": ("face_jaw", "face_brows", "face_nose", "face_eyes", "face_lips"),
27
+ "all": _ALL_GROUPS,
28
+ "none": (),
29
+ }
30
+
31
+
32
+ def selection_from_groups(groups: Iterable[str]) -> KeypointSelection:
33
+ """Union the indices of the named render groups."""
34
+ indices: set[int] = set()
35
+ for name in groups:
36
+ indices.update(RENDER_GROUPS[name])
37
+ return KeypointSelection(visible=frozenset(indices))
38
+
39
+
40
+ def selection_for(preset: str) -> KeypointSelection:
41
+ """The selection a preset chip applies. Raises KeyError for an unknown name."""
42
+ return selection_from_groups(PRESETS[preset])
43
+
44
+
45
+ # matching_preset (below) returns the first exact match in dict order, so two
46
+ # presets resolving to the same visible set would make the second one
47
+ # unreachable and the UI would silently light up the wrong chip. Nothing in
48
+ # PRESETS collides today, but a future preset added without checking this
49
+ # could collide silently at runtime instead of loudly at import time — so
50
+ # assert distinctness once, here, over the (cheap: nine small sets) set of
51
+ # all presets.
52
+ _visible_sets = [selection_for(name).visible for name in PRESETS]
53
+ assert len(_visible_sets) == len(set(_visible_sets)), (
54
+ "PRESETS must all resolve to distinct visible sets: matching_preset picks the first "
55
+ "exact match in dict order, so a collision would silently hide one preset behind another"
56
+ )
57
+
58
+
59
+ def matching_preset(selection: KeypointSelection) -> str | None:
60
+ """The preset this selection exactly equals, if any.
61
+
62
+ Order matters only for presets that could coincide; ``none`` and ``all`` are
63
+ checked like any other because an empty or complete selection is unambiguous.
64
+ """
65
+ for name in PRESETS:
66
+ if selection_for(name).visible == selection.visible:
67
+ return name
68
+ return None