"""Unit tests for localization construction and scoring (no API deps).""" from __future__ import annotations from localization.construct import ( label_specs_from_segments, localization_prompt, multiplicity_phrase, ) from localization.schema import GoldSegment, PredictedInterval, PredictionResult from localization.score import optimal_group_assignment, score_episode def _segments(labels: list[str]) -> list[GoldSegment]: return [ GoldSegment(float(index), float(index + 1), label) for index, label in enumerate(labels) ] def test_multiplicity_phrasing_handles_singletons_and_duplicates(): gold = _segments(["pick", "place", "pick"]) specs = sorted( label_specs_from_segments("homer_1", gold, seed=0), key=lambda spec: spec.label, ) assert [multiplicity_phrase(spec) for spec in specs] == [ '"pick" (occurs 2 times)', '"place"', ] prompt = localization_prompt("stack the blocks", specs) assert '"pick" (occurs 2 times)' in prompt assert '- "place"\n' in prompt assert "occurs 1" not in prompt def test_label_shuffle_is_deterministic_under_seed(): gold = _segments(["a", "b", "c", "d"]) first = [spec.label for spec in label_specs_from_segments("homer_1", gold, seed=3)] second = [spec.label for spec in label_specs_from_segments("homer_1", gold, seed=3)] alternatives = { tuple(spec.label for spec in label_specs_from_segments("homer_1", gold, seed=seed)) for seed in range(10) } assert first == second assert len(alternatives) > 1 def test_optimal_group_assignment_ties_are_deterministic(): golds = [ GoldSegment(0.0, 2.0, "repeat"), GoldSegment(2.0, 4.0, "repeat"), ] preds = [ PredictedInterval(label_echo="repeat", start_sec=1.0, end_sec=3.0), PredictedInterval(label_echo="repeat", start_sec=1.0, end_sec=3.0), ] assert optimal_group_assignment(golds, preds) == {0: 0, 1: 1} def test_score_episode_exact_match_is_perfect(): gold = _segments(["pick", "place"]) specs = label_specs_from_segments("ep", gold, seed=0) prediction = PredictionResult( labels=[ { "label": "pick", "intervals": [ {"label_echo": "pick", "start_sec": 0.0, "end_sec": 1.0}, ], }, { "label": "place", "intervals": [ {"label_echo": "place", "start_sec": 1.0, "end_sec": 2.0}, ], }, ] ) rows, diagnostics = score_episode( episode_id="ep", family="homer", gold_segments=gold, specs=specs, prediction=prediction, ) assert diagnostics["events_total"] == 2 assert all(row["iou"] == 1.0 for row in rows) assert all(row["hit_0_75"] for row in rows)