"""Schema for the gold-service export used as benchmark ground truth.""" from __future__ import annotations import json from pathlib import Path from typing import Any from pydantic import BaseModel, Field, field_validator, model_validator class GoldViolation(BaseModel): """One independently scored localisation target.""" use_case_id: str use_case_name: str bbox: list[float] = Field(min_length=4, max_length=4) description: str | None = None @field_validator("bbox") @classmethod def validate_bbox(cls, bbox: list[float]) -> list[float]: x, y, width, height = bbox if width < 0 or height < 0: raise ValueError("bbox width and height must be non-negative") if min(x, y) < 0 or max(x + width, y + height) > 1: raise ValueError("bbox must be normalised [x, y, width, height]") return bbox class GoldLabel(BaseModel): plausibility: int | None = Field(default=None, ge=1, le=5) naturalness: int | None = Field(default=None, ge=1, le=5) no_violation_detected: bool violations: list[GoldViolation] = Field(default_factory=list) reported: bool = False report_reason: str | None = None @model_validator(mode="after") def validate_state(self) -> "GoldLabel": if self.reported: if self.violations or self.no_violation_detected: raise ValueError("reported labels cannot contain evaluation targets") return self if self.no_violation_detected == bool(self.violations): raise ValueError("label must contain violations or declare no violation, not both") return self class GoldRecord(BaseModel): image_id: str gold: GoldLabel kind: str base_annotator: str | None = None source_annotators: list[str] = Field(default_factory=list) edit_summary: Any = None agreement_at_gold: dict[str, Any] | None = None adjudicated_by: str | None = None adjudicated_at: str | None = None class GoldDataset(BaseModel): """Validated top-level gold array with unique image identifiers.""" records: list[GoldRecord] @model_validator(mode="after") def validate_unique_ids(self) -> "GoldDataset": ids = [record.image_id for record in self.records] if len(ids) != len(set(ids)): raise ValueError("gold dataset contains duplicate image_id values") return self @classmethod def from_file(cls, path: Path) -> "GoldDataset": payload = json.loads(path.read_text(encoding="utf-8")) if isinstance(payload, dict) and isinstance(payload.get("items"), list): payload = payload["items"] if not isinstance(payload, list): raise ValueError(f"{path} must contain a gold record array") return cls(records=payload)