File size: 2,826 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""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)