municipalbench-full / code /schemas /inference.py
Yuquanlee's picture
MunicipalBench dataset files
7825400 verified
Raw History Blame Contribute Delete
5.48 kB
"""Inference response schema — the contract between model adapters and metrics.
Models return a list of DetectionResult dicts per image (COCO-style).
An empty list means no violations were detected.
An empty list is ambiguous on its own, though: it looks identical whether the
model said "no violations" or produced something we failed to parse. Every
response therefore carries a ``parse_status`` recording which of those happened,
so a silent parse failure cannot be mistaken for a clean negative.
"""
from typing import Literal
from pydantic import BaseModel, Field, field_validator
ParseStatus = Literal["ok", "empty", "parse_error", "format_mismatch", "unrecorded"]
"""How the adapter's raw output was interpreted.
* ``ok`` — parsed cleanly, at least one detection
* ``empty`` — parsed cleanly, the model reported no violations (a real answer)
* ``parse_error`` — the output could not be parsed at all
* ``format_mismatch`` — parsed as structured data, but not in the expected shape
* ``unrecorded`` — the adapter did not say. The default, so that results written
before parse tracking existed are not silently upgraded to ``ok``; every
current adapter sets a real status.
"""
FormatSeen = Literal["json", "json_repaired", "yaml", "plain_text", "empty", "other"]
"""The output format actually observed, regardless of what was asked for.
``json_repaired`` means the response was JSON in every respect except that it
would not parse as written — in practice, zero-padded integers like
``"category_id": 03``. Kept distinct from ``json`` because it measures a real
compliance failure, and distinct from ``yaml`` because YAML happens to accept
those literals, which previously made well-formed JSON look like a model
answering in the wrong format entirely.
"""
class DetectionResult(BaseModel):
"""A single detection predicted by a model for one image.
Follows format:
{category_id, bbox, score}
An image with no detections simply has zero ``DetectionResult`` entries.
"""
category_id: int
bbox: list[float] = Field(..., min_length=4, max_length=4)
score: float = Field(ge=0.0, le=1.0)
@field_validator("bbox")
@classmethod
def validate_bbox(cls, v: list[float]) -> list[float]:
"""Ensure bbox has exactly 4 elements [x, y, width, height]."""
if len(v) != 4:
raise ValueError("bbox must have exactly 4 elements [x, y, width, height]")
return v
class InferenceResponse(BaseModel):
"""Wrapper for the full model response for a single image.
This is the single source of truth for the inference→metrics boundary.
The ``detections`` list may be empty if no violations were detected.
"""
image_id: str
detections: list[DetectionResult] = []
raw_text: str | None = None
model_name: str
latency_ms: float
# Parse tracking. The defaults describe an adapter that said nothing, so
# older results stay readable without being credited with a clean parse.
parse_status: ParseStatus = "unrecorded"
format_seen: FormatSeen | None = None
parse_error: str | None = None
# Geometry tracking. ``bbox`` above is always canonical unit [x, y, w, h];
# this records the convention it was converted *from*, and what the
# conversion had to repair. None means the file predates geometry tracking —
# its boxes were stored exactly as the model emitted them and may not be
# canonical at all.
box_convention: str | None = None
box_repairs: dict[str, int] = {}
# What this one image cost, as reported by the provider. ``None`` means no
# cost was reported — a local model, or a provider that does not say — and
# is deliberately distinct from ``0.0``, which claims the call was free.
# Never estimated from token counts: a benchmark that publishes cost per
# image must publish what was actually billed.
cost_usd: float | None = None
# Why generation stopped, as the provider reported it. ``"length"`` means
# the answer was cut off at ``max_tokens`` — a fact about our request, not
# about the model, and the difference between "this model cannot do the
# task" and "we did not let it finish". Reasoning models make that
# distinction load-bearing: they spend the token budget thinking before
# they emit a single character of answer, so a budget that is merely
# generous for a normal model leaves them with an empty ``content`` and a
# results file that reads as total failure. ``None`` means the provider did
# not say, or the adapter is local.
finish_reason: str | None = None
# Optional accounting used by local and hosted multi-pass runs. Older
# result files remain valid because every field is additive.
input_tokens: int | None = None
output_tokens: int | None = None
context_limit: int | None = None
context_headroom: int | None = None
provider_diagnostics: dict = {}
pass_summaries: list[dict] = []
@property
def parsed_cleanly(self) -> bool:
"""Whether the model's output was understood, detections or not."""
return self.parse_status in ("ok", "empty")
class InferenceAttempt(BaseModel):
"""Auditable record of every model call made for one image."""
image_id: str
attempt: int = Field(ge=1)
status: Literal["ok", "failed"]
response: InferenceResponse | None = None
error_type: str | None = None
error: str | None = None