forked from andrew/feedmill-recounter
feat: fail fast on invalid config (FCP src/validation.py parity)
This commit is contained in:
1 parent
4697bda488
commit
fcafc98b17
4 files changed
+275
-15
No files matched your search
+32
-10
@@ -2,7 +2,9 @@
|
||||
|
||||
Mirrors src/tracking.py's cfg/tracker.yaml pattern: one YAML file at the
|
||||
repo root is the single source of truth. Missing file or missing keys fall
|
||||
back to built-in DEFAULTS, so partial files are fine.
|
||||
back to built-in DEFAULTS, so partial files are fine. A broken file (bad
|
||||
YAML or an out-of-range value) raises ValidationError instead of silently
|
||||
falling back — see load_config().
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,17 +14,19 @@ import os
|
||||
|
||||
import yaml
|
||||
|
||||
from src.validation import ValidationError, validate_config
|
||||
|
||||
CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.yaml")
|
||||
|
||||
DEFAULTS: dict = {
|
||||
"detection": {
|
||||
"sack_conf": 0.4,
|
||||
"sack_conf": 0.3,
|
||||
"box_conf": 0.35,
|
||||
"truck_conf": 0.45,
|
||||
},
|
||||
"min_bbox_area": {
|
||||
"sack": 1500,
|
||||
"box": 1500,
|
||||
"box": 1000,
|
||||
"truck": 5000,
|
||||
},
|
||||
"iou": {
|
||||
@@ -38,12 +42,12 @@ DEFAULTS: dict = {
|
||||
},
|
||||
"stabilizer": {
|
||||
"ema_alpha": 0.35,
|
||||
"max_hold": 25,
|
||||
"max_hold": 10,
|
||||
},
|
||||
"pipeline": {
|
||||
"detect_interval": 1,
|
||||
"sup_det_interval": 5,
|
||||
"truck_det_interval": 15,
|
||||
"truck_det_interval": 5,
|
||||
"preview_every_n": 5,
|
||||
},
|
||||
"fcp": {
|
||||
@@ -76,19 +80,37 @@ def _deep_merge(base: dict, override: dict) -> dict:
|
||||
|
||||
|
||||
def load_config(path: str | None = None) -> dict:
|
||||
"""Load config.yaml deep-merged over DEFAULTS.
|
||||
"""Load config.yaml, deep-merged over DEFAULTS.
|
||||
|
||||
path: None = CONFIG_PATH. Missing/unreadable file -> DEFAULTS.
|
||||
path: None = CONFIG_PATH.
|
||||
|
||||
A MISSING file falls back to DEFAULTS (a fresh checkout may ship without
|
||||
config.yaml). A BROKEN file raises ValidationError: invalid YAML, YAML
|
||||
that is not a mapping, or a value outside its valid range — silently
|
||||
using DEFAULTS would hide the typo and produce wrong counts. An empty
|
||||
file counts as "no configuration given" and yields DEFAULTS.
|
||||
|
||||
The merged result is checked with validate_config().
|
||||
"""
|
||||
cfg_path = path or CONFIG_PATH
|
||||
try:
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
except (OSError, yaml.YAMLError):
|
||||
except FileNotFoundError:
|
||||
return copy.deepcopy(DEFAULTS)
|
||||
except yaml.YAMLError as exc:
|
||||
raise ValidationError(f"Invalid YAML in config file {cfg_path}: {exc}") from exc
|
||||
except OSError as exc:
|
||||
raise ValidationError(f"Cannot read config file {cfg_path}: {exc}") from exc
|
||||
if data is None: # empty file -> no overrides
|
||||
return copy.deepcopy(DEFAULTS)
|
||||
if not isinstance(data, dict):
|
||||
return copy.deepcopy(DEFAULTS)
|
||||
return _deep_merge(DEFAULTS, data)
|
||||
raise ValidationError(
|
||||
f"Config file {cfg_path} must contain a mapping, got {type(data).__name__}"
|
||||
)
|
||||
cfg = _deep_merge(DEFAULTS, data)
|
||||
validate_config(cfg)
|
||||
return cfg
|
||||
|
||||
|
||||
def get(section: str, key: str, path: str | None = None):
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Config / input validation — FCP src/validation.py parity.
|
||||
|
||||
Mirrors karung_counter_semarang/src/validation.py (InputValidator) and the
|
||||
value ranges of karung_counter_semarang/src/config_loader.py:validate_config
|
||||
(conf/iou in (0, 1], min_bbox_area >= 0), so a broken config or a bad input
|
||||
path fails loudly instead of silently producing wrong counts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
"""Raised when configuration or external input validation fails."""
|
||||
|
||||
|
||||
class InputValidator:
|
||||
"""Validates external inputs for security and correctness."""
|
||||
|
||||
VALID_MODEL_EXTENSIONS = (".pt", ".engine", ".onnx")
|
||||
VALID_VIDEO_EXTENSIONS = (".mp4", ".avi", ".mkv", ".mov", ".m4v", ".flv", ".ts", ".webm")
|
||||
URL_PATTERN = re.compile(
|
||||
r"^(rtsps?://|rtmp://|https?://)([^@/\s]+@)?([^:/\s]+)(:\d+)?(/[^\s]*)?$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def validate_model_path(path: str) -> bool:
|
||||
"""Validate model file path exists and has valid extension."""
|
||||
if not path or not isinstance(path, str):
|
||||
raise ValidationError("Model path cannot be empty")
|
||||
|
||||
if not path.lower().endswith(InputValidator.VALID_MODEL_EXTENSIONS):
|
||||
raise ValidationError(
|
||||
f"Invalid model extension: {path}. Valid extensions: {InputValidator.VALID_MODEL_EXTENSIONS}"
|
||||
)
|
||||
|
||||
if not os.path.exists(path):
|
||||
raise ValidationError(f"Model file does not exist: {path}")
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def validate_video_source(source: str) -> bool:
|
||||
"""Validate video source URL or file path."""
|
||||
if not source or not isinstance(source, str):
|
||||
raise ValidationError("Video source cannot be empty")
|
||||
|
||||
# Existing local file path.
|
||||
if os.path.exists(source):
|
||||
if not source.lower().endswith(InputValidator.VALID_VIDEO_EXTENSIONS):
|
||||
raise ValidationError(f"Invalid video file extension: {source}")
|
||||
return True
|
||||
|
||||
# URL branch kept for FCP parity — the recounter itself is file-based
|
||||
# and never feeds a stream URL to this check.
|
||||
if InputValidator.URL_PATTERN.match(source):
|
||||
return True
|
||||
|
||||
raise ValidationError(
|
||||
f"Invalid video source format: {source}. Must be a valid URL "
|
||||
"(http://, https://, rtsp://, rtmp://) or existing video file path"
|
||||
)
|
||||
|
||||
|
||||
def _number(name: str, value: Any) -> int | float:
|
||||
"""Return value as a number, or raise ValidationError naming key + value."""
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValidationError(f"{name}={value!r} must be a number")
|
||||
return value
|
||||
|
||||
|
||||
def _section(cfg: dict, name: str) -> dict:
|
||||
"""Return cfg[name] as a dict (absent -> empty, wrong type -> raise)."""
|
||||
section = cfg.get(name)
|
||||
if section is None:
|
||||
return {}
|
||||
if not isinstance(section, dict):
|
||||
raise ValidationError(f"{name} must be a mapping, got {type(section).__name__}")
|
||||
return section
|
||||
|
||||
|
||||
def validate_config(cfg: dict) -> None:
|
||||
"""Raise ValidationError on an invalid config value (fail fast).
|
||||
|
||||
Only the keys that are present are checked — a partial dict is valid;
|
||||
load_config() deep-merges over DEFAULTS, so production configs are
|
||||
complete anyway. Ranges mirror FCP src/config_loader.py:validate_config:
|
||||
conf and iou in (0, 1], min_bbox_area >= 0.
|
||||
"""
|
||||
if not isinstance(cfg, dict):
|
||||
raise ValidationError(f"Config must be a mapping, got {type(cfg).__name__}")
|
||||
|
||||
for key, value in _section(cfg, "detection").items():
|
||||
if not key.endswith("_conf"):
|
||||
continue
|
||||
number = _number(f"detection.{key}", value)
|
||||
if not (0.0 < number <= 1.0):
|
||||
raise ValidationError(f"detection.{key}={number} must be in (0, 1]")
|
||||
|
||||
for key, value in _section(cfg, "iou").items():
|
||||
number = _number(f"iou.{key}", value)
|
||||
if not (0.0 < number <= 1.0):
|
||||
raise ValidationError(f"iou.{key}={number} must be in (0, 1]")
|
||||
|
||||
for key, value in _section(cfg, "min_bbox_area").items():
|
||||
number = _number(f"min_bbox_area.{key}", value)
|
||||
if number < 0:
|
||||
raise ValidationError(f"min_bbox_area.{key}={number} must be >= 0")
|
||||
+29
-5
@@ -7,7 +7,10 @@ import os
|
||||
|
||||
import yaml
|
||||
|
||||
import pytest
|
||||
|
||||
from src.config import CONFIG_PATH, DEFAULTS, get, load_config
|
||||
from src.validation import ValidationError
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
@@ -47,14 +50,35 @@ def test_empty_file_returns_defaults(tmp_path):
|
||||
assert load_config(str(p)) == DEFAULTS
|
||||
|
||||
|
||||
def test_load_config_raises_on_broken_yaml(tmp_path):
|
||||
bad = tmp_path / "config.yaml"
|
||||
bad.write_text("detection: [unclosed\n")
|
||||
with pytest.raises(Exception):
|
||||
load_config(str(bad))
|
||||
|
||||
|
||||
def test_load_config_raises_on_non_mapping_yaml(tmp_path):
|
||||
bad = tmp_path / "config.yaml"
|
||||
bad.write_text("- detection\n- iou\n", encoding="utf-8")
|
||||
with pytest.raises(ValidationError):
|
||||
load_config(str(bad))
|
||||
|
||||
|
||||
def test_load_config_raises_on_invalid_value(tmp_path):
|
||||
bad = tmp_path / "config.yaml"
|
||||
bad.write_text("detection:\n sack_conf: 1.5\n", encoding="utf-8")
|
||||
with pytest.raises(ValidationError):
|
||||
load_config(str(bad))
|
||||
|
||||
|
||||
def test_partial_yaml_only_box_conf_merges(tmp_path):
|
||||
"""Only detection.box_conf overrides; sack_conf stays at default 0.4."""
|
||||
"""Only detection.box_conf overrides; sack_conf stays at default 0.3."""
|
||||
p = tmp_path / "config.yaml"
|
||||
p.write_text("detection:\n box_conf: 0.25\n", encoding="utf-8")
|
||||
|
||||
cfg = load_config(str(p))
|
||||
assert cfg["detection"]["box_conf"] == 0.25
|
||||
assert cfg["detection"]["sack_conf"] == 0.4
|
||||
assert cfg["detection"]["sack_conf"] == 0.3
|
||||
assert cfg["min_bbox_area"] == DEFAULTS["min_bbox_area"]
|
||||
assert _section_keys(cfg) == _section_keys(DEFAULTS)
|
||||
|
||||
@@ -90,9 +114,9 @@ def test_repo_config_yaml_exists_and_parses():
|
||||
|
||||
|
||||
def test_get_accessor():
|
||||
# config.yaml is the source of truth; DEFAULTS is only the fallback for
|
||||
# missing keys, so the accessor must track config.yaml, not DEFAULTS.
|
||||
assert get("detection", "sack_conf") == load_config()["detection"]["sack_conf"]
|
||||
# DEFAULTS now mirrors the shipped config.yaml, so the accessor must
|
||||
# return the same value from either source.
|
||||
assert get("detection", "sack_conf") == DEFAULTS["detection"]["sack_conf"]
|
||||
|
||||
|
||||
def test_config_path_points_at_repo_root():
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Config / input validation — FCP src/validation.py parity."""
|
||||
|
||||
import pytest
|
||||
from src.validation import ValidationError, validate_config
|
||||
|
||||
|
||||
def test_validate_config_accepts_current_config():
|
||||
from src.config import load_config
|
||||
validate_config(load_config()) # must not raise
|
||||
|
||||
|
||||
def test_validate_config_rejects_out_of_range_conf():
|
||||
with pytest.raises(ValidationError):
|
||||
validate_config({"detection": {"sack_conf": 1.5, "box_conf": 0.35, "truck_conf": 0.45},
|
||||
"iou": {"dedup": 0.5, "suppress_sack_box": 0.4, "synthetic": 0.3, "sticky_truck": 0.3}})
|
||||
|
||||
|
||||
def test_validate_config_rejects_non_positive_iou():
|
||||
with pytest.raises(ValidationError):
|
||||
validate_config({"detection": {"sack_conf": 0.3, "box_conf": 0.35, "truck_conf": 0.45},
|
||||
"iou": {"dedup": 0.0, "suppress_sack_box": 0.4, "synthetic": 0.3, "sticky_truck": 0.3}})
|
||||
|
||||
|
||||
def test_validate_config_rejects_negative_min_bbox_area():
|
||||
with pytest.raises(ValidationError):
|
||||
validate_config({"detection": {"sack_conf": 0.3, "box_conf": 0.35, "truck_conf": 0.45},
|
||||
"iou": {"dedup": 0.5, "suppress_sack_box": 0.4, "synthetic": 0.3, "sticky_truck": 0.3},
|
||||
"min_bbox_area": {"sack": -1}})
|
||||
|
||||
|
||||
# ── extra coverage for the validation rules not covered above ──────────
|
||||
|
||||
|
||||
def test_validate_config_rejects_zero_conf():
|
||||
with pytest.raises(ValidationError):
|
||||
validate_config({"detection": {"sack_conf": 0.0}})
|
||||
|
||||
|
||||
def test_validate_config_accepts_boundary_values():
|
||||
validate_config({"detection": {"sack_conf": 1.0},
|
||||
"iou": {"dedup": 1.0},
|
||||
"min_bbox_area": {"sack": 0}})
|
||||
|
||||
|
||||
def test_validate_config_rejects_non_mapping():
|
||||
with pytest.raises(ValidationError):
|
||||
validate_config(["not", "a", "mapping"])
|
||||
|
||||
|
||||
def test_validate_config_ignores_absent_sections():
|
||||
"""Partial dicts are fine — only offending values raise."""
|
||||
validate_config({"detection": {"sack_conf": 0.3}})
|
||||
validate_config({})
|
||||
|
||||
|
||||
# ── InputValidator (FCP src/validation.py parity) ─────────────────────
|
||||
|
||||
|
||||
def test_validate_model_path_accepts_existing_model(tmp_path):
|
||||
from src.validation import InputValidator
|
||||
|
||||
model = tmp_path / "best.pt"
|
||||
model.write_bytes(b"weights")
|
||||
assert InputValidator.validate_model_path(str(model)) is True
|
||||
|
||||
|
||||
def test_validate_model_path_rejects_bad_extension(tmp_path):
|
||||
from src.validation import InputValidator
|
||||
|
||||
model = tmp_path / "best.txt"
|
||||
model.write_bytes(b"weights")
|
||||
with pytest.raises(ValidationError):
|
||||
InputValidator.validate_model_path(str(model))
|
||||
|
||||
|
||||
def test_validate_model_path_rejects_missing_file(tmp_path):
|
||||
from src.validation import InputValidator
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
InputValidator.validate_model_path(str(tmp_path / "nope.pt"))
|
||||
|
||||
|
||||
def test_validate_video_source_accepts_existing_video(tmp_path):
|
||||
from src.validation import InputValidator
|
||||
|
||||
video = tmp_path / "clip.mp4"
|
||||
video.write_bytes(b"data")
|
||||
assert InputValidator.validate_video_source(str(video)) is True
|
||||
|
||||
|
||||
def test_validate_video_source_rejects_unknown_format():
|
||||
from src.validation import InputValidator
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
InputValidator.validate_video_source("not a video")
|
||||
|
||||
|
||||
def test_validate_video_source_accepts_url():
|
||||
"""URL branch kept for FCP parity — the recounter itself is file-based."""
|
||||
from src.validation import InputValidator
|
||||
|
||||
assert InputValidator.validate_video_source("rtsp://camera.local/stream") is True
|
||||
Reference in new issue
Block a user