Datasets:
Download code/schemas/geometry.py from govtech/municipalbench-full: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/datasets/govtech/municipalbench-full/resolve/main/code/schemas/geometry.py
- Command line
-
hf download hf://datasets/govtech/municipalbench-full/code/schemas/geometry.py
-
curl -L -o geometry.py https://huggingface.co/datasets/govtech/municipalbench-full/resolve/main/code/schemas/geometry.py
10.2 kB
| """Bounding-box conventions, and the one transform between them. | |
| Models disagree about what four numbers in a box mean. Qwen-VL emits | |
| ``[x1, y1, x2, y2]`` on a 0-1000 integer grid; Llama 4 emits the same corners | |
| normalised 0-1; YOLO gives normalised corners; the prompt asks for offsets and | |
| extents. Storing any of those verbatim scores IoU near zero against ground truth | |
| without raising anything, which is exactly how three model runs came to be | |
| recorded as complete failures. | |
| So the convention is *declared* (see ``configs/box_conventions.json``) and | |
| converted here, once, on the way in. Everything downstream — metrics, the | |
| contract, the drift report — may assume the canonical form: | |
| unit-normalised ``[x, y, width, height]``, origin top-left. | |
| Nothing in this module guesses. If a box does not fit its declared convention it | |
| is passed through with the problem recorded, so the drift report flags it; a | |
| silent rescue would hide the very drift this repo exists to measure. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Literal | |
| BoxSpace = Literal["unit", "grid1000", "pixel"] | |
| """The coordinate space a model's numbers live in. | |
| * ``unit`` — normalised 0.0-1.0 | |
| * ``grid1000`` — integer 0-1000 grid (the Qwen-VL family) | |
| * ``pixel`` — absolute pixels; needs the image size to normalise | |
| **``unit`` repairs partial non-compliance, per coordinate.** Models are asked for | |
| 0-1 and some of them only partly comply: Gemma 4 E2B returned | |
| ``[0.41, 580, 0.65, 780]`` — x normalised as instructed, y left on the 0-1000 | |
| grid it thinks in — and Qwen3.8 27B does the same on 3 boxes in 30. So a | |
| ``unit``-declared coordinate above 1 is divided by 1000 rather than clipped. | |
| This is narrower than it looks, and it is not a guess. A coordinate *declared* | |
| unit-scale and greater than 1 is already known illegal; the only question is what | |
| to do about it, and clipping is the one answer guaranteed to be wrong — it | |
| collapsed every one of Gemma's boxes to a zero-height sliver on the frame's | |
| bottom edge. Rescaling is recorded (``out_of_declared_range`` and | |
| ``rescaled_from_grid``), never silent, so a run can always say how far the model | |
| missed and what was done about it. | |
| It applies to ``unit`` only. ``grid1000`` divides everything by 1000 already, and | |
| a per-coordinate rule there would read a legitimate ``1`` (meaning 0.001) as the | |
| full width of the image. A model that emits genuine pixel coordinates must be | |
| declared ``pixel``; declared ``unit`` it would be divided by 1000 and land in the | |
| top-left corner. | |
| """ | |
| BoxOrder = Literal["xywh", "xyxy", "yxyx"] | |
| """What the four numbers are, and in which axis order. | |
| * ``xywh`` — top-left corner, then width and height | |
| * ``xyxy`` — top-left corner, then bottom-right corner | |
| * ``yxyx`` — the same two corners with the **axes swapped**: ``[y1, x1, y2, x2]`` | |
| ``yxyx`` exists because Gemini emits it. Google's documentation is explicit — | |
| "The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000" — and it | |
| is the only major family that does. Read as ``xyxy`` it does not produce | |
| obvious rubbish; it produces a transposed box, which on a roughly square image | |
| is plausible enough to pass every range check and simply score badly. That is | |
| the same failure mode as the corners-read-as-extents bug, so it gets a name | |
| rather than a comment. | |
| """ | |
| # Boxes are rounded to 4dp, so allow a hair of slack before calling a coordinate | |
| # out of range. Matches utils.contract.BBOX_TOLERANCE. | |
| TOLERANCE = 1e-3 | |
| _SCALE = {"unit": 1.0, "grid1000": 1000.0} | |
| class BoxConvention: | |
| """How to read a model's four box numbers.""" | |
| space: BoxSpace = "unit" | |
| order: BoxOrder = "xywh" | |
| def parse(cls, spec: str) -> "BoxConvention": | |
| """Build from a ``"space:order"`` string, e.g. ``"grid1000:xyxy"``.""" | |
| try: | |
| space, order = spec.strip().split(":") | |
| except ValueError: | |
| raise ValueError( | |
| f"box convention {spec!r} must look like 'space:order', " | |
| f"e.g. 'grid1000:xyxy'" | |
| ) from None | |
| if space not in ("unit", "grid1000", "pixel"): | |
| raise ValueError(f"unknown box space {space!r} in {spec!r}") | |
| if order not in ("xywh", "xyxy", "yxyx"): | |
| raise ValueError(f"unknown box order {order!r} in {spec!r}") | |
| return cls(space=space, order=order) # type: ignore[arg-type] | |
| def __str__(self) -> str: | |
| return f"{self.space}:{self.order}" | |
| CANONICAL = BoxConvention("unit", "xywh") | |
| """What every box on disk is expected to be.""" | |
| def to_unit_xywh( | |
| bbox: list[float], | |
| convention: BoxConvention = CANONICAL, | |
| image_size: tuple[int, int] | None = None, | |
| ) -> tuple[list[float], list[str]]: | |
| """Convert *bbox* from *convention* to canonical unit ``[x, y, w, h]``. | |
| Args: | |
| bbox: Four numbers as the model emitted them. | |
| convention: How to read them. | |
| image_size: ``(width, height)`` in pixels. Required for ``pixel`` space. | |
| Returns: | |
| ``(canonical_bbox, repairs)``. ``repairs`` names every adjustment made, | |
| so a run can report how much interpretation its boxes needed. An empty | |
| list means the box was already well formed. | |
| """ | |
| if len(bbox) != 4: | |
| return list(bbox), ["bbox is not four numbers"] | |
| repairs: list[str] = [] | |
| values = [float(v) for v in bbox] | |
| order = convention.order | |
| # --- 0. Put the axes in x-first order -------------------------------- | |
| # Reordering is scale-free, so doing it before anything else means the rest | |
| # of the pipeline — including which slots divide by width — never has to | |
| # know that a y-first convention exists. | |
| if order == "yxyx": | |
| y1, x1, y2, x2 = values | |
| values = [x1, y1, x2, y2] | |
| order = "xyxy" | |
| # --- 1. Normalise into 0-1 ------------------------------------------- | |
| if convention.space == "pixel": | |
| if not image_size: | |
| return values, ["pixel space needs an image size to normalise"] | |
| img_w, img_h = image_size | |
| if img_w <= 0 or img_h <= 0: | |
| return values, [f"invalid image size {image_size}"] | |
| # x-like values divide by width, y-like by height, in both orderings. | |
| values = [ | |
| values[0] / img_w, | |
| values[1] / img_h, | |
| values[2] / img_w, | |
| values[3] / img_h, | |
| ] | |
| elif convention.space == "unit": | |
| # Per coordinate, because a model is not necessarily consistent within | |
| # one box. Both flags are recorded: the first says the model did not do | |
| # what it was asked, the second says what we did about it. Keeping them | |
| # separate matters — the non-compliance is a result about the model and | |
| # must stay visible even though the box is now usable. | |
| rescaled = [v > 1.0 + TOLERANCE for v in values] | |
| if any(rescaled): | |
| repairs.append("out_of_declared_range") | |
| repairs.append("rescaled_from_grid") | |
| if all(rescaled): | |
| # Nothing was in unit scale at all, so this box needed no | |
| # per-coordinate judgement: plain grid1000 would read it identically. | |
| repairs.append("wholly_on_grid") | |
| values = [v / 1000.0 if r else v for v, r in zip(values, rescaled)] | |
| elif convention.space == "grid1000": | |
| # Qwen-VL normally uses its native 0-1000 grid, but has occasionally | |
| # complied with the prompt's requested unit scale for an entire box. | |
| # Decimal coordinates wholly inside 0-1 are unambiguous evidence of | |
| # that switch (unlike integer 0/1, which are valid grid coordinates). | |
| # Preserve those values and record the per-box deviation explicitly. | |
| wholly_unit_decimal = ( | |
| all(-TOLERANCE <= v <= 1.0 + TOLERANCE for v in values) | |
| and any(abs(v - round(v)) > TOLERANCE for v in values) | |
| ) | |
| if wholly_unit_decimal: | |
| repairs.append("response_scale_override") | |
| repairs.append("preserved_unit_scale") | |
| else: | |
| values = [v / _SCALE[convention.space] for v in values] | |
| # --- 2. Reduce to offsets and extents -------------------------------- | |
| if order == "xyxy": | |
| x1, y1, x2, y2 = values | |
| if x2 < x1: | |
| x1, x2 = x2, x1 | |
| repairs.append("swapped_x") | |
| if y2 < y1: | |
| y1, y2 = y2, y1 | |
| repairs.append("swapped_y") | |
| values = [x1, y1, x2 - x1, y2 - y1] | |
| # --- 3. Clip to the frame -------------------------------------------- | |
| x, y, w, h = values | |
| clipped_x = min(max(x, 0.0), 1.0) | |
| clipped_y = min(max(y, 0.0), 1.0) | |
| clipped_w = min(w, 1.0 - clipped_x) | |
| clipped_h = min(h, 1.0 - clipped_y) | |
| if ( | |
| abs(clipped_x - x) > TOLERANCE | |
| or abs(clipped_y - y) > TOLERANCE | |
| or abs(clipped_w - w) > TOLERANCE | |
| or abs(clipped_h - h) > TOLERANCE | |
| ): | |
| repairs.append("clipped") | |
| canonical = [round(v, 4) for v in (clipped_x, clipped_y, clipped_w, clipped_h)] | |
| return canonical, repairs | |
| def looks_like(bbox: list[float], convention: BoxConvention) -> bool: | |
| """Whether *bbox* is *consistent* with *convention* — never proof of it. | |
| Used by the probe script to weigh hypotheses and by adapters to report | |
| format compliance. A single box rarely settles the question; aggregate over | |
| a whole run before concluding anything. | |
| """ | |
| if len(bbox) != 4: | |
| return False | |
| in_unit = all(-TOLERANCE <= v <= 1.0 + TOLERANCE for v in bbox) | |
| if convention.space == "unit" and not in_unit: | |
| return False | |
| if convention.space == "grid1000" and not all(0 <= v <= 1000 for v in bbox): | |
| return False | |
| # Range checks above are order-blind; the shape check below is not. | |
| order = convention.order | |
| if order == "yxyx": | |
| bbox = [bbox[1], bbox[0], bbox[3], bbox[2]] | |
| order = "xyxy" | |
| scale = _SCALE.get(convention.space, 1.0) | |
| x, y, a, b = (v / scale for v in bbox) | |
| if order == "xywh": | |
| # Extents must be positive and stay inside the frame. | |
| return a > 0 and b > 0 and x + a <= 1.0 + TOLERANCE and y + b <= 1.0 + TOLERANCE | |
| return a > x and b > y | |