Move the five top-level scripts into src/rowing_stats, one module per pipeline stage, behind a single 'rowing-stats' command with a subcommand each (crop, classify, ocr, claude, tune). Add type hints throughout, packaging metadata, pinned requirements files, and a test suite. Failures are now typed exceptions under RowingStatsError instead of prints, None returns and sys.exit: unreadable or missing images, photos with no detectable screen, a missing tesseract binary, tesseract failures, unusable Claude replies, and missing optional dependencies, model weights or API credentials. Each command reports a bad file and carries on, stops once on a setup problem, and returns a non-zero exit code when something failed. Crops, classifier labels and OCR votes are unchanged. Other changes: - crop.find_screen takes a CropParams, so the tuner searches the real detection code instead of a copy of it. - OCR validation scores only images that have a reference reading; images without one were counted as wrong. - 'classify train --data-dir train/' works with the repository layout (it looked for train/train), and the CNN weights path defaults to the committed screen_classifier_model.pth instead of a missing model.pth. - The CNN is loaded once per run rather than once per image. - ocr and claude can write their readings with --output. - crop no longer defaults to /mnt/user-data paths. - Pure vote-counting moved to parsing.py; the unused 'expected' argument that let a caller steer the vote is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
109 lines
4.0 KiB
Python
109 lines
4.0 KiB
Python
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
|