feat: nearest-match select function

This commit is contained in:
Ben Stull
2026-06-04 01:36:07 -07:00
parent d28fb0a0a7
commit 904c4bff52
2 changed files with 98 additions and 0 deletions
+43
View File
@@ -53,3 +53,46 @@ def candidates_for_mode(records, mode: str, pool_size: int) -> list[Record]:
extra = [r for r in records if r.mode in {"audio", "video"}]
return primary + extra
return primary
from typing import Optional
def select(
records,
coord: Coordinate,
mode: str,
*,
pool_size: int = 4,
weights: Weights = Weights(),
approved_only: bool = False,
rng=None,
) -> Optional[Record]:
"""Pick the record nearest `coord` for the given selector `mode`.
- 'none' selector mode returns None (the void/rest state).
- With rng=None, returns the single nearest record (ties broken by id) for
deterministic behavior. Pass a random.Random to shuffle within the
pool_size nearest records.
- approved_only restricts to records the human has blessed.
"""
if mode not in SELECTOR_MODES:
raise ValueError(
f"invalid selector mode {mode!r}; expected one of {sorted(SELECTOR_MODES)}"
)
if mode == "none":
return None
pool = records
if approved_only:
pool = [r for r in pool if r.review_status == "approved"]
candidates = candidates_for_mode(pool, mode, pool_size)
if not candidates:
return None
ranked = sorted(
candidates,
key=lambda r: (distance(coord, record_coordinate(r), weights), r.id),
)
nearest = ranked[:pool_size]
if rng is None:
return nearest[0]
return rng.choice(nearest)