Yuquanlee's picture
MunicipalBench dataset files
7825400 verified
Raw History Blame Contribute Delete
9.09 kB
"""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