import json import cv2 import numpy as np import pytest from conftest import REPO from rowing_stats import classifier from rowing_stats.errors import ImageLoadError, ModelLoadError FEATURES = {"std_dev", "entropy", "edge_density", "h_line_strength", "mean_saturation", "dark_pixel_ratio", "bright_pixel_ratio", "local_variance"} ROWING = REPO / "train" / "1" / "IMG_5523_screen.jpg" @pytest.fixture def flat_path(tmp_path): """A featureless grey image: nothing like a display.""" path = tmp_path / "flat.png" cv2.imwrite(str(path), np.full((200, 200, 3), 128, dtype=np.uint8)) return path def test_extract_features(flat_path): feats = classifier.extract_features(flat_path) assert set(feats) == FEATURES assert feats["std_dev"] == 0.0 assert feats["edge_density"] < 0.05 # only the image border registers assert feats["mean_saturation"] == 0.0 def test_extract_features_handles_black_pixels_without_warning(tmp_path): path = tmp_path / "black.png" cv2.imwrite(str(path), np.zeros((50, 50, 3), dtype=np.uint8)) with np.errstate(all="raise"): # saturation divides by the max channel assert classifier.extract_features(path)["mean_saturation"] == 0.0 def test_feature_classifier_tells_a_display_from_a_flat_image(flat_path): assert classifier.feature_based_predict(ROWING)[0] == 1 label, confidence = classifier.feature_based_predict(flat_path) assert label == 0 assert 0.5 <= confidence <= 1.0 def test_unreadable_image(corrupt_path, tmp_path): with pytest.raises(ImageLoadError, match="not a readable image"): classifier.extract_features(corrupt_path) with pytest.raises(ImageLoadError, match="file not found"): classifier.feature_based_predict(tmp_path / "missing.jpg") def test_cli_predict_dir_skips_unreadable_files(flat_path, corrupt_path, capsys): code = classifier.main(["predict", "--dir", str(flat_path.parent)]) captured = capsys.readouterr() assert code == 1 assert "flat.png → NOT ROWING MACHINE" in captured.out assert "Summary: 1 images | 0 rowing | 1 not rowing" in captured.out assert "corrupt.jpg: not a readable image" in captured.err def test_cli_extract_prints_features(flat_path, capsys): assert classifier.main(["extract", "--image", str(flat_path)]) == 0 assert set(json.loads(capsys.readouterr().out)) == FEATURES def test_cli_predict_requires_exactly_one_target(flat_path): with pytest.raises(SystemExit): classifier.main(["predict"]) with pytest.raises(SystemExit): classifier.main(["predict", "--image", str(flat_path), "--dir", "."]) # --- CNN (needs the ml extra) ------------------------------------------------ def test_cnn_predict_with_the_committed_weights(): pytest.importorskip("torchvision") model_path = REPO / classifier.DEFAULT_MODEL_PATH label, confidence = classifier.cnn_predict(ROWING, model_path) assert label == 1 and confidence > 0.5 not_rowing = sorted((REPO / "train" / "0").iterdir())[0] assert classifier.cnn_predict(not_rowing, model_path)[0] == 0 def test_cnn_missing_or_invalid_weights(tmp_path, capsys): pytest.importorskip("torchvision") with pytest.raises(ModelLoadError, match="not found"): classifier.cnn_predict(ROWING, tmp_path / "nope.pth") garbage = tmp_path / "garbage.pth" garbage.write_bytes(b"not a checkpoint") with pytest.raises(ModelLoadError, match="could not load"): classifier.cnn_predict(ROWING, garbage) # The CLI reports it once and stops, rather than once per image code = classifier.main(["predict", "--dir", str(ROWING.parent), "--model", "cnn", "--model-path", str(tmp_path / "nope.pth")]) assert code == 1 assert capsys.readouterr().err.count("CNN weights not found") == 1 def test_train_rejects_a_directory_without_class_folders(tmp_path, capsys): pytest.importorskip("torchvision") assert classifier.main(["train", "--data-dir", str(tmp_path)]) == 1 assert "must contain 0/ and 1/" in capsys.readouterr().err