Restructure scripts into the rowing_stats package

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]>
This commit is contained in:
2026-10-09 12:08:01 +01:00
co-authored by Claude Opus 5.5
parent c447cc41ea
commit 7b19d8f3e9
31 changed files with 2572 additions and 1086 deletions
+32
View File
@@ -0,0 +1,32 @@
from pathlib import Path
import cv2
import numpy as np
import pytest
REPO = Path(__file__).parent.parent
@pytest.fixture
def photo() -> np.ndarray:
"""A synthetic photo: dark wall, one bright 'screen' with digits on it."""
image = np.full((600, 800, 3), 40, dtype=np.uint8)
cv2.rectangle(image, (300, 200), (500, 380), (220, 220, 220), thickness=-1)
for row, text in enumerate(["30:06", "7283", "2:04"]):
cv2.putText(image, text, (320, 250 + row * 50), cv2.FONT_HERSHEY_SIMPLEX,
1.2, (20, 20, 20), 3)
return image
@pytest.fixture
def photo_path(tmp_path: Path, photo: np.ndarray) -> Path:
path = tmp_path / "IMG_0001.jpg"
cv2.imwrite(str(path), photo)
return path
@pytest.fixture
def corrupt_path(tmp_path: Path) -> Path:
path = tmp_path / "corrupt.jpg"
path.write_text("this is not a JPEG")
return path
+108
View File
@@ -0,0 +1,108 @@
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
+253
View File
@@ -0,0 +1,253 @@
"""Tests for the Claude reader.
No Claude call happens here: `claude._client` is replaced with a fake whose
`messages.create` returns a canned reply, so what is under test is everything
around the call - the request that is built, how the reply is parsed and
validated, and how failures are reported.
"""
import base64
from pathlib import Path
from types import SimpleNamespace
import pytest
from PIL import Image
from rowing_stats import claude
from rowing_stats.errors import ClaudeUnavailableError, ExtractionError, ImageLoadError
GOOD_REPLY = '{"timeMinutes": 30, "timeSeconds": 6, "distance": 7283}'
def text_reply(text):
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
@pytest.fixture
def fake_claude(monkeypatch):
"""Stand in for the Anthropic client; returns the list of calls it received.
Set `fake_claude.reply` to a message-like object, or to an exception
instance to have the call raise it.
"""
pytest.importorskip("anthropic")
state = SimpleNamespace(calls=[], reply=text_reply(GOOD_REPLY))
def create(**kwargs):
state.calls.append(kwargs)
if isinstance(state.reply, Exception):
raise state.reply
return state.reply
client = SimpleNamespace(messages=SimpleNamespace(create=create))
monkeypatch.setattr(claude, "_client", lambda: client)
return state
@pytest.fixture
def dated_photo(tmp_path) -> Path:
path = tmp_path / "IMG_5413.jpeg"
img = Image.new("RGB", (8, 8), "white")
exif = img.getexif()
exif[claude.ExifBase.DateTime] = "2025:11:05 12:08:00"
img.save(path, exif=exif)
return path
# --- reply parsing ----------------------------------------------------------
@pytest.mark.parametrize("raw, expected", [
('{"a": 1}', '{"a": 1}'),
(' {"a": 1}\n', '{"a": 1}'),
('```json\n{"a": 1}\n```', '{"a": 1}'),
('```\n{"a": 1}\n```', '{"a": 1}'),
('```json\n{"a": 1}', '{"a": 1}'),
])
def test_strip_markdown_fence(raw, expected):
assert claude.strip_markdown_fence(raw) == expected
def test_parse_reply():
assert claude.parse_reply(GOOD_REPLY) == (30, 6, 7283)
assert claude.parse_reply(f"```json\n{GOOD_REPLY}\n```") == (30, 6, 7283)
assert claude.parse_reply('{"timeMinutes": "30", "timeSeconds": 6.0, "distance": 7283}') \
== (30, 6, 7283)
@pytest.mark.parametrize("raw", [
"I can't read that display.",
"",
'{"timeMinutes": 30, "timeSeconds": 6}', # key missing
'{"timeMinutes": null, "timeSeconds": 6, "distance": 7283}',
'{"timeMinutes": "thirty", "timeSeconds": 6, "distance": 7283}',
"[30, 6, 7283]", # not an object
])
def test_parse_reply_rejects_anything_else(raw):
with pytest.raises(ExtractionError, match="Unparseable reply"):
claude.parse_reply(raw)
# --- sanity bounds ----------------------------------------------------------
def test_validate_reading_derives_metrics():
data = claude.validate_reading(30, 6, 7283)
assert data.total_seconds == 1806
assert data.time_per_500m == 123.99
assert data.calories == 485.53
assert data.date_taken is None
@pytest.mark.parametrize("minutes, seconds, distance, message", [
(30, 6, 0, "Invalid distance: 0"),
(0, 25, 99, "Anomalous distance: 99"),
(30, 6, 100_001, "Anomalous distance"),
(0, 29, 100, "Anomalous time: 29s"),
(120, 1, 30_000, "Anomalous time: 7201s"),
(30, 6, 12_000, "Anomalous pace"), # 1:15 /500m: faster than anyone rows
(30, 6, 5_000, "Anomalous pace"), # 3:01 /500m: a digit was dropped
(30, 6, 728, "Anomalous pace"),
])
def test_validate_reading_rejects_implausible_values(minutes, seconds, distance, message):
with pytest.raises(ExtractionError, match=message):
claude.validate_reading(minutes, seconds, distance)
@pytest.mark.parametrize("minutes, seconds, distance", [
(0, 30, 150), # shortest allowed, 1:40 pace
(120, 0, 30_000), # two hours exactly, 2:00 pace
(40, 0, 15_000), # 1:20 pace exactly
(50, 0, 10_000), # 2:30 pace exactly
])
def test_validate_reading_accepts_the_boundaries(minutes, seconds, distance):
assert claude.validate_reading(minutes, seconds, distance).distance == distance
# --- dates and file selection -----------------------------------------------
@pytest.mark.parametrize("raw, expected", [
("2025:11:05 12:08:00", "2025-11-05 12:08:00"),
(" 2025:11:05 12:08:00 ", "2025-11-05 12:08:00"),
("yesterday", None),
("", None),
(None, None),
])
def test_format_exif_date(raw, expected):
assert claude.format_exif_date(raw) == expected
def test_get_exif_date(dated_photo, tmp_path, corrupt_path):
assert claude.get_exif_date(dated_photo) == "2025:11:05 12:08:00"
undated = tmp_path / "undated.png"
Image.new("RGB", (8, 8)).save(undated)
assert claude.get_exif_date(undated) is None
with pytest.raises(ImageLoadError):
claude.get_exif_date(corrupt_path)
def test_keep_latest_versions():
names = ["IMG_1_screen.jpg", "IMG_1_screen (1).jpg", "IMG_1_screen (3).jpg",
"IMG_2_screen (10).jpg", "IMG_2_screen (9).jpg", "IMG_3_screen.jpg"]
kept = claude._keep_latest_versions([Path(n) for n in names])
assert [p.name for p in kept] == [
"IMG_1_screen (3).jpg", "IMG_2_screen (10).jpg", "IMG_3_screen.jpg"]
# --- the call ---------------------------------------------------------------
def test_extract_rowing_data_sends_image_then_prompt(fake_claude, dated_photo):
data = claude.extract_rowing_data(dated_photo)
assert (data.time_minutes, data.time_seconds, data.distance) == (30, 6, 7283)
assert data.date_taken == "2025:11:05 12:08:00"
(call,) = fake_claude.calls
assert call["model"] == claude.MODEL
image, prompt = call["messages"][0]["content"]
assert image["source"]["media_type"] == "image/jpeg"
assert base64.standard_b64decode(image["source"]["data"]) == dated_photo.read_bytes()
assert prompt == {"type": "text", "text": claude.PROMPT}
def test_bad_images_never_reach_the_api(fake_claude, tmp_path, corrupt_path):
heic = tmp_path / "photo.heic"
heic.touch()
with pytest.raises(ImageLoadError, match="unsupported image type"):
claude.extract_rowing_data(heic)
with pytest.raises(ImageLoadError, match="not a readable image"):
claude.extract_rowing_data(corrupt_path)
with pytest.raises(ImageLoadError, match="file not found"):
claude.extract_rowing_data(tmp_path / "missing.jpg")
assert fake_claude.calls == []
def test_unusable_replies(fake_claude, dated_photo):
fake_claude.reply = SimpleNamespace(content=[])
with pytest.raises(ExtractionError, match="Empty response"):
claude.extract_rowing_data(dated_photo)
fake_claude.reply = text_reply('{"timeMinutes": 30, "timeSeconds": 6, "distance": 728}')
with pytest.raises(ExtractionError, match="Anomalous pace"):
claude.extract_rowing_data(dated_photo)
def _api_error(cls, status):
import httpx2 as httpx
request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
return cls("nope", response=httpx.Response(status, request=request), body=None)
def test_api_failures_are_reported_per_image(fake_claude, dated_photo):
import anthropic
import httpx2 as httpx
fake_claude.reply = _api_error(anthropic.RateLimitError, 429)
with pytest.raises(ExtractionError, match="Claude API error 429"):
claude.extract_rowing_data(dated_photo)
fake_claude.reply = anthropic.APIConnectionError(
request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"))
with pytest.raises(ExtractionError, match="unreachable"):
claude.extract_rowing_data(dated_photo)
def test_credential_problems_stop_the_run(fake_claude, dated_photo, capsys):
import anthropic
fake_claude.reply = _api_error(anthropic.AuthenticationError, 401)
with pytest.raises(ClaudeUnavailableError, match="rejected the credentials"):
claude.extract_rowing_data(dated_photo)
fake_claude.reply = TypeError("Could not resolve authentication method.")
with pytest.raises(ClaudeUnavailableError, match="ANTHROPIC_API_KEY"):
claude.extract_rowing_data(dated_photo)
# From the CLI: reported once, not once per image
Image.new("RGB", (8, 8)).save(dated_photo.with_name("second.png"))
assert claude.main(["--dir", str(dated_photo.parent)]) == 1
assert len(fake_claude.calls) == 3
assert capsys.readouterr().err.count("ANTHROPIC_API_KEY") == 1
def test_an_unrelated_type_error_is_not_swallowed(fake_claude, dated_photo):
fake_claude.reply = TypeError("unexpected keyword argument")
with pytest.raises(TypeError):
claude.extract_rowing_data(dated_photo)
def test_cli_writes_the_results_csv(fake_claude, dated_photo, corrupt_path, capsys):
output = dated_photo.parent / "results.csv"
code = claude.main(["--dir", str(dated_photo.parent), "--output", str(output)])
out = capsys.readouterr().out
assert code == 1 # the corrupt file failed
assert "ERROR: corrupt.jpg: not a readable image" in out
assert "Time: 30:06" in out and "Pace: 2:04.0 /500m" in out
assert output.read_text().splitlines() == [
"image,time,distance_m,pace_per_500m,calories,date_taken",
"IMG_5413.jpeg,30:06,7283,2:04.0,486,2025-11-05 12:08:00",
]
+24
View File
@@ -0,0 +1,24 @@
from rowing_stats import cli
def test_no_command_prints_usage(capsys):
assert cli.main([]) == 2
out = capsys.readouterr().out
for command in cli.COMMANDS:
assert command in out
def test_help(capsys):
assert cli.main(["--help"]) == 0
assert "usage: rowing-stats" in capsys.readouterr().out
def test_unknown_command(capsys):
assert cli.main(["frobnicate"]) == 2
assert "unknown command 'frobnicate'" in capsys.readouterr().err
def test_dispatches_to_the_subcommand(tmp_path, capsys):
# An empty directory: the crop command runs and reports there is nothing to do
assert cli.main(["crop", str(tmp_path)]) == 1
assert "No images found" in capsys.readouterr().err
+84
View File
@@ -0,0 +1,84 @@
import cv2
import numpy as np
import pytest
from rowing_stats import crop
from rowing_stats.crop import CropParams, crop_screen, find_screen, order_corners
from rowing_stats.errors import ImageLoadError, ScreenNotFoundError
def test_order_corners_returns_tl_tr_br_bl():
shuffled = np.array([[90, 80], [10, 15], [12, 85], [95, 12]], dtype="float32")
assert order_corners(shuffled).tolist() == [[10, 15], [95, 12], [90, 80], [12, 85]]
def test_find_screen_locates_the_display(photo):
screen = find_screen(photo)
assert screen is not None
# The fixture draws the display at (300, 200)-(500, 380)
assert abs(screen.x - 300) <= 5 and abs(screen.y - 200) <= 5
assert abs(screen.w - 200) <= 10 and abs(screen.h - 180) <= 10
def test_find_screen_blank_image_is_none():
assert find_screen(np.full((600, 800, 3), 40, dtype=np.uint8)) is None
def test_find_screen_ignores_a_bright_region_with_no_content():
# A window or wall: right size and shape, but no text edges inside it
image = np.full((600, 800, 3), 40, dtype=np.uint8)
cv2.rectangle(image, (300, 200), (500, 380), (220, 220, 220), thickness=-1)
assert find_screen(image) is None
def test_find_screen_respects_params(photo):
assert find_screen(photo, CropParams(area_ratio_min=0.1)) is None
assert find_screen(photo, CropParams(aspect_max=1.0)) is None
assert find_screen(photo, CropParams(edge_density_min=0.9)) is None
def test_crop_screen_writes_padded_crop(photo_path, tmp_path):
out = tmp_path / "crop.jpg"
w, h = crop_screen(photo_path, out, padding=15)
saved = cv2.imread(str(out))
assert saved.shape[:2] == (h + 30, w + 30)
assert saved.mean() > 120 # the light display, not the dark wall
def test_crop_screen_unreadable_image(corrupt_path, tmp_path):
with pytest.raises(ImageLoadError, match="not a readable image"):
crop_screen(corrupt_path, tmp_path / "out.jpg")
with pytest.raises(ImageLoadError, match="file not found"):
crop_screen(tmp_path / "missing.jpg", tmp_path / "out.jpg")
assert not (tmp_path / "out.jpg").exists()
def test_crop_screen_no_screen(tmp_path):
blank = tmp_path / "blank.jpg"
cv2.imwrite(str(blank), np.full((600, 800, 3), 40, dtype=np.uint8))
with pytest.raises(ScreenNotFoundError):
crop_screen(blank, tmp_path / "out.jpg")
def test_cli_reports_each_file_and_keeps_going(photo_path, corrupt_path, tmp_path, capsys):
blank = tmp_path / "blank.jpg"
cv2.imwrite(str(blank), np.full((600, 800, 3), 40, dtype=np.uint8))
out_dir = tmp_path / "out"
code = crop.main([str(tmp_path), str(out_dir)])
out = capsys.readouterr().out
assert code == 1 # one file was unreadable
assert "OK: IMG_0001.jpg -> IMG_0001_screen.jpg" in out
assert "SKIP: No screen detected in blank.jpg" in out
assert "ERROR: corrupt.jpg: not a readable image" in out
assert "Done: 1/3 screens cropped" in out
assert [p.name for p in out_dir.iterdir()] == ["IMG_0001_screen.jpg"]
def test_cli_no_images(tmp_path, capsys):
assert crop.main([str(tmp_path)]) == 1
assert crop.main([str(tmp_path / "missing")]) == 1
err = capsys.readouterr().err
assert "No images found" in err and "is not a directory" in err
+171
View File
@@ -0,0 +1,171 @@
import shutil
import subprocess
from pathlib import Path
import cv2
import numpy as np
import pytest
from conftest import REPO
from rowing_stats import ocr
from rowing_stats.errors import ImageLoadError, OcrError, TesseractNotInstalledError
VARIANT_LABELS = ["s2_clahe_t120", "s2_clahe_t130", "s2_otsu", "s2_otsu_inv",
"s3_otsu", "s3_otsu_inv"]
@pytest.fixture
def screen_path(tmp_path: Path, photo: np.ndarray) -> Path:
path = tmp_path / "IMG_0001_screen.jpg"
cv2.imwrite(str(path), photo[200:380, 300:500])
return path
@pytest.fixture
def fake_tesseract(monkeypatch):
"""Replace the tesseract call with canned texts, one per variant in order."""
texts = ["30:06\n7283", "30:06\n7288", "30:06\n7283", "", "38:06\n7283", "30:06"]
calls = iter(texts * 10)
monkeypatch.setattr(ocr, "ocr_image", lambda img: next(calls))
def test_preprocess_variants(photo):
variants = ocr.preprocess_variants(photo)
assert [label for label, _ in variants] == VARIANT_LABELS
for label, img in variants:
scale = int(label[1])
assert img.shape == (600 * scale, 800 * scale)
assert set(np.unique(img).tolist()) <= {0, 255} # binarised
by_label = dict(variants)
assert np.array_equal(by_label["s3_otsu_inv"], 255 - by_label["s3_otsu"])
def test_extract_screen_data_takes_the_majority(screen_path, fake_tesseract):
reading = ocr.extract_screen_data(screen_path)
assert reading.time == "30:06"
assert reading.distance == 7283
assert reading.time_votes == {"30:06": 4, "38:06": 1}
assert reading.distance_votes == {"7283": 3, "7288": 1}
assert [label for label, _ in reading.labeled_texts] == VARIANT_LABELS
def test_extract_screen_data_nothing_legible(screen_path, monkeypatch):
monkeypatch.setattr(ocr, "ocr_image", lambda img: "")
reading = ocr.extract_screen_data(screen_path)
assert reading.time is None and reading.distance is None
def test_extract_screen_data_unreadable_image(corrupt_path, tmp_path, fake_tesseract):
with pytest.raises(ImageLoadError, match="not a readable image"):
ocr.extract_screen_data(corrupt_path)
with pytest.raises(ImageLoadError, match="file not found"):
ocr.extract_screen_data(tmp_path / "missing.jpg")
def _run_raising(exc):
def run(*args, **kwargs):
raise exc
return run
def test_ocr_image_reports_missing_tesseract(photo, monkeypatch):
monkeypatch.setattr(subprocess, "run", _run_raising(FileNotFoundError("tesseract")))
with pytest.raises(TesseractNotInstalledError, match="not installed"):
ocr.ocr_image(photo)
def test_ocr_image_reports_timeout(photo, monkeypatch):
monkeypatch.setattr(subprocess, "run",
_run_raising(subprocess.TimeoutExpired("tesseract", 60)))
with pytest.raises(OcrError, match="timed out"):
ocr.ocr_image(photo)
def test_ocr_image_reports_failure_and_cleans_up(photo, monkeypatch):
seen = []
def run(cmd, **kwargs):
seen.append(Path(cmd[1]))
assert seen[0].is_file() # the image was written for tesseract
return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="bad image\n")
monkeypatch.setattr(subprocess, "run", run)
with pytest.raises(OcrError, match="tesseract failed: bad image"):
ocr.ocr_image(photo)
assert not seen[0].exists() # and removed afterwards
def test_ocr_image_passes_psm_and_whitelist(photo, monkeypatch):
def run(cmd, **kwargs):
assert cmd[0] == "tesseract" and cmd[2:] == [
"stdout", "--psm", "6", "-c", "tessedit_char_whitelist=0123456789:."]
return subprocess.CompletedProcess(cmd, 0, stdout=" 30:06\n", stderr="")
monkeypatch.setattr(subprocess, "run", run)
assert ocr.ocr_image(photo) == "30:06"
def test_read_photo_pools_crops_and_skips_unreadable_ones(
screen_path, corrupt_path, fake_tesseract, capsys):
second = screen_path.with_name("IMG_0001_screen (1).jpg")
shutil.copy(screen_path, second)
reading = ocr.read_photo([screen_path, corrupt_path, second])
assert reading.time_votes == {"30:06": 8, "38:06": 2}
assert reading.time == "30:06" and reading.distance == "7283"
assert len(reading.labeled_texts) == 12
assert "corrupt.jpg: not a readable image" in capsys.readouterr().err
def test_read_photo_stops_when_tesseract_is_missing(screen_path, monkeypatch):
monkeypatch.setattr(subprocess, "run", _run_raising(FileNotFoundError("tesseract")))
with pytest.raises(TesseractNotInstalledError):
ocr.read_photo([screen_path, screen_path])
def test_cli_validation_scores_only_images_with_a_reference(
screen_path, fake_tesseract, tmp_path, capsys):
shutil.copy(screen_path, tmp_path / "IMG_0002_screen.jpg")
shutil.copy(screen_path, tmp_path / "IMG_0003_screen.jpg")
reference = tmp_path / "reference.csv"
reference.write_text("image,time,distance_m\n"
"IMG_0001.JPEG,30:06,7283\n"
"IMG_0002.JPEG,30:06,9999\n")
output = tmp_path / "ocr.csv"
code = ocr.main(["--dir", str(tmp_path), "--validate", str(reference),
"--output", str(output)])
out = capsys.readouterr().out
assert code == 0
assert "Processing 3 unique images from 3 crops" in out
assert "Time: 30:06 OK" in out
assert "Distance: 7283 EXPECTED 9999" in out
assert "Time: 2/2 (100%)" in out
assert "Distance: 1/2 (50%)" in out
assert "(1 images have no reference reading and are not scored)" in out
assert output.read_text().splitlines()[1] == "IMG_0001,30:06,7283,2:04.0,486,"
def test_cli_stops_cleanly_when_tesseract_is_missing(screen_path, monkeypatch, capsys):
monkeypatch.setattr(subprocess, "run", _run_raising(FileNotFoundError("tesseract")))
assert ocr.main(["--image", str(screen_path)]) == 1
assert "tesseract is not installed" in capsys.readouterr().err
def test_cli_bad_inputs(tmp_path, screen_path, capsys):
assert ocr.main(["--dir", str(tmp_path / "missing")]) == 1
assert ocr.main(["--image", str(screen_path), "--validate", str(tmp_path / "no.csv")]) == 1
err = capsys.readouterr().err
assert "is not a directory" in err and "could not read" in err
@pytest.mark.skipif(shutil.which("tesseract") is None, reason="tesseract not installed")
def test_real_tesseract_reads_a_sample_screen():
"""End-to-end on a committed crop whose reference reading is 30:06 / 7559 m."""
reading = ocr.extract_screen_data(REPO / "train" / "1" / "IMG_5523_screen.jpg")
assert reading.time == "30:06"
assert reading.distance == 7559
+117
View File
@@ -0,0 +1,117 @@
from collections import Counter
import pytest
from rowing_stats.parsing import (
extract_distances,
extract_distances_by_method,
extract_times,
extract_times_by_method,
find_distances,
find_times,
image_base_name,
pick_best,
)
@pytest.mark.parametrize("text, expected", [
("30:06", ["30:06"]),
("30:06 29\n7283", ["30:06"]),
("30:06\n40:05", ["30:06", "40:05"]),
("30:06 30:06", ["30:06", "30:06"]), # each occurrence is a vote
("", []),
("no digits here", []),
("2:04", []), # a pace: one-digit minutes
("02:04", []), # under the 10-minute floor
("09:59", []),
("10:00", ["10:00"]),
("30:60", []), # seconds out of range
("99:00", ["99:00"]),
("130:06", ["30:06"]), # a stray leading digit is dropped
])
def test_find_times_mm_ss(text, expected):
assert find_times(text) == expected
@pytest.mark.parametrize("text, expected", [
("1:00:08", ["60:08"]), # normalised to total minutes
("1:30:00", ["90:00"]),
("2:00:00", ["120:00"]),
("2:00:01", ["120:01"]), # bound is on minutes only
("2:01:00", []), # over two hours
("0:05:00", []), # under ten minutes
("0:30:06", ["30:06"]),
("1:00:08 30:06", ["60:08", "30:06"]),
])
def test_find_times_h_mm_ss(text, expected):
assert find_times(text) == expected
def test_find_times_does_not_reread_the_tail_of_an_hour_time():
# "1:00:08" must not also produce "00:08", nor "1:30:45" a second "30:45"
assert find_times("1:30:45") == ["90:45"]
# ...even when the hour-format time itself was rejected
assert find_times("2:30:45") == []
@pytest.mark.parametrize("text, expected", [
("7283", ["7283"]),
("13879 26911", ["13879", "26911"]),
("999", []), # too short
("1000 50000", ["1000", "50000"]), # bounds are inclusive
("50001", []),
("0999", []), # four digits, but under 1000 m
("07337", ["07337"]), # a leading zero is kept as read
("123456", []), # six digits is not a distance
("30:06", []),
("72.83", []),
("", []),
])
def test_find_distances(text, expected):
assert find_distances(text) == expected
LABELED = [
("s2_otsu", "30:06 29\n7283"),
("s2_otsu_inv", "30:06\n7288"),
("s3_otsu", "38:06\n7283"),
("s3_otsu_inv", ""),
]
def test_votes_are_counted_across_variants():
assert extract_times(LABELED) == Counter({"30:06": 2, "38:06": 1})
assert extract_distances(LABELED) == Counter({"7283": 2, "7288": 1})
def test_majority_wins():
assert pick_best(extract_times(LABELED)) == "30:06"
assert pick_best(extract_distances(LABELED)) == "7283"
def test_pick_best_empty_is_none():
assert pick_best(Counter()) is None
def test_pick_best_tie_goes_to_first_seen():
assert pick_best(extract_times([("a", "30:06"), ("b", "31:06")])) == "30:06"
assert pick_best(extract_times([("a", "31:06"), ("b", "30:06")])) == "31:06"
def test_by_method_groups_and_shows_abstentions():
assert extract_times_by_method(LABELED) == {
"s2_otsu": {"30:06"}, "s2_otsu_inv": {"30:06"},
"s3_otsu": {"38:06"}, "s3_otsu_inv": set(),
}
assert extract_distances_by_method(LABELED)["s3_otsu_inv"] == set()
assert extract_distances_by_method(LABELED)["s2_otsu_inv"] == {"7288"}
@pytest.mark.parametrize("filename, expected", [
("IMG_5413_screen.jpg", "IMG_5413"),
("IMG_5413_screen (1).jpg", "IMG_5413"),
("IMG_5413_screen (12).jpg", "IMG_5413"),
("IMG_5413.JPEG", "IMG_5413"),
])
def test_image_base_name(filename, expected):
assert image_base_name(filename) == expected
+90
View File
@@ -0,0 +1,90 @@
import pytest
from conftest import REPO
from rowing_stats.errors import RowingStatsError
from rowing_stats.results import (
CSV_COLUMNS,
WorkoutRow,
calories,
format_pace,
format_time,
load_ground_truth,
make_row,
pace_per_500m,
parse_time,
write_csv,
)
@pytest.mark.parametrize("seconds, expected", [
(124.0, "2:04.0"),
(123.14, "2:03.1"),
(119.5, "1:59.5"),
(119.97, "2:00.0"), # rounds up into the next minute, not "1:60.0"
(60.0, "1:00.0"),
])
def test_format_pace(seconds, expected):
assert format_pace(seconds) == expected
def test_time_round_trip():
assert format_time(30, 6) == "30:06"
assert format_time(60, 33) == "60:33" # minutes run past the hour
assert parse_time("30:06") == 1806
assert parse_time("60:33") == 3633
def test_derived_metrics_match_the_committed_results():
# First row of rowing_results.csv: 30:06, 7283 m -> 2:04.0, 486 kcal
assert format_pace(pace_per_500m(1806, 7283)) == "2:04.0"
assert round(calories(7283)) == 486
def test_make_row_derives_pace_and_calories():
assert make_row("IMG_5413.JPEG", "30:06", 7283, "2025-11-05 12:08:00") == WorkoutRow(
image="IMG_5413.JPEG", time="30:06", distance_m=7283,
pace_per_500m="2:04.0", calories=486, date_taken="2025-11-05 12:08:00",
)
def test_make_row_leaves_gaps_for_missing_fields():
assert make_row("a", "30:06", None) == WorkoutRow(image="a", time="30:06")
assert make_row("a", None, 7283) == WorkoutRow(image="a", distance_m=7283, calories=486)
assert make_row("a", None, None) == WorkoutRow(image="a")
def test_csv_round_trip(tmp_path):
path = tmp_path / "out.csv"
write_csv([make_row("IMG_1.JPEG", "30:06", 7283), make_row("IMG_2.JPEG", "40:05", 9671)],
path)
header, first, _ = path.read_text().splitlines()
assert header.split(",") == CSV_COLUMNS
assert first == "IMG_1.JPEG,30:06,7283,2:04.0,486,"
assert load_ground_truth(path) == {
"IMG_1": {"time": "30:06", "distance_m": 7283},
"IMG_2": {"time": "40:05", "distance_m": 9671},
}
def test_load_ground_truth_reads_the_committed_reference():
truth = load_ground_truth(REPO / "rowing_results.csv")
assert len(truth) == 34
assert truth["IMG_5413"] == {"time": "30:06", "distance_m": 7283}
def test_load_ground_truth_missing_file(tmp_path):
with pytest.raises(RowingStatsError, match="could not read"):
load_ground_truth(tmp_path / "nope.csv")
@pytest.mark.parametrize("content", [
"name,value\nx,1\n", # wrong columns
"image,time,distance_m\nIMG_1.JPEG,30:06,far\n", # distance not a number
"image,time,distance_m\nIMG_1.JPEG,30:06\n", # short row
])
def test_load_ground_truth_rejects_other_csvs(tmp_path, content):
path = tmp_path / "bad.csv"
path.write_text(content)
with pytest.raises(RowingStatsError, match="not a results CSV"):
load_ground_truth(path)
+48
View File
@@ -0,0 +1,48 @@
import pytest
from rowing_stats import tune
from rowing_stats.crop import CropParams
def test_load_images_skips_unreadable_files(photo_path, corrupt_path, capsys):
images = tune.load_images(photo_path.parent)
assert [path.name for path, _ in images] == ["IMG_0001.jpg"]
assert "corrupt.jpg" in capsys.readouterr().err
def test_count_rowing_crops(photo_path, photo, tmp_path, monkeypatch):
seen = []
def fake_predict(path, model_path):
seen.append(path)
assert path.is_file() # the crop exists while it is classified
return 1, 0.9
monkeypatch.setattr(tune, "cnn_predict", fake_predict)
images = [(photo_path, photo), (photo_path, photo)]
assert tune.count_rowing_crops(images, CropParams(), tmp_path, tmp_path / "m.pth") == 2
assert not any(path.exists() for path in seen) # and is removed afterwards
# Parameters that find no screen classify nothing
assert tune.count_rowing_crops(images, CropParams(area_ratio_min=0.1), tmp_path,
tmp_path / "m.pth") == 0
assert len(seen) == 2
def test_objective_rejects_inverted_ranges(photo_path, photo, tmp_path, monkeypatch):
optuna = pytest.importorskip("optuna")
monkeypatch.setattr(tune, "cnn_predict", lambda path, model_path: (1, 0.9))
objective = tune.make_objective([(photo_path, photo)], tmp_path, tmp_path / "m.pth")
defaults = dict(vars(CropParams()))
assert objective(optuna.trial.FixedTrial(defaults)) == 1
assert objective(optuna.trial.FixedTrial({**defaults, "thresh_min": 160,
"thresh_max": 160})) == 0
assert objective(optuna.trial.FixedTrial({**defaults, "canny_low": 100,
"canny_high": 100})) == 0
def test_cli_missing_weights(tmp_path, capsys):
pytest.importorskip("torchvision")
assert tune.main(["--model-path", str(tmp_path / "nope.pth"), "--n-trials", "1"]) == 1
assert "CNN weights not found" in capsys.readouterr().err