File size: 9,091 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""Metrics engine — orchestrates all metric modules and produces a unified report.

Two primary evaluation tracks:

* **Localisation** — how well the VLM draws bounding boxes and labels them.
* **Classification** — how well the VLM identifies which violations are present.

Additional metric modules (scalar, agreement) are imported dynamically and
run when available.
"""

from utils.result_paths import result_path
from utils.result_paths import relocated_result

import hashlib
import logging
from datetime import datetime, timezone
from pathlib import Path

from schemas.ground_truth import GoldDataset
from schemas.inference import InferenceResponse
from utils.io import read_jsonl, write_json

logger = logging.getLogger(__name__)

PROJECT_ROOT = Path(__file__).resolve().parent.parent
INFERENCE_RESULTS_DIR = PROJECT_ROOT / "results" / "inference"
REPORTS_DIR = PROJECT_ROOT / "results" / "metrics"

DEFAULT_MANIFEST_PATH = (
    PROJECT_ROOT / "data" / "full_dataset" / "cohorts"
    / "one_pass_balanced_up_to_350.gold.json"
)
LOCALISATION_IOU_THRESHOLDS = (0.30, 0.40, 0.50)


# ---------------------------------------------------------------------------
# Empty-report stubs (used when a metric module is unavailable)
# ---------------------------------------------------------------------------


def _empty_localisation() -> dict:
    return {
        "per_violation": {},
        "iou_threshold": 0.5,
        "n_images": 0,
        "n_predictions": 0,
        "n_gt_boxes": 0,
    }


def _empty_classification() -> dict:
    return {
        "per_violation": {},
        "n_images": 0,
    }

# ---------------------------------------------------------------------------
# Dynamic metric loading
# ---------------------------------------------------------------------------

def _try_import_metric(module_name: str, func_name: str):
    """Try to import a metric function; return None if the module is missing."""
    try:
        import importlib
        mod = importlib.import_module(f"metrics.{module_name}")
        return getattr(mod, func_name)
    except (ImportError, AttributeError):
        logger.warning("Metric module '%s' not available — skipping", module_name)
        return None


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------


def _resolve_results_file(target_path: Path) -> Path:
    """Resolve *target_path* to the single results file it names.

    A directory is accepted only when it holds exactly one run. Silently
    scoring the alphabetically last of several is the worst possible failure
    here: it produces a complete, plausible report for a run nobody asked
    about, under a `run_id` that quietly disagrees with the command that was
    typed.
    """
    if not target_path.is_dir():
        if not target_path.exists():
            raise FileNotFoundError(f"Results file not found: {target_path}")
        return target_path

    runs = sorted(
        p for p in target_path.rglob("*.jsonl")
        if not p.name.endswith((".errors.jsonl", ".attempts.jsonl"))
    )
    if not runs:
        raise FileNotFoundError(f"No JSONL results found in directory {target_path}")
    if len(runs) > 1:
        shown = [p.name for p in runs[:10]]
        if len(runs) > len(shown):
            shown.append(f"... and {len(runs) - len(shown)} more")
        raise ValueError(
            f"{target_path} holds {len(runs)} result files — name the one to "
            "score:\n  " + "\n  ".join(shown)
        )
    return runs[0]


def run_metrics(
    results_path: Path | str | None = None,
    manifest_path: Path | str | None = None,
    iou_threshold: float = 0.50,
    image_ids: set[str] | None = None,
    report_suffix: str = "met",
) -> dict:
    """Compute all available metrics for a given inference run.

    Args:
        results_path: Path to the inference results JSONL file (e.g.
            ``results/inference/YYMMDD_NN_modelname.jsonl``) or a filename
            relative to ``results/inference/``. A directory is accepted only
            when it contains exactly one run. Defaults to
            ``results/inference/``.
        manifest_path: Path to the benchmark ground-truth JSON.
        iou_threshold: Minimum IoU for a localisation prediction to count as
            a true positive (default 0.50).

    Returns:
        Unified metrics report dict.

    Raises:
        FileNotFoundError: If the results file or directory holds no run.
        ValueError: If a directory holds more than one run, so which to score
            is ambiguous.
    """
    if results_path is None:
        target_path = INFERENCE_RESULTS_DIR
    else:
        target_path = relocated_result(results_path)
        if not target_path.exists() and Path(results_path).name == str(results_path):
            target_path = result_path(INFERENCE_RESULTS_DIR, str(results_path))

    target_path = _resolve_results_file(target_path)

    # Load data
    predictions = read_jsonl(target_path, InferenceResponse)
    manifest_p = Path(manifest_path) if manifest_path else DEFAULT_MANIFEST_PATH
    dataset = GoldDataset.from_file(manifest_p)
    try:
        ground_truth_file = str(manifest_p.resolve().relative_to(PROJECT_ROOT))
    except ValueError:
        ground_truth_file = str(manifest_p)
    ground_truths = dataset.records
    gt_ids = {record.image_id for record in ground_truths if not record.gold.reported}
    rows_by_id = {prediction.image_id: prediction for prediction in predictions}
    all_valid_predictions = [
        rows_by_id[image_id]
        for image_id in gt_ids
        if image_id in rows_by_id and rows_by_id[image_id].parsed_cleanly
    ]
    valid_predictions = all_valid_predictions
    if image_ids is not None:
        valid_predictions = [
            prediction
            for prediction in all_valid_predictions
            if prediction.image_id in image_ids
        ]
    invalid = sorted(
        image_id
        for image_id in gt_ids
        if image_id in rows_by_id and not rows_by_id[image_id].parsed_cleanly
    )
    missing = sorted(gt_ids - rows_by_id.keys())

    logger.info(
        "Loaded %d predictions and %d ground-truth images from %s",
        len(predictions),
        len(ground_truths),
        target_path.name,
    )

    stem = target_path.stem
    # Stem format: YYMMDD_runID_modelname  (e.g. 260815_04_yolov8m-worldv2)
    # Legacy format without run ID: YYMMDD_modelname  (e.g. 260804_example)
    _parts = stem.split("_", 2)
    if len(_parts) == 3 and _parts[1].isdigit():
        model_name = _parts[2]
    elif len(_parts) >= 2:
        model_name = "_".join(_parts[1:])
    else:
        model_name = stem

    # --- Primary tracks ---
    compute_localisation = _try_import_metric("localisation", "compute_localisation_metrics")
    compute_classification = _try_import_metric("classification", "compute_classification_metrics")

    localisation_thresholds = tuple(sorted(set((*LOCALISATION_IOU_THRESHOLDS, iou_threshold))))
    localisation_sensitivity = (
        {
            f"{threshold:.2f}": compute_localisation(
                valid_predictions, ground_truths, iou_threshold=threshold
            )
            for threshold in localisation_thresholds
        }
        if compute_localisation else {}
    )
    localisation = localisation_sensitivity.get(f"{iou_threshold:.2f}", _empty_localisation())
    classification = (
        compute_classification(
            valid_predictions, ground_truths,
        )
        if compute_classification else _empty_classification()
    )

    report = {
        "run_id": stem,
        "model_name": model_name,
        "computed_at": datetime.now(timezone.utc).isoformat(),
        "n_predictions": len(predictions),
        "n_ground_truth": len(ground_truths),
        "ground_truth_file": ground_truth_file,
        "ground_truth_sha256": hashlib.sha256(manifest_p.read_bytes()).hexdigest(),
        "coverage": {
            "expected": len(gt_ids), "valid": len(all_valid_predictions),
            "invalid": len(invalid), "missing": len(missing),
            "invalid_image_ids": invalid, "missing_image_ids": missing,
        },
        "evaluation_scope": {
            "requested_image_ids": (
                len(image_ids) if image_ids is not None else len(gt_ids)
            ),
            "evaluated_valid": len(valid_predictions),
        },
        "localisation": localisation,
        "localisation_sensitivity": localisation_sensitivity,
        "classification": classification,
    }

    # Save report. The directory is created here rather than assumed: on a
    # fresh checkout `results/metrics/` does not exist, and scoring a run would
    # otherwise fail with a bare FileNotFoundError *after* doing all the work.
    report_path = result_path(REPORTS_DIR, f"{stem}_{report_suffix}.json")
    report_path.parent.mkdir(parents=True, exist_ok=True)
    write_json(report_path, report)

    logger.info("Metrics saved to %s", report_path)
    return report