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