diff --git a/.gitignore b/.gitignore
index d7845ea..c056684 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,8 @@
-/__pycache__
+__pycache__/
+*.egg-info/
+.pytest_cache/
+.venv/
.env
+.idea/
+/cropped/
+/debug/
diff --git a/crop_to_screen.py b/crop_to_screen.py
deleted file mode 100644
index 5f8ffa3..0000000
--- a/crop_to_screen.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""
-Crop Concept 2 PM5 rowing machine screens from photos using OpenCV.
-
-Detection strategy:
- The LCD screen has HIGH internal edge density (text/numbers/lines)
- compared to other bright regions (windows, walls, lockers).
- We threshold at multiple brightness levels, filter by edge density,
- aspect ratio, and size, then pick the best match.
-
-Usage:
- python crop_screens.py [input_dir] [output_dir]
-"""
-
-import cv2
-import numpy as np
-import os
-import glob
-import sys
-
-
-def order_corners(pts):
- """Order 4 points as [top-left, top-right, bottom-right, bottom-left]."""
- rect = np.zeros((4, 2), dtype="float32")
- s = pts.sum(axis=1)
- rect[0] = pts[np.argmin(s)]
- rect[2] = pts[np.argmax(s)]
- d = np.diff(pts, axis=1)
- rect[1] = pts[np.argmin(d)]
- rect[3] = pts[np.argmax(d)]
- return rect
-
-
-def find_screen(image):
- """
- Detect the Concept 2 PM5 LCD screen region in the image.
-
- Returns (x, y, w, h, contour) or None if not found.
- The contour is the best-matching contour for perspective correction.
- """
- h_img, w_img = image.shape[:2]
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
-
- # Pre-compute edge map for internal-content scoring
- blurred = cv2.GaussianBlur(gray, (11, 11), 0)
- edges = cv2.Canny(blurred, 80, 100)
-
- candidates = []
-
- # Sweep brightness thresholds — screen brightness varies by
- # lighting conditions (ranges from ~100 in dim gyms to ~200+)
- for thresh_val in range(70, 210, 10):
- _, thresh = cv2.threshold(gray, thresh_val, 255, cv2.THRESH_BINARY)
- kern = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kern)
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kern)
-
- contours, _ = cv2.findContours(
- thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
- )
-
- for cnt in contours:
- x, y, w, h = cv2.boundingRect(cnt)
- area = cv2.contourArea(cnt)
- rect_area = w * h
- if rect_area == 0:
- continue
-
- # Size: screen is a small-to-medium portion of the photo
- area_ratio = rect_area / (h_img * w_img)
- if area_ratio < 0.004480508227271387 or area_ratio > 0.13807760800032298:
- continue
-
- # Aspect ratio: LCD is roughly square
- aspect = w / h
- if aspect < 0.6831978184146027 or aspect > 1.9505294279578584:
- continue
-
- # Rectangularity
- rectangularity = area / rect_area
- if rectangularity < 0.6914579162415992:
- continue
-
- # KEY: edge density — LCD with text has high edge density
- roi_edges = edges[y : y + h, x : x + w]
- edge_density = np.sum(roi_edges > 0) / rect_area
- if edge_density < 0.012759310759672408:
- continue
-
- # Score: edge density * area * rectangularity
- # This favours text-rich regions that are large and well-shaped
- score = edge_density * area * rectangularity
- candidates.append((score, x, y, w, h, cnt))
-
- if not candidates:
- return None
-
- candidates.sort(key=lambda c: c[0], reverse=True)
- best = candidates[0]
- return best[1], best[2], best[3], best[4], best[5]
-
-
-def perspective_correct(image, contour, dst_w, dst_h):
- """Warp the screen quadrilateral to a flat rectangle."""
- # Approximate contour to a polygon, tightening until we get 4 corners
- peri = cv2.arcLength(contour, True)
- for eps_mult in [0.02, 0.03, 0.05, 0.08, 0.10]:
- approx = cv2.approxPolyDP(contour, eps_mult * peri, True)
- if len(approx) == 4:
- break
-
- if len(approx) != 4:
- # Fall back to the minimum area rectangle corners
- rect = cv2.minAreaRect(contour)
- approx = cv2.boxPoints(rect).astype(np.float32)
- else:
- approx = approx.reshape(4, 2).astype(np.float32)
-
- src = order_corners(approx)
- dst = np.array(
- [[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]],
- dtype="float32",
- )
- M = cv2.getPerspectiveTransform(src, dst)
- return cv2.warpPerspective(image, M, (dst_w, dst_h))
-
-
-def crop_screen(image_path, output_path, padding=15):
- """Load an image, find the screen, perspective-correct and save it."""
- image = cv2.imread(image_path)
- if image is None:
- print(f" ERROR: Could not read {image_path}")
- return False
-
- h_img, w_img = image.shape[:2]
- result = find_screen(image)
-
- if result is None:
- print(f" SKIP: No screen detected in {os.path.basename(image_path)}")
- return False
-
- x, y, w, h, contour = result
-
- # Use perspective correction to flatten the screen
- corrected = perspective_correct(image, contour, w + 2 * padding, h + 2 * padding)
-
- cv2.imwrite(output_path, corrected, [cv2.IMWRITE_JPEG_QUALITY, 95])
- print(
- f" OK: {os.path.basename(image_path)} -> {os.path.basename(output_path)} ({w}x{h})"
- )
- return True
-
-
-def main():
- if len(sys.argv) >= 3:
- input_dir = sys.argv[1]
- output_dir = sys.argv[2]
- elif len(sys.argv) == 2:
- input_dir = sys.argv[1]
- output_dir = os.path.join(input_dir, "cropped")
- else:
- input_dir = "/mnt/user-data/uploads"
- output_dir = "/mnt/user-data/outputs"
-
- os.makedirs(output_dir, exist_ok=True)
-
- images = sorted(
- glob.glob(os.path.join(input_dir, "*.JPEG"))
- + glob.glob(os.path.join(input_dir, "*.jpeg"))
- + glob.glob(os.path.join(input_dir, "*.jpg"))
- + glob.glob(os.path.join(input_dir, "*.JPG"))
- )
-
- if not images:
- print(f"No images found in {input_dir}")
- return
-
- print(f"Found {len(images)} images in {input_dir}\n")
-
- success = 0
- for img_path in images:
- name = os.path.splitext(os.path.basename(img_path))[0]
- out_path = os.path.join(output_dir, f"{name}_screen.jpg")
- if crop_screen(img_path, out_path):
- success += 1
-
- print(f"\nDone: {success}/{len(images)} screens cropped -> {output_dir}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/extract_rowing_data.py b/extract_rowing_data.py
deleted file mode 100644
index 4119bd0..0000000
--- a/extract_rowing_data.py
+++ /dev/null
@@ -1,203 +0,0 @@
-"""
-Extract rowing machine time and distance from a display photo using Claude's vision API.
-
-Mirrors the extraction logic from handle_rowing.go.
-
-Usage:
- python extract_rowing_data.py path/to/image.jpg
- python extract_rowing_data.py --dir path/to/images/
-"""
-
-import argparse
-import base64
-import json
-import mimetypes
-import re
-import sys
-from pathlib import Path
-
-import anthropic
-from PIL import Image
-from PIL.ExifTags import Base as ExifBase
-
-
-ALLOWED_MEDIA_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"}
-
-PROMPT = """Look at this rowing machine display. Extract the total elapsed time and total distance.
-
-Return ONLY a JSON object with these exact keys and numeric values:
-- "timeMinutes": total minutes (e.g. 2:30 = 2)
-- "timeSeconds": total seconds (e.g. 2:30 = 30)
-- "distance": distance in meters as a number (e.g. 5000)
-
-No text, no markdown, no explanation. Just the JSON object."""
-
-# Validation bounds (same as Go handler)
-MIN_DISTANCE = 100 # metres
-MAX_DISTANCE = 100_000 # metres
-MIN_TOTAL_SECS = 30 # 30 seconds
-MAX_TOTAL_SECS = 7200 # 2 hours
-MIN_PACE_PER_500M = 80 # ~1:20 /500m
-MAX_PACE_PER_500M = 150 # ~2:30 /500m
-
-
-def get_exif_date(image_path: str) -> str | None:
- """Extract the date taken from EXIF data."""
- img = Image.open(image_path)
- exif = img.getexif()
- if not exif:
- return None
- return exif.get(ExifBase.DateTime)
-
-
-def extract_rowing_data(image_path: str) -> dict:
- """
- Send an image to Claude and extract rowing time/distance.
-
- Returns dict with keys: timeMinutes, timeSeconds, distance, totalSeconds,
- timePer500m, calories, dateTaken.
- """
- path = Path(image_path)
- media_type = mimetypes.guess_type(str(path))[0]
- if media_type not in ALLOWED_MEDIA_TYPES:
- raise ValueError(f"Unsupported image type: {media_type}")
-
- encoded = base64.standard_b64encode(path.read_bytes()).decode("utf-8")
-
- client = anthropic.Anthropic()
- message = client.messages.create(
- model="claude-haiku-4-5-20251001",
- max_tokens=256,
- messages=[
- {
- "role": "user",
- "content": [
- {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": media_type,
- "data": encoded,
- },
- },
- {
- "type": "text",
- "text": PROMPT,
- },
- ],
- }
- ],
- )
-
- if not message.content:
- raise RuntimeError("Empty response from Claude")
-
- raw = message.content[0].text.strip()
- # Strip markdown fencing if present
- raw = raw.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
-
- data = json.loads(raw)
- time_minutes = int(data["timeMinutes"])
- time_seconds = int(data["timeSeconds"])
- distance = int(data["distance"])
-
- if distance == 0:
- raise ValueError("Invalid distance: 0")
-
- total_seconds = time_minutes * 60 + time_seconds
-
- # Validate
- if not (MIN_DISTANCE <= distance <= MAX_DISTANCE):
- raise ValueError(f"Anomalous distance: {distance}")
- if not (MIN_TOTAL_SECS <= total_seconds <= MAX_TOTAL_SECS):
- raise ValueError(f"Anomalous time: {total_seconds}s")
-
- per_500m = total_seconds / distance * 500.0
- if not (MIN_PACE_PER_500M <= per_500m <= MAX_PACE_PER_500M):
- raise ValueError(f"Anomalous pace: {per_500m:.1f}s /500m")
-
- calories = distance / 7500.0 * 500.0
-
- date_taken = get_exif_date(image_path)
-
- return {
- "timeMinutes": time_minutes,
- "timeSeconds": time_seconds,
- "distance": distance,
- "totalSeconds": total_seconds,
- "timePer500m": round(per_500m, 2),
- "calories": round(calories, 2),
- "dateTaken": date_taken,
- }
-
-
-_VERSION_RE = re.compile(r"^(?P.+?)(?:\s+\((?P\d+)\))?(?P\.\w+)$")
-
-
-def _keep_latest_versions(paths: list[Path]) -> list[Path]:
- """Keep only the highest-numbered version of each base filename.
-
- e.g. given IMG_5454_screen.jpg, IMG_5454_screen (1).jpg, IMG_5454_screen (3).jpg
- only IMG_5454_screen (3).jpg is kept. No-suffix counts as version 0.
- """
- best: dict[str, tuple[int, Path]] = {}
- for p in paths:
- m = _VERSION_RE.match(p.name)
- if not m:
- best.setdefault(p.name, (0, p))
- continue
- base_key = m.group("base") + m.group("ext")
- num = int(m.group("num")) if m.group("num") else 0
- prev_num, _ = best.get(base_key, (-1, p))
- if num > prev_num:
- best[base_key] = (num, p)
- return sorted(p for _, p in best.values())
-
-
-def main():
- parser = argparse.ArgumentParser(description="Extract rowing data from display photos")
- parser.add_argument("--image", help="Path to a single image")
- parser.add_argument("--dir", help="Path to a directory of images")
- args = parser.parse_args()
-
- if not args.image and not args.dir:
- parser.error("Provide --image or --dir")
- if args.image and args.dir:
- parser.error("--image and --dir are mutually exclusive")
-
- IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
-
- if args.dir:
- dir_path = Path(args.dir)
- all_images = sorted(
- p for p in dir_path.iterdir() if p.suffix.lower() in IMAGE_EXTS
- )
- if not all_images:
- print(f"No images found in {args.dir}")
- sys.exit(1)
- image_paths = _keep_latest_versions(all_images)
- else:
- image_paths = [Path(args.image)]
-
- for img_path in image_paths:
- print(f"\n {img_path.name}:")
- try:
- result = extract_rowing_data(str(img_path))
- mins = result["timeMinutes"]
- secs = result["timeSeconds"]
- dist = result["distance"]
- pace = result["timePer500m"]
- pace_m = int(pace) // 60
- pace_s = pace % 60
- print(f" Time: {mins}:{secs:02d}")
- print(f" Distance: {dist}m")
- print(f" Pace: {pace_m}:{pace_s:04.1f} /500m")
- print(f" Calories: {result['calories']:.0f}")
- if result["dateTaken"]:
- print(f" Date: {result['dateTaken']}")
- except Exception as e:
- print(f" ERROR: {e}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/extract_screen_data.py b/extract_screen_data.py
deleted file mode 100644
index ce45925..0000000
--- a/extract_screen_data.py
+++ /dev/null
@@ -1,391 +0,0 @@
-"""
-Extract rowing machine time and distance from cropped screen images using Tesseract OCR.
-
-Uses multiple preprocessing variants (CLAHE, thresholding, scaling) and majority-vote
-extraction to reliably read the Concept 2 PM5 LCD display.
-
-Usage:
- python extract_screen_data.py --dir train/1/
- python extract_screen_data.py --image path/to/cropped.jpg
- python extract_screen_data.py --dir train/1/ --validate rowing_results.csv
-"""
-
-import argparse
-import csv
-import os
-import re
-import subprocess
-import sys
-import tempfile
-from collections import Counter
-from pathlib import Path
-
-import cv2
-import numpy as np
-
-
-def ocr_image(img, psm=6, whitelist="0123456789:."):
- """Run tesseract on a cv2 image and return the text."""
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
- cv2.imwrite(f.name, img)
- result = subprocess.run(
- [
- "tesseract",
- f.name,
- "stdout",
- "--psm",
- str(psm),
- "-c",
- f"tessedit_char_whitelist={whitelist}",
- ],
- capture_output=True,
- text=True,
- )
- os.unlink(f.name)
- return result.stdout.strip()
-
-
-def preprocess_and_ocr(img_path):
- """Generate multiple preprocessed variants and OCR each one.
-
- Returns a list of (label, text) tuples from different preprocessing pipelines.
- Labels like 's2_clahe_t120', 's3_otsu', 's4_otsu_inv'.
- """
- img = cv2.imread(img_path)
- if img is None:
- return []
-
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- results = []
-
- for scale in [2, 3]:
- scaled = cv2.resize(
- gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC
- )
-
- # CLAHE + fixed thresholds (only t120/t130 at scale 2 are useful)
- if scale == 2:
- clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
- enhanced = clahe.apply(scaled)
- for thresh_val in [120, 130]:
- _, thresh = cv2.threshold(enhanced, thresh_val, 255, cv2.THRESH_BINARY)
- results.append((f"s{scale}_clahe_t{thresh_val}", ocr_image(thresh)))
-
- # Otsu
- blur = cv2.GaussianBlur(scaled, (3, 3), 0)
- _, otsu = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
- results.append((f"s{scale}_otsu", ocr_image(otsu)))
-
- # Inverted Otsu
- results.append((f"s{scale}_otsu_inv", ocr_image(255 - otsu)))
-
- return results
-
-
-def extract_times(labeled_texts):
- """Extract time candidates from OCR texts using majority voting.
-
- Supports both H:MM:SS (hour+ workouts) and MM:SS formats.
- All times are normalized to MM:SS format for downstream consistency.
- """
- texts = [t for _, t in labeled_texts]
- time_counts = Counter()
- for text in texts:
- # Match H:MM:SS patterns first (e.g. 1:00:08)
- hms_matches = re.findall(r"(\d{1,2}):(\d{2}):(\d{2})", text)
- # Track positions consumed by H:MM:SS to avoid double-matching as MM:SS
- consumed = set()
- for h, m, s in hms_matches:
- hours, mins, secs = int(h), int(m), int(s)
- total_mins = hours * 60 + mins
- if 10 <= total_mins <= 120 and 0 <= secs <= 59:
- normalized = f"{total_mins}:{secs:02d}"
- time_counts[normalized] += 1
- # Mark these positions as consumed
- for match in re.finditer(r"\d{1,2}:\d{2}:\d{2}", text):
- consumed.add((match.start(), match.end()))
-
- # Match MM:SS patterns, skipping anything already matched as H:MM:SS
- for match in re.finditer(r"(\d{2}):(\d{2})", text):
- # Skip if this match overlaps with an H:MM:SS match
- if any(
- match.start() >= cs and match.end() <= ce
- for cs, ce in consumed
- ):
- continue
- mins, secs = int(match.group(1)), int(match.group(2))
- # Filter to plausible rowing times: 10-120 min, valid seconds
- if 10 <= mins <= 120 and 0 <= secs <= 59:
- time_counts[f"{mins}:{secs:02d}"] += 1
- return time_counts
-
-
-def extract_distances(labeled_texts):
- """Extract distance candidates from OCR texts using majority voting."""
- texts = [t for _, t in labeled_texts]
- dist_counts = Counter()
- for text in texts:
- # Match 4-5 digit numbers (plausible rowing distances: 1000-99999m)
- matches = re.findall(r"\b(\d{4,5})\b", text)
- for m in matches:
- val = int(m)
- if 1000 <= val <= 50000:
- dist_counts[m] += 1
- return dist_counts
-
-
-def extract_times_by_method(labeled_texts):
- """Extract time candidates grouped by method label.
-
- Returns dict mapping method label to set of extracted time strings.
- """
- by_method = {}
- for label, text in labeled_texts:
- times = set()
- hms_matches = re.findall(r"(\d{1,2}):(\d{2}):(\d{2})", text)
- consumed = set()
- for h, m, s in hms_matches:
- hours, mins, secs = int(h), int(m), int(s)
- total_mins = hours * 60 + mins
- if 10 <= total_mins <= 120 and 0 <= secs <= 59:
- times.add(f"{total_mins}:{secs:02d}")
- for match in re.finditer(r"\d{1,2}:\d{2}:\d{2}", text):
- consumed.add((match.start(), match.end()))
- for match in re.finditer(r"(\d{2}):(\d{2})", text):
- if any(match.start() >= cs and match.end() <= ce for cs, ce in consumed):
- continue
- mins, secs = int(match.group(1)), int(match.group(2))
- if 10 <= mins <= 120 and 0 <= secs <= 59:
- times.add(f"{mins}:{secs:02d}")
- by_method[label] = times
- return by_method
-
-
-def extract_distances_by_method(labeled_texts):
- """Extract distance candidates grouped by method label.
-
- Returns dict mapping method label to set of extracted distance strings.
- """
- by_method = {}
- for label, text in labeled_texts:
- dists = set()
- matches = re.findall(r"\b(\d{4,5})\b", text)
- for m in matches:
- val = int(m)
- if 1000 <= val <= 50000:
- dists.add(m)
- by_method[label] = dists
- return by_method
-
-
-def pick_best(counts, expected=None):
- """Pick the best candidate from vote counts. Prefer expected value if present."""
- if not counts:
- return None
- if expected and expected in counts:
- return expected
- return counts.most_common(1)[0][0]
-
-
-def extract_screen_data(img_path, expected_time=None, expected_distance=None):
- """Extract time and distance from a cropped rowing screen image.
-
- Args:
- img_path: Path to the cropped screen image.
- expected_time: Optional expected time string (e.g. "30:06") for validation.
- expected_distance: Optional expected distance string (e.g. "7283") for validation.
-
- Returns:
- dict with keys: time, distance, time_votes, distance_votes
- """
- labeled_texts = preprocess_and_ocr(img_path)
- if not labeled_texts:
- return None
-
- time_counts = extract_times(labeled_texts)
- dist_counts = extract_distances(labeled_texts)
-
- best_time = pick_best(time_counts, expected_time)
- best_distance = pick_best(dist_counts, expected_distance)
-
- return {
- "time": best_time,
- "distance": int(best_distance) if best_distance else None,
- "time_votes": time_counts,
- "distance_votes": dist_counts,
- "labeled_texts": labeled_texts,
- }
-
-
-def load_ground_truth(csv_path):
- """Load ground truth from rowing_results.csv.
-
- Returns dict mapping image base name (e.g. 'IMG_5413') to {time, distance}.
- """
- truth = {}
- with open(csv_path) as f:
- reader = csv.DictReader(f)
- for row in reader:
- # image column is like "IMG_5413.JPEG"
- base = row["image"].split(".")[0]
- truth[base] = {
- "time": row["time"],
- "distance_m": int(row["distance_m"]),
- }
- return truth
-
-
-def image_base_name(filename):
- """Extract base image name from cropped filename.
-
- e.g. 'IMG_5413_screen (1).jpg' -> 'IMG_5413'
- """
- # Remove _screen suffix and any (N) copy indicator
- name = Path(filename).stem
- name = re.sub(r"_screen.*", "", name)
- return name
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Extract rowing data from cropped screen images using Tesseract OCR"
- )
- parser.add_argument("--image", help="Path to a single cropped image")
- parser.add_argument("--dir", help="Path to directory of cropped images")
- parser.add_argument(
- "--validate",
- help="Path to rowing_results.csv for validation",
- )
- args = parser.parse_args()
-
- if not args.image and not args.dir:
- parser.error("Provide --image or --dir")
- if args.image and args.dir:
- parser.error("--image and --dir are mutually exclusive")
-
- IMAGE_EXTS = {".jpg", ".jpeg", ".png"}
-
- if args.dir:
- dir_path = Path(args.dir)
- image_paths = sorted(
- p for p in dir_path.iterdir() if p.suffix.lower() in IMAGE_EXTS
- )
- if not image_paths:
- print(f"No images found in {args.dir}")
- sys.exit(1)
- else:
- image_paths = [Path(args.image)]
-
- # Load ground truth if provided
- truth = {}
- if args.validate:
- truth = load_ground_truth(args.validate)
-
- # Group images by base name (multiple crops per original photo)
- # We only need to extract once per original photo - pick the best crop
- from collections import defaultdict
-
- by_base = defaultdict(list)
- for p in image_paths:
- base = image_base_name(p.name)
- by_base[base].append(p)
-
- correct_time = 0
- correct_dist = 0
- total = 0
-
- # Per-method accuracy tracking: method -> {time_correct, time_wrong, time_abstain, ...}
- method_stats = defaultdict(lambda: {
- "time_correct": 0, "time_wrong": 0, "time_abstain": 0,
- "dist_correct": 0, "dist_wrong": 0, "dist_abstain": 0,
- })
-
- print(f"Processing {len(by_base)} unique images from {len(image_paths)} crops...\n")
-
- for base, paths in sorted(by_base.items()):
- gt = truth.get(base)
- expected_time = gt["time"] if gt else None
- expected_dist = str(gt["distance_m"]) if gt else None
-
- # Try each crop, collect all votes
- all_time_votes = Counter()
- all_dist_votes = Counter()
- all_labeled_texts = []
-
- for p in paths:
- result = extract_screen_data(str(p))
- if result:
- all_time_votes.update(result["time_votes"])
- all_dist_votes.update(result["distance_votes"])
- all_labeled_texts.extend(result["labeled_texts"])
-
- best_time = pick_best(all_time_votes)
- best_dist = pick_best(all_dist_votes)
-
- total += 1
- time_ok = best_time == expected_time if gt else None
- dist_ok = best_dist == expected_dist if gt else None
-
- if time_ok:
- correct_time += 1
- if dist_ok:
- correct_dist += 1
-
- # Track per-method accuracy against ground truth
- if gt:
- times_by_method = extract_times_by_method(all_labeled_texts)
- dists_by_method = extract_distances_by_method(all_labeled_texts)
-
- for method, times in times_by_method.items():
- if not times:
- method_stats[method]["time_abstain"] += 1
- elif expected_time in times:
- method_stats[method]["time_correct"] += 1
- else:
- method_stats[method]["time_wrong"] += 1
-
- for method, dists in dists_by_method.items():
- if not dists:
- method_stats[method]["dist_abstain"] += 1
- elif expected_dist in dists:
- method_stats[method]["dist_correct"] += 1
- else:
- method_stats[method]["dist_wrong"] += 1
-
- # Display
- status_t = ""
- status_d = ""
- if gt:
- status_t = " OK" if time_ok else f" EXPECTED {expected_time}"
- status_d = " OK" if dist_ok else f" EXPECTED {expected_dist}"
-
- print(f" {base}:")
- print(
- f" Time: {best_time or '???'}{status_t} (votes: {all_time_votes.most_common(3)})"
- )
- print(
- f" Distance: {best_dist or '???'}{status_d} (votes: {all_dist_votes.most_common(3)})"
- )
-
- if truth:
- print(f"\nAccuracy:")
- print(f" Time: {correct_time}/{total} ({correct_time / total * 100:.0f}%)")
- print(f" Distance: {correct_dist}/{total} ({correct_dist / total * 100:.0f}%)")
-
- if method_stats:
- print(f"\nMethod Accuracy:")
- print(
- f" {'Method':<20s} {'Time OK':>8s} {'Time Wrong':>11s} {'Time Abstain':>13s}"
- f" {'Dist OK':>8s} {'Dist Wrong':>11s} {'Dist Abstain':>13s}"
- )
- for method in sorted(method_stats):
- s = method_stats[method]
- print(
- f" {method:<20s} {s['time_correct']:>8d} {s['time_wrong']:>11d}"
- f" {s['time_abstain']:>13d} {s['dist_correct']:>8d}"
- f" {s['dist_wrong']:>11d} {s['dist_abstain']:>13d}"
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/optimize_crop.py b/optimize_crop.py
deleted file mode 100644
index 7354252..0000000
--- a/optimize_crop.py
+++ /dev/null
@@ -1,202 +0,0 @@
-"""
-Optimize crop_to_screen.py parameters using Optuna.
-
-Uses the feature-based classifier from screen_classifier.py as the
-evaluation function. For each trial, runs find_screen() with suggested
-parameters on all source photos and counts how many crops are classified
-as rowing displays (label=1). Optuna maximises this count.
-
-Usage:
- python optimize_crop.py [--n-trials 300] [--photos-dir photos/]
-"""
-
-import argparse
-import glob
-import os
-import tempfile
-
-import cv2
-import numpy as np
-import optuna
-
-from screen_classifier import cnn_predict
-
-
-def find_screen_parameterized(image, params):
- """
- Detect the Concept 2 PM5 LCD screen region in the image.
- Same logic as crop_to_screen.find_screen but with tunable parameters.
-
- Returns (x, y, w, h) bounding box or None if not found.
- """
- h_img, w_img = image.shape[:2]
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
-
- gk = params["gaussian_kernel_size"]
- blurred = cv2.GaussianBlur(gray, (gk, gk), 0)
- edges = cv2.Canny(blurred, params["canny_low"], params["canny_high"])
-
- candidates = []
-
- for thresh_val in range(params["thresh_min"], params["thresh_max"], 10):
- _, thresh = cv2.threshold(gray, thresh_val, 255, cv2.THRESH_BINARY)
- mk = params["morph_kernel_size"]
- kern = cv2.getStructuringElement(cv2.MORPH_RECT, (mk, mk))
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kern)
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kern)
-
- contours, _ = cv2.findContours(
- thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
- )
-
- for cnt in contours:
- x, y, w, h = cv2.boundingRect(cnt)
- area = cv2.contourArea(cnt)
- rect_area = w * h
- if rect_area == 0:
- continue
-
- area_ratio = rect_area / (h_img * w_img)
- if (
- area_ratio < params["area_ratio_min"]
- or area_ratio > params["area_ratio_max"]
- ):
- continue
-
- aspect = w / h
- if aspect < params["aspect_min"] or aspect > params["aspect_max"]:
- continue
-
- rectangularity = area / rect_area
- if rectangularity < params["rectangularity_min"]:
- continue
-
- roi_edges = edges[y : y + h, x : x + w]
- edge_density = np.sum(roi_edges > 0) / rect_area
- if edge_density < params["edge_density_min"]:
- continue
-
- score = edge_density * area * rectangularity
- candidates.append((score, x, y, w, h))
-
- if not candidates:
- return None
-
- candidates.sort(key=lambda c: c[0], reverse=True)
- return candidates[0][1:]
-
-
-def load_images(photos_dir):
- """Load all source images once for reuse across trials."""
- paths = sorted(
- glob.glob(os.path.join(photos_dir, "*.JPEG"))
- + glob.glob(os.path.join(photos_dir, "*.jpeg"))
- + glob.glob(os.path.join(photos_dir, "*.jpg"))
- + glob.glob(os.path.join(photos_dir, "*.JPG"))
- )
- images = []
- for p in paths:
- img = cv2.imread(p)
- if img is not None:
- images.append((p, img))
- return images
-
-
-def make_objective(images, tmp_dir, model_path):
- """Create an Optuna objective function closed over images and tmp_dir."""
-
- def objective(trial):
- params = {
- "thresh_min": trial.suggest_int("thresh_min", 60, 160, step=10),
- "thresh_max": trial.suggest_int("thresh_max", 160, 255, step=10),
- "morph_kernel_size": trial.suggest_int("morph_kernel_size", 3, 21, step=2),
- "gaussian_kernel_size": trial.suggest_int(
- "gaussian_kernel_size", 3, 11, step=2
- ),
- "canny_low": trial.suggest_int("canny_low", 20, 100, step=10),
- "canny_high": trial.suggest_int("canny_high", 100, 250, step=10),
- "area_ratio_min": trial.suggest_float("area_ratio_min", 0.001, 0.02),
- "area_ratio_max": trial.suggest_float("area_ratio_max", 0.05, 0.30),
- "aspect_min": trial.suggest_float("aspect_min", 0.3, 0.8),
- "aspect_max": trial.suggest_float("aspect_max", 1.2, 2.5),
- "rectangularity_min": trial.suggest_float("rectangularity_min", 0.2, 0.7),
- "edge_density_min": trial.suggest_float("edge_density_min", 0.005, 0.06),
- }
-
- # Ensure thresh_min < thresh_max
- if params["thresh_min"] >= params["thresh_max"]:
- return 0
-
- # Ensure canny_low < canny_high
- if params["canny_low"] >= params["canny_high"]:
- return 0
-
- rowing_count = 0
- for img_path, img in images:
- result = find_screen_parameterized(img, params)
- if result is None:
- continue
-
- x, y, w, h = result
- h_img, w_img = img.shape[:2]
- padding = 15
- x1 = max(0, x - padding)
- y1 = max(0, y - padding)
- x2 = min(w_img, x + w + padding)
- y2 = min(h_img, y + h + padding)
- cropped = img[y1:y2, x1:x2]
-
- # Save to temp file for the classifier
- basename = os.path.splitext(os.path.basename(img_path))[0]
- tmp_path = os.path.join(tmp_dir, f"{basename}_trial{trial.number}.jpg")
- cv2.imwrite(tmp_path, cropped, [cv2.IMWRITE_JPEG_QUALITY, 95])
-
- try:
- label, _ = cnn_predict(tmp_path, model_path)
- if label == 1:
- rowing_count += 1
- finally:
- # Clean up immediately to save disk space
- if os.path.exists(tmp_path):
- os.remove(tmp_path)
-
- return rowing_count
-
- return objective
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Optimize crop_to_screen.py parameters"
- )
- parser.add_argument(
- "--photos-dir", default="photos/", help="Directory of source photos"
- )
- parser.add_argument(
- "--n-trials", type=int, default=300, help="Number of Optuna trials"
- )
- parser.add_argument(
- "--model-path",
- default="screen_classifier_model.pth",
- help="Path to CNN model weights",
- )
- args = parser.parse_args()
-
- images = load_images(args.photos_dir)
- print(f"Loaded {len(images)} source images from {args.photos_dir}")
-
- with tempfile.TemporaryDirectory() as tmp_dir:
- study = optuna.create_study(direction="maximize")
- objective = make_objective(images, tmp_dir, args.model_path)
- study.optimize(objective, n_trials=args.n_trials, show_progress_bar=True)
-
- print(f"\n{'=' * 60}")
- print(f"Best score: {study.best_value} / {len(images)} images classified as rowing")
- print(f"Best parameters:")
- for k, v in sorted(study.best_params.items()):
- print(f" {k:>25s}: {v}")
- print(f"{'=' * 60}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..6b8648d
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,30 @@
+[build-system]
+requires = ["setuptools>=77"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "rowing-stats"
+version = "0.1.0"
+description = "Extract workout data from photos of a Concept 2 PM5 rowing machine display"
+readme = "README.md"
+requires-python = ">=3.10"
+dependencies = [
+ "numpy>=2.0",
+ "opencv-python-headless>=4.10",
+ "pillow>=10.0",
+]
+
+[project.optional-dependencies]
+claude = ["anthropic>=1.0"]
+ml = ["torch>=2.6", "torchvision>=0.21", "optuna>=4.0"]
+dev = ["pytest>=8.0"]
+
+[project.scripts]
+rowing-stats = "rowing_stats.cli:main"
+
+[tool.setuptools.packages.find]
+where = ["src"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+pythonpath = ["src"]
diff --git a/requirements-claude.txt b/requirements-claude.txt
new file mode 100644
index 0000000..c11d1bf
--- /dev/null
+++ b/requirements-claude.txt
@@ -0,0 +1,3 @@
+# Adds what `rowing-stats claude` needs.
+-r requirements.txt
+anthropic==1.12.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000..a704938
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,4 @@
+# Everything, plus the test runner.
+-r requirements-claude.txt
+-r requirements-ml.txt
+pytest==9.1.0
diff --git a/requirements-ml.txt b/requirements-ml.txt
new file mode 100644
index 0000000..8fe25a8
--- /dev/null
+++ b/requirements-ml.txt
@@ -0,0 +1,5 @@
+# Adds what the CNN classifier and `rowing-stats tune` need.
+-r requirements.txt
+torch==2.13.0
+torchvision==0.28.0
+optuna==5.0.0
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..2e4092b
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,6 @@
+# Exact versions the crop / classify (features) / ocr commands were tested
+# against, on Python 3.14. Also requires the Tesseract binary (tested with
+# 5.5.3) — see README.
+numpy==2.5.2
+opencv-python-headless==5.0.0.93
+pillow==12.3.0
diff --git a/src/rowing_stats/__init__.py b/src/rowing_stats/__init__.py
new file mode 100644
index 0000000..78f45ae
--- /dev/null
+++ b/src/rowing_stats/__init__.py
@@ -0,0 +1,3 @@
+"""Extract workout data from photos of a Concept 2 PM5 rowing machine display."""
+
+__version__ = "0.1.0"
diff --git a/src/rowing_stats/__main__.py b/src/rowing_stats/__main__.py
new file mode 100644
index 0000000..b68a02f
--- /dev/null
+++ b/src/rowing_stats/__main__.py
@@ -0,0 +1,6 @@
+import sys
+
+from rowing_stats.cli import main
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/screen_classifier.py b/src/rowing_stats/classifier.py
similarity index 62%
rename from screen_classifier.py
rename to src/rowing_stats/classifier.py
index 1b502f0..67a8a23 100644
--- a/screen_classifier.py
+++ b/src/rowing_stats/classifier.py
@@ -5,33 +5,51 @@ Binary classifier: 1 = rowing machine display, 0 = not rowing machine.
Two modes:
1. Feature-based (works immediately, no training needed)
- 2. CNN-based with transfer learning (needs training data)
+ 2. CNN-based, a small network trained from scratch (needs training data
+ and the `ml` extra: torch and torchvision)
Usage:
# Predict with feature-based classifier (no training needed)
- python classifier.py predict --image path/to/image.jpg
+ rowing-stats classify predict --image path/to/image.jpg
- # Organize training data, then train CNN
- python classifier.py train --data-dir data/
- python classifier.py predict --image path/to/image.jpg --model cnn
+ # Train the CNN on train/0 and train/1, then predict with it
+ rowing-stats classify train --data-dir train/
+ rowing-stats classify predict --image path/to/image.jpg --model cnn
"""
import argparse
-import os
-import sys
+import functools
import json
-import numpy as np
+import sys
+from collections.abc import Sequence
from pathlib import Path
-from PIL import Image, ImageStat, ImageFilter
+from typing import TYPE_CHECKING
+
+import numpy as np
+from PIL import ImageFilter
+
+from rowing_stats.errors import (
+ MissingDependencyError,
+ ModelLoadError,
+ RowingStatsError,
+ SetupError,
+)
+from rowing_stats.images import IMAGE_SUFFIXES, list_images, open_image
+
+if TYPE_CHECKING:
+ import torch
+
+DEFAULT_MODEL_PATH = Path("screen_classifier_model.pth")
+CLASSIFIER_SUFFIXES = IMAGE_SUFFIXES | {".bmp", ".tiff"}
# ---------------------------------------------------------------------------
# Feature-based classifier (works out of the box, no GPU needed)
# ---------------------------------------------------------------------------
-def extract_features(image_path: str) -> dict:
+def extract_features(image_path: Path) -> dict[str, float]:
"""Extract hand-crafted features that distinguish rowing displays."""
- img = Image.open(image_path).convert("RGB")
+ img = open_image(image_path).convert("RGB")
gray = img.convert("L")
# Resize for consistent analysis
@@ -71,7 +89,7 @@ def extract_features(image_path: str) -> dict:
r, g, b = color_pixels[:, :, 0], color_pixels[:, :, 1], color_pixels[:, :, 2]
max_c = np.maximum(np.maximum(r, g), b)
min_c = np.minimum(np.minimum(r, g), b)
- saturation = np.where(max_c > 0, (max_c - min_c) / max_c, 0)
+ saturation = np.divide(max_c - min_c, max_c, out=np.zeros_like(max_c), where=max_c > 0)
features["mean_saturation"] = float(np.mean(saturation))
# 6. Dark pixel ratio: displays have significant dark regions (text)
@@ -90,7 +108,7 @@ def extract_features(image_path: str) -> dict:
return features
-def feature_based_predict(image_path: str, verbose: bool = False) -> tuple[int, float]:
+def feature_based_predict(image_path: Path, verbose: bool = False) -> tuple[int, float]:
"""
Predict using hand-crafted features and a rule-based scorer.
Returns (label, confidence).
@@ -148,19 +166,24 @@ def feature_based_predict(image_path: str, verbose: bool = False) -> tuple[int,
# ---------------------------------------------------------------------------
-def get_cnn_model():
- """Build a simple CNN for binary classification."""
+def _require_torch() -> None:
+ """Raise MissingDependencyError unless torch and torchvision can be imported."""
try:
- import torch
- import torch.nn as nn
- except ImportError:
- print(
- "Error: PyTorch required for CNN mode. Install with: pip install torch torchvision"
- )
- sys.exit(1)
+ import torch # noqa: F401
+ import torchvision # noqa: F401
+ except ImportError as exc:
+ raise MissingDependencyError(
+ 'PyTorch required for CNN mode. Install with: pip install -e ".[ml]"'
+ ) from exc
+
+
+def get_cnn_model() -> "torch.nn.Module":
+ """Build a simple CNN for binary classification."""
+ _require_torch()
+ import torch.nn as nn
class RowingCNN(nn.Module):
- def __init__(self):
+ def __init__(self) -> None:
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
@@ -188,26 +211,34 @@ def get_cnn_model():
nn.Linear(128, 1),
)
- def forward(self, x):
+ def forward(self, x: "torch.Tensor") -> "torch.Tensor":
return self.classifier(self.features(x))
return RowingCNN()
def train_cnn(
- data_dir: str,
+ data_dir: Path,
epochs: int = 20,
lr: float = 1e-3,
- save_path: str = "screen_classifier_model.pth",
-):
+ save_path: Path = DEFAULT_MODEL_PATH,
+ val_dir: Path | None = None,
+) -> None:
"""
Train the CNN. Expects data_dir with structure:
data_dir/
- train/
- 0/ (non-rowing images)
- 1/ (rowing images)
- val/ (optional, same structure)
+ 0/ (non-rowing images)
+ 1/ (rowing images)
+ and val_dir, if given, with the same structure.
+
+ Without val_dir the weights from the last epoch are saved; with it, the
+ weights from the epoch with the best validation accuracy.
"""
+ _require_torch()
+ for directory in (data_dir, val_dir):
+ if directory is not None and not (directory / "0").is_dir():
+ raise RowingStatsError(f"{directory} must contain 0/ and 1/ subdirectories")
+
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
@@ -234,15 +265,13 @@ def train_cnn(
]
)
- train_dir = os.path.join(data_dir, "train")
- train_ds = datasets.ImageFolder(train_dir, transform=transform_train)
+ train_ds = datasets.ImageFolder(str(data_dir), transform=transform_train)
train_loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=2)
print(f"Training samples: {len(train_ds)} Classes: {train_ds.classes}")
val_loader = None
- val_dir = os.path.join(data_dir, "val")
- if os.path.isdir(val_dir):
- val_ds = datasets.ImageFolder(val_dir, transform=transform_val)
+ if val_dir is not None:
+ val_ds = datasets.ImageFolder(str(val_dir), transform=transform_val)
val_loader = DataLoader(val_ds, batch_size=16, shuffle=False, num_workers=2)
print(f"Validation samples: {len(val_ds)}")
@@ -298,16 +327,29 @@ def train_cnn(
print(f"\nModel saved to {save_path}")
-def cnn_predict(image_path: str, model_path: str = "model.pth") -> tuple[int, float]:
- """Predict using the trained CNN."""
- import torch
- from torchvision import transforms
-
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+@functools.lru_cache(maxsize=2)
+def load_cnn(model_path: Path) -> "tuple[torch.nn.Module, torch.device]":
+ """Load trained weights, once per path, and return the model in eval mode."""
model = get_cnn_model()
- model.load_state_dict(torch.load(model_path, map_location=device))
+ import torch
+
+ if not model_path.is_file():
+ raise ModelLoadError(f"CNN weights not found at {model_path}")
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ try:
+ model.load_state_dict(torch.load(model_path, map_location=device))
+ except Exception as exc: # torch raises several unrelated types for a bad file
+ raise ModelLoadError(f"could not load CNN weights from {model_path}: {exc}") from exc
model.to(device)
model.eval()
+ return model, device
+
+
+def cnn_predict(image_path: Path, model_path: Path = DEFAULT_MODEL_PATH) -> tuple[int, float]:
+ """Predict using the trained CNN."""
+ model, device = load_cnn(model_path)
+ import torch
+ from torchvision import transforms
transform = transforms.Compose(
[
@@ -317,7 +359,7 @@ def cnn_predict(image_path: str, model_path: str = "model.pth") -> tuple[int, fl
]
)
- img = Image.open(image_path).convert("RGB")
+ img = open_image(image_path).convert("RGB")
tensor = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
@@ -334,89 +376,104 @@ def cnn_predict(image_path: str, model_path: str = "model.pth") -> tuple[int, fl
# ---------------------------------------------------------------------------
-def main():
- parser = argparse.ArgumentParser(description="Rowing Machine Display Classifier")
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="rowing-stats classify", description="Rowing Machine Display Classifier"
+ )
sub = parser.add_subparsers(dest="command", required=True)
# --- predict ---
p_pred = sub.add_parser("predict", help="Classify an image or directory of images")
- p_pred.add_argument("--image", help="Path to image file")
- p_pred.add_argument("--dir", help="Path to directory of images")
+ target = p_pred.add_mutually_exclusive_group(required=True)
+ target.add_argument("--image", type=Path, help="Path to image file")
+ target.add_argument("--dir", type=Path, help="Path to directory of images")
p_pred.add_argument(
"--model",
choices=["features", "cnn"],
default="features",
help="Which classifier to use (default: features)",
)
- p_pred.add_argument("--model-path", default="model.pth", help="Path to CNN weights")
+ p_pred.add_argument("--model-path", type=Path, default=DEFAULT_MODEL_PATH,
+ help=f"Path to CNN weights (default: {DEFAULT_MODEL_PATH})")
p_pred.add_argument("--verbose", "-v", action="store_true")
# --- train ---
p_train = sub.add_parser("train", help="Train the CNN classifier")
- p_train.add_argument("--data-dir", required=True, help="Root data directory")
+ p_train.add_argument("--data-dir", type=Path, required=True,
+ help="Directory containing 0/ (not rowing) and 1/ (rowing)")
+ p_train.add_argument("--val-dir", type=Path,
+ help="Optional held-out directory with the same layout")
p_train.add_argument("--epochs", type=int, default=20)
p_train.add_argument("--lr", type=float, default=1e-3)
- p_train.add_argument("--save", default="model.pth", help="Where to save weights")
+ p_train.add_argument("--save", type=Path, default=DEFAULT_MODEL_PATH,
+ help=f"Where to save weights (default: {DEFAULT_MODEL_PATH})")
# --- extract ---
p_feat = sub.add_parser("extract", help="Print extracted features for an image")
- p_feat.add_argument("--image", required=True)
+ p_feat.add_argument("--image", type=Path, required=True)
+ return parser
- args = parser.parse_args()
- if args.command == "predict":
- if not args.image and not args.dir:
- parser.error("predict requires --image or --dir")
- if args.image and args.dir:
- parser.error("--image and --dir are mutually exclusive")
+def _predict(args: argparse.Namespace) -> int:
+ # Build list of image paths
+ if args.dir:
+ image_paths = list_images(args.dir, CLASSIFIER_SUFFIXES)
+ if not image_paths:
+ print(f"No images found in {args.dir}", file=sys.stderr)
+ return 1
+ else:
+ image_paths = [args.image]
- # Build list of image paths
- IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}
- if args.dir:
- dir_path = Path(args.dir)
- if not dir_path.is_dir():
- print(f"Error: {args.dir} is not a directory")
- sys.exit(1)
- image_paths = sorted(
- p for p in dir_path.iterdir() if p.suffix.lower() in IMAGE_EXTS
- )
- if not image_paths:
- print(f"No images found in {args.dir}")
- sys.exit(1)
- else:
- image_paths = [Path(args.image)]
-
- # Classify each image
- rowing_count = 0
- for img_path in image_paths:
+ # Classify each image
+ rowing_count = 0
+ errors = 0
+ for img_path in image_paths:
+ try:
if args.model == "features":
- label, conf = feature_based_predict(str(img_path), verbose=args.verbose)
+ label, conf = feature_based_predict(img_path, verbose=args.verbose)
else:
- label, conf = cnn_predict(str(img_path), args.model_path)
+ label, conf = cnn_predict(img_path, args.model_path)
+ except SetupError:
+ raise # every other image would fail the same way
+ except RowingStatsError as exc:
+ print(f" ERROR: {exc}", file=sys.stderr)
+ errors += 1
+ continue
- tag = "ROWING MACHINE" if label == 1 else "NOT ROWING MACHINE"
- if args.dir:
- print(f" {img_path.name} \u2192 {tag} (confidence={conf:.2f})")
- else:
- print(f"\n Result: {tag} (label={label}, confidence={conf:.2f})\n")
- if label == 1:
- rowing_count += 1
-
- # Summary for directory mode
+ tag = "ROWING MACHINE" if label == 1 else "NOT ROWING MACHINE"
if args.dir:
- total = len(image_paths)
- not_rowing = total - rowing_count
- print(
- f"\n Summary: {total} images | {rowing_count} rowing | {not_rowing} not rowing"
- )
+ print(f" {img_path.name} \u2192 {tag} (confidence={conf:.2f})")
+ else:
+ print(f"\n Result: {tag} (label={label}, confidence={conf:.2f})\n")
+ if label == 1:
+ rowing_count += 1
- elif args.command == "train":
- train_cnn(args.data_dir, epochs=args.epochs, lr=args.lr, save_path=args.save)
+ # Summary for directory mode
+ if args.dir:
+ total = len(image_paths) - errors
+ not_rowing = total - rowing_count
+ print(
+ f"\n Summary: {total} images | {rowing_count} rowing | {not_rowing} not rowing"
+ )
+ return 1 if errors else 0
- elif args.command == "extract":
- feats = extract_features(args.image)
- print(json.dumps(feats, indent=2))
+
+def main(argv: Sequence[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ try:
+ if args.command == "predict":
+ return _predict(args)
+ if args.command == "train":
+ train_cnn(args.data_dir, epochs=args.epochs, lr=args.lr,
+ save_path=args.save, val_dir=args.val_dir)
+ elif args.command == "extract":
+ feats = extract_features(args.image)
+ print(json.dumps(feats, indent=2))
+ except RowingStatsError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ return 0
if __name__ == "__main__":
- main()
+ sys.exit(main())
diff --git a/src/rowing_stats/claude.py b/src/rowing_stats/claude.py
new file mode 100644
index 0000000..ea6ae0f
--- /dev/null
+++ b/src/rowing_stats/claude.py
@@ -0,0 +1,331 @@
+"""
+Extract rowing machine time and distance from a display photo using Claude's vision API.
+
+This is the reference reader: it is what rowing_results.csv was produced with,
+and what the Tesseract pipeline in ocr.py is validated against. It mirrors the
+extraction logic of the Go handler it was ported from (handle_rowing.go).
+
+Usage:
+ rowing-stats claude --image path/to/image.jpg
+ rowing-stats claude --dir path/to/images/ --output rowing_results.csv
+"""
+
+import argparse
+import base64
+import functools
+import json
+import mimetypes
+import re
+import sys
+from collections.abc import Sequence
+from dataclasses import dataclass, replace
+from datetime import datetime
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from PIL.ExifTags import Base as ExifBase
+
+from rowing_stats.errors import (
+ ClaudeUnavailableError,
+ ExtractionError,
+ ImageLoadError,
+ MissingDependencyError,
+ RowingStatsError,
+ SetupError,
+)
+from rowing_stats.images import list_images, open_image
+from rowing_stats.results import (
+ WorkoutRow,
+ calories,
+ format_pace,
+ format_time,
+ make_row,
+ pace_per_500m,
+ write_csv,
+)
+
+if TYPE_CHECKING:
+ import anthropic
+
+MODEL = "claude-haiku-4-5-20251001"
+# The answer is a three-key JSON object, so this is a ceiling, not a target.
+MAX_TOKENS = 256
+# Seconds per attempt; the SDK retries twice on top (429/5xx/connection).
+TIMEOUT_S = 30.0
+
+ALLOWED_MEDIA_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"}
+CLAUDE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png", ".gif", ".webp"})
+
+PROMPT = """Look at this rowing machine display. Extract the total elapsed time and total distance.
+
+Return ONLY a JSON object with these exact keys and numeric values:
+- "timeMinutes": total minutes (e.g. 2:30 = 2)
+- "timeSeconds": total seconds (e.g. 2:30 = 30)
+- "distance": distance in meters as a number (e.g. 5000)
+
+No text, no markdown, no explanation. Just the JSON object."""
+
+# Validation bounds (same as Go handler)
+MIN_DISTANCE = 100 # metres
+MAX_DISTANCE = 100_000 # metres
+MIN_TOTAL_SECS = 30 # 30 seconds
+MAX_TOTAL_SECS = 7200 # 2 hours
+MIN_PACE_PER_500M = 80 # ~1:20 /500m
+MAX_PACE_PER_500M = 150 # ~2:30 /500m
+
+EXIF_DATE_FORMAT = "%Y:%m:%d %H:%M:%S"
+
+
+@dataclass(frozen=True)
+class RowingData:
+ """A validated reading, with the metrics derived from it."""
+
+ time_minutes: int
+ time_seconds: int
+ distance: int
+ total_seconds: int
+ time_per_500m: float
+ calories: float
+ date_taken: str | None = None
+
+ def to_row(self, image: str) -> WorkoutRow:
+ return make_row(image, format_time(self.time_minutes, self.time_seconds),
+ self.distance, format_exif_date(self.date_taken))
+
+
+def get_exif_date(image_path: Path) -> str | None:
+ """Extract the date taken from EXIF data, as the raw 'YYYY:MM:DD HH:MM:SS' string."""
+ exif = open_image(image_path).getexif()
+ if not exif:
+ return None
+ value = exif.get(ExifBase.DateTime)
+ return value if isinstance(value, str) else None
+
+
+def format_exif_date(raw: str | None) -> str | None:
+ """Convert an EXIF timestamp to 'YYYY-MM-DD HH:MM:SS'; None if absent or malformed."""
+ if not raw:
+ return None
+ try:
+ return datetime.strptime(raw.strip(), EXIF_DATE_FORMAT).strftime("%Y-%m-%d %H:%M:%S")
+ except ValueError:
+ return None
+
+
+def strip_markdown_fence(raw: str) -> str:
+ """Remove a surrounding markdown code fence from a model's response."""
+ raw = raw.strip()
+ return raw.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
+
+
+def parse_reply(raw: str) -> tuple[int, int, int]:
+ """Parse Claude's reply into (minutes, seconds, distance).
+
+ Raises ExtractionError if it is not the JSON object the prompt asks for.
+ """
+ try:
+ data = json.loads(strip_markdown_fence(raw))
+ return int(data["timeMinutes"]), int(data["timeSeconds"]), int(data["distance"])
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
+ raise ExtractionError(f"Unparseable reply from Claude: {raw!r}") from exc
+
+
+def validate_reading(time_minutes: int, time_seconds: int, distance: int) -> RowingData:
+ """Check a reading against the sanity bounds and derive pace and calories.
+
+ Raises ExtractionError if the distance, time, or implied pace is implausible,
+ which usually means a digit was misread.
+ """
+ if distance == 0:
+ raise ExtractionError("Invalid distance: 0")
+
+ total_seconds = time_minutes * 60 + time_seconds
+
+ if not (MIN_DISTANCE <= distance <= MAX_DISTANCE):
+ raise ExtractionError(f"Anomalous distance: {distance}")
+ if not (MIN_TOTAL_SECS <= total_seconds <= MAX_TOTAL_SECS):
+ raise ExtractionError(f"Anomalous time: {total_seconds}s")
+
+ per_500m = pace_per_500m(total_seconds, distance)
+ if not (MIN_PACE_PER_500M <= per_500m <= MAX_PACE_PER_500M):
+ raise ExtractionError(f"Anomalous pace: {per_500m:.1f}s /500m")
+
+ return RowingData(
+ time_minutes=time_minutes,
+ time_seconds=time_seconds,
+ distance=distance,
+ total_seconds=total_seconds,
+ time_per_500m=round(per_500m, 2),
+ calories=round(calories(distance), 2),
+ )
+
+
+@functools.lru_cache(maxsize=1)
+def _client() -> "anthropic.Anthropic":
+ """Build the Anthropic client on first use.
+
+ Credentials are resolved by the SDK (ANTHROPIC_API_KEY, or a profile).
+ """
+ try:
+ import anthropic
+ except ImportError as exc:
+ raise MissingDependencyError(
+ 'the anthropic SDK is required. Install with: pip install -e ".[claude]"'
+ ) from exc
+ try:
+ return anthropic.Anthropic(timeout=TIMEOUT_S)
+ except anthropic.AnthropicError as exc:
+ raise ClaudeUnavailableError(f"could not set up the Claude client: {exc}") from exc
+
+
+def ask_claude(media_type: str, encoded: str) -> str:
+ """Send a base64 image to Claude with the extraction prompt; return its text reply.
+
+ Raises ClaudeUnavailableError for missing or rejected credentials, and
+ ExtractionError if the call fails or the reply has no text.
+ """
+ client = _client()
+ import anthropic
+
+ try:
+ message = client.messages.create(
+ model=MODEL,
+ max_tokens=MAX_TOKENS,
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": media_type,
+ "data": encoded,
+ },
+ },
+ {
+ "type": "text",
+ "text": PROMPT,
+ },
+ ],
+ }
+ ],
+ )
+ except (anthropic.AuthenticationError, anthropic.PermissionDeniedError) as exc:
+ raise ClaudeUnavailableError(f"Claude API rejected the credentials: {exc}") from exc
+ except anthropic.APIStatusError as exc:
+ raise ExtractionError(f"Claude API error {exc.status_code}: {exc.message}") from exc
+ except anthropic.APIConnectionError as exc:
+ raise ExtractionError(f"Claude API unreachable: {exc}") from exc
+ except TypeError as exc:
+ # The SDK raises TypeError when no credentials can be resolved at request time
+ if "authentication" not in str(exc):
+ raise
+ raise ClaudeUnavailableError(
+ "no Claude API credentials found (set ANTHROPIC_API_KEY)"
+ ) from exc
+
+ text = next((block.text for block in message.content if block.type == "text"), None)
+ if text is None:
+ raise ExtractionError("Empty response from Claude")
+ return text
+
+
+def extract_rowing_data(image_path: Path) -> RowingData:
+ """
+ Send an image to Claude and extract rowing time/distance.
+
+ Raises ImageLoadError if the file is not an image the API accepts,
+ ExtractionError if the API call fails or the reading is unusable, and
+ a SetupError if the SDK or credentials are missing.
+ """
+ media_type = mimetypes.guess_type(image_path.name)[0]
+ if media_type not in ALLOWED_MEDIA_TYPES:
+ raise ImageLoadError(f"{image_path.name}: unsupported image type: {media_type}")
+
+ # Decode locally first: a corrupt file should not cost an API call
+ date_taken = get_exif_date(image_path)
+ encoded = base64.standard_b64encode(image_path.read_bytes()).decode("utf-8")
+
+ reading = validate_reading(*parse_reply(ask_claude(media_type, encoded)))
+ return replace(reading, date_taken=date_taken)
+
+
+_VERSION_RE = re.compile(r"^(?P.+?)(?:\s+\((?P\d+)\))?(?P\.\w+)$")
+
+
+def _keep_latest_versions(paths: list[Path]) -> list[Path]:
+ """Keep only the highest-numbered version of each base filename.
+
+ e.g. given IMG_5454_screen.jpg, IMG_5454_screen (1).jpg, IMG_5454_screen (3).jpg
+ only IMG_5454_screen (3).jpg is kept. No-suffix counts as version 0.
+ """
+ best: dict[str, tuple[int, Path]] = {}
+ for p in paths:
+ m = _VERSION_RE.match(p.name)
+ if not m:
+ best.setdefault(p.name, (0, p))
+ continue
+ base_key = m.group("base") + m.group("ext")
+ num = int(m.group("num")) if m.group("num") else 0
+ prev_num, _ = best.get(base_key, (-1, p))
+ if num > prev_num:
+ best[base_key] = (num, p)
+ return sorted(p for _, p in best.values())
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ prog="rowing-stats claude",
+ description="Extract rowing data from display photos with Claude "
+ "(one paid API call per image)",
+ )
+ target = parser.add_mutually_exclusive_group(required=True)
+ target.add_argument("--image", type=Path, help="Path to a single image")
+ target.add_argument("--dir", type=Path, help="Path to a directory of images")
+ parser.add_argument("--output", "-o", type=Path,
+ help="Write the readings to this CSV file")
+ args = parser.parse_args(argv)
+
+ try:
+ if args.dir:
+ all_images = list_images(args.dir, CLAUDE_SUFFIXES)
+ if not all_images:
+ print(f"No images found in {args.dir}", file=sys.stderr)
+ return 1
+ image_paths = _keep_latest_versions(all_images)
+ else:
+ image_paths = [args.image]
+
+ rows: list[WorkoutRow] = []
+ errors = 0
+ for img_path in image_paths:
+ print(f"\n {img_path.name}:")
+ try:
+ result = extract_rowing_data(img_path)
+ except SetupError:
+ raise # every other image would fail the same way
+ except RowingStatsError as exc:
+ print(f" ERROR: {exc}")
+ errors += 1
+ continue
+ rows.append(result.to_row(img_path.name))
+ print(f" Time: {format_time(result.time_minutes, result.time_seconds)}")
+ print(f" Distance: {result.distance}m")
+ print(f" Pace: {format_pace(result.time_per_500m)} /500m")
+ print(f" Calories: {result.calories:.0f}")
+ if result.date_taken:
+ print(f" Date: {result.date_taken}")
+
+ if args.output:
+ write_csv(rows, args.output)
+ print(f"\nWrote {len(rows)} rows to {args.output}")
+ except RowingStatsError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/rowing_stats/cli.py b/src/rowing_stats/cli.py
new file mode 100644
index 0000000..612caea
--- /dev/null
+++ b/src/rowing_stats/cli.py
@@ -0,0 +1,39 @@
+"""The `rowing-stats` command: one subcommand per pipeline stage."""
+
+import importlib
+import sys
+from collections.abc import Sequence
+
+# Subcommand -> (module, what it does). Modules are imported only when their
+# command runs, so the optional dependencies of one never break another.
+COMMANDS = {
+ "crop": ("rowing_stats.crop", "find and crop the screen in each photo"),
+ "classify": ("rowing_stats.classifier", "tell rowing displays from other crops"),
+ "ocr": ("rowing_stats.ocr", "read time and distance from crops with Tesseract"),
+ "claude": ("rowing_stats.claude", "read time and distance from photos with Claude"),
+ "tune": ("rowing_stats.tune", "search for better screen detection parameters"),
+}
+
+
+def usage() -> str:
+ lines = ["usage: rowing-stats [options]", "", "commands:"]
+ lines += [f" {name:<10}{help_}" for name, (_, help_) in COMMANDS.items()]
+ lines += ["", "Run 'rowing-stats --help' for a command's options."]
+ return "\n".join(lines)
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ args = list(sys.argv[1:] if argv is None else argv)
+ if not args or args[0] in ("-h", "--help"):
+ print(usage())
+ return 0 if args else 2
+ if args[0] not in COMMANDS:
+ print(f"rowing-stats: unknown command '{args[0]}'\n\n{usage()}", file=sys.stderr)
+ return 2
+
+ module = importlib.import_module(COMMANDS[args[0]][0])
+ return module.main(args[1:])
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/rowing_stats/crop.py b/src/rowing_stats/crop.py
new file mode 100644
index 0000000..77ea1d7
--- /dev/null
+++ b/src/rowing_stats/crop.py
@@ -0,0 +1,247 @@
+"""
+Crop Concept 2 PM5 rowing machine screens from photos using OpenCV.
+
+Detection strategy:
+ The LCD screen has HIGH internal edge density (text/numbers/lines)
+ compared to other bright regions (windows, walls, lockers).
+ We threshold at multiple brightness levels, filter by edge density,
+ aspect ratio, and size, then pick the best match.
+
+Usage:
+ rowing-stats crop [input_dir] [output_dir]
+"""
+
+import argparse
+import sys
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import NamedTuple
+
+import cv2
+import numpy as np
+
+from rowing_stats.errors import RowingStatsError, ScreenNotFoundError
+from rowing_stats.images import list_images, read_image
+
+JPEG_SUFFIXES = frozenset({".jpg", ".jpeg"})
+DEFAULT_PADDING = 15
+
+
+@dataclass(frozen=True)
+class CropParams:
+ """
+ Detection parameters. The defaults were found by `rowing-stats tune`
+ (see tune.py) on the photos in photos/.
+ """
+
+ # Brightness thresholds swept, in steps of THRESH_STEP — screen brightness
+ # varies by lighting conditions (ranges from ~100 in dim gyms to ~200+)
+ thresh_min: int = 70
+ thresh_max: int = 210
+ morph_kernel_size: int = 5
+ gaussian_kernel_size: int = 11
+ canny_low: int = 80
+ canny_high: int = 100
+ # Size: screen is a small-to-medium portion of the photo
+ area_ratio_min: float = 0.004480508227271387
+ area_ratio_max: float = 0.13807760800032298
+ # Aspect ratio: LCD is roughly square
+ aspect_min: float = 0.6831978184146027
+ aspect_max: float = 1.9505294279578584
+ rectangularity_min: float = 0.6914579162415992
+ # KEY: edge density — LCD with text has high edge density
+ edge_density_min: float = 0.012759310759672408
+
+
+THRESH_STEP = 10
+DEFAULT_PARAMS = CropParams()
+
+
+class Screen(NamedTuple):
+ """A detected screen: its bounding box and the contour it came from."""
+
+ x: int
+ y: int
+ w: int
+ h: int
+ contour: np.ndarray
+
+
+def order_corners(pts: np.ndarray) -> np.ndarray:
+ """Order 4 points as [top-left, top-right, bottom-right, bottom-left]."""
+ rect = np.zeros((4, 2), dtype="float32")
+ s = pts.sum(axis=1)
+ rect[0] = pts[np.argmin(s)]
+ rect[2] = pts[np.argmax(s)]
+ d = np.diff(pts, axis=1)
+ rect[1] = pts[np.argmin(d)]
+ rect[3] = pts[np.argmax(d)]
+ return rect
+
+
+def find_screen(image: np.ndarray, params: CropParams = DEFAULT_PARAMS) -> Screen | None:
+ """
+ Detect the Concept 2 PM5 LCD screen region in the image.
+
+ Returns the best-scoring candidate, or None if nothing passes the filters.
+ Its contour is what `perspective_correct` flattens.
+ """
+ h_img, w_img = image.shape[:2]
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
+
+ # Pre-compute edge map for internal-content scoring
+ gk = params.gaussian_kernel_size
+ blurred = cv2.GaussianBlur(gray, (gk, gk), 0)
+ edges = cv2.Canny(blurred, params.canny_low, params.canny_high)
+
+ mk = params.morph_kernel_size
+ kern = cv2.getStructuringElement(cv2.MORPH_RECT, (mk, mk))
+
+ best_score = 0.0
+ best: Screen | None = None
+
+ for thresh_val in range(params.thresh_min, params.thresh_max, THRESH_STEP):
+ _, thresh = cv2.threshold(gray, thresh_val, 255, cv2.THRESH_BINARY)
+ thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kern)
+ thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kern)
+
+ contours, _ = cv2.findContours(
+ thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
+ )
+
+ for cnt in contours:
+ x, y, w, h = cv2.boundingRect(cnt)
+ area = cv2.contourArea(cnt)
+ rect_area = w * h
+ if rect_area == 0:
+ continue
+
+ area_ratio = rect_area / (h_img * w_img)
+ if area_ratio < params.area_ratio_min or area_ratio > params.area_ratio_max:
+ continue
+
+ aspect = w / h
+ if aspect < params.aspect_min or aspect > params.aspect_max:
+ continue
+
+ rectangularity = area / rect_area
+ if rectangularity < params.rectangularity_min:
+ continue
+
+ roi_edges = edges[y : y + h, x : x + w]
+ edge_density = np.sum(roi_edges > 0) / rect_area
+ if edge_density < params.edge_density_min:
+ continue
+
+ # Score: edge density * area * rectangularity
+ # This favours text-rich regions that are large and well-shaped
+ score = edge_density * area * rectangularity
+ if best is None or score > best_score:
+ best_score = score
+ best = Screen(x, y, w, h, cnt)
+
+ return best
+
+
+def perspective_correct(
+ image: np.ndarray, contour: np.ndarray, dst_w: int, dst_h: int
+) -> np.ndarray:
+ """Warp the screen quadrilateral to a flat rectangle."""
+ # Approximate contour to a polygon, loosening until we get 4 corners
+ peri = cv2.arcLength(contour, True)
+ for eps_mult in [0.02, 0.03, 0.05, 0.08, 0.10]:
+ approx = cv2.approxPolyDP(contour, eps_mult * peri, True)
+ if len(approx) == 4:
+ break
+
+ if len(approx) != 4:
+ # Fall back to the minimum area rectangle corners
+ rect = cv2.minAreaRect(contour)
+ approx = cv2.boxPoints(rect).astype(np.float32)
+ else:
+ approx = approx.reshape(4, 2).astype(np.float32)
+
+ src = order_corners(approx)
+ dst = np.array(
+ [[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]],
+ dtype="float32",
+ )
+ M = cv2.getPerspectiveTransform(src, dst)
+ return cv2.warpPerspective(image, M, (dst_w, dst_h))
+
+
+def crop_screen(
+ image_path: Path,
+ output_path: Path,
+ padding: int = DEFAULT_PADDING,
+ params: CropParams = DEFAULT_PARAMS,
+) -> tuple[int, int]:
+ """
+ Load an image, find the screen, perspective-correct and save it.
+
+ Returns the detected screen's (width, height). Raises ImageLoadError if the
+ photo cannot be read, ScreenNotFoundError if no screen is detected, and
+ RowingStatsError if the crop cannot be written.
+ """
+ image = read_image(image_path)
+
+ screen = find_screen(image, params)
+ if screen is None:
+ raise ScreenNotFoundError(f"No screen detected in {image_path.name}")
+
+ # Use perspective correction to flatten the screen
+ corrected = perspective_correct(
+ image, screen.contour, screen.w + 2 * padding, screen.h + 2 * padding
+ )
+
+ if not cv2.imwrite(str(output_path), corrected, [cv2.IMWRITE_JPEG_QUALITY, 95]):
+ raise RowingStatsError(f"Could not write {output_path}")
+ return screen.w, screen.h
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ prog="rowing-stats crop",
+ description="Crop the PM5 screen out of each photo in a directory",
+ )
+ parser.add_argument("input_dir", type=Path, nargs="?", default=Path("photos"),
+ help="directory of photos (default: photos/)")
+ parser.add_argument("output_dir", type=Path, nargs="?",
+ help="where to write the crops (default: INPUT_DIR/cropped)")
+ args = parser.parse_args(argv)
+ output_dir: Path = args.output_dir or args.input_dir / "cropped"
+
+ try:
+ images = list_images(args.input_dir, JPEG_SUFFIXES)
+ except RowingStatsError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ if not images:
+ print(f"No images found in {args.input_dir}", file=sys.stderr)
+ return 1
+
+ output_dir.mkdir(parents=True, exist_ok=True)
+ print(f"Found {len(images)} images in {args.input_dir}\n")
+
+ success = 0
+ errors = 0
+ for img_path in images:
+ out_path = output_dir / f"{img_path.stem}_screen.jpg"
+ try:
+ w, h = crop_screen(img_path, out_path)
+ except ScreenNotFoundError as exc:
+ print(f" SKIP: {exc}")
+ except RowingStatsError as exc:
+ print(f" ERROR: {exc}")
+ errors += 1
+ else:
+ print(f" OK: {img_path.name} -> {out_path.name} ({w}x{h})")
+ success += 1
+
+ print(f"\nDone: {success}/{len(images)} screens cropped -> {output_dir}")
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/rowing_stats/errors.py b/src/rowing_stats/errors.py
new file mode 100644
index 0000000..d30bd0a
--- /dev/null
+++ b/src/rowing_stats/errors.py
@@ -0,0 +1,45 @@
+"""Exceptions raised on purpose by this package.
+
+Everything derives from RowingStatsError, so a caller processing a batch can
+catch that one class, report the file, and carry on.
+"""
+
+
+class RowingStatsError(Exception):
+ """Base class for every error this package raises on purpose."""
+
+
+class ImageLoadError(RowingStatsError):
+ """The file is missing, unreadable, or not a decodable image."""
+
+
+class ScreenNotFoundError(RowingStatsError):
+ """No LCD-like region could be located in the photo."""
+
+
+class OcrError(RowingStatsError):
+ """Tesseract failed while reading an image."""
+
+
+class ExtractionError(RowingStatsError):
+ """Claude's reply was unusable, or the values it read are implausible."""
+
+
+class SetupError(RowingStatsError):
+ """The environment is not set up; every file in the batch would fail."""
+
+
+class TesseractNotInstalledError(SetupError, OcrError):
+ """The tesseract binary is not installed or not on PATH."""
+
+
+class MissingDependencyError(SetupError):
+ """An optional Python dependency for this command is not installed."""
+
+
+class ModelLoadError(SetupError):
+ """The CNN weights file is missing or does not match the model."""
+
+
+class ClaudeUnavailableError(SetupError):
+ """The Claude API rejected the credentials, or none are configured."""
diff --git a/src/rowing_stats/images.py b/src/rowing_stats/images.py
new file mode 100644
index 0000000..fb68568
--- /dev/null
+++ b/src/rowing_stats/images.py
@@ -0,0 +1,43 @@
+"""Finding and loading image files."""
+
+from collections.abc import Collection
+from pathlib import Path
+
+import cv2
+import numpy as np
+from PIL import Image, UnidentifiedImageError
+
+from rowing_stats.errors import ImageLoadError, RowingStatsError
+
+IMAGE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png"})
+
+
+def list_images(directory: Path, suffixes: Collection[str] = IMAGE_SUFFIXES) -> list[Path]:
+ """Return the image files directly inside a directory, sorted by name."""
+ if not directory.is_dir():
+ raise RowingStatsError(f"{directory} is not a directory")
+ return sorted(p for p in directory.iterdir() if p.suffix.lower() in suffixes)
+
+
+def read_image(path: Path) -> np.ndarray:
+ """Load an image as an OpenCV BGR array, raising ImageLoadError if that fails."""
+ if not path.is_file():
+ raise ImageLoadError(f"{path.name}: file not found")
+ image = cv2.imread(str(path))
+ if image is None:
+ raise ImageLoadError(f"{path.name}: not a readable image")
+ return image
+
+
+def open_image(path: Path) -> Image.Image:
+ """Open and fully decode an image with Pillow, raising ImageLoadError if that fails."""
+ try:
+ img = Image.open(path)
+ img.load() # Image.open is lazy; force decoding so truncated files fail here
+ except FileNotFoundError as exc:
+ raise ImageLoadError(f"{path.name}: file not found") from exc
+ except UnidentifiedImageError as exc:
+ raise ImageLoadError(f"{path.name}: not a readable image") from exc
+ except OSError as exc:
+ raise ImageLoadError(f"{path.name}: could not read image ({exc})") from exc
+ return img
diff --git a/src/rowing_stats/ocr.py b/src/rowing_stats/ocr.py
new file mode 100644
index 0000000..bcdb63f
--- /dev/null
+++ b/src/rowing_stats/ocr.py
@@ -0,0 +1,352 @@
+"""
+Extract rowing machine time and distance from cropped screen images using Tesseract OCR.
+
+Uses multiple preprocessing variants (CLAHE, thresholding, scaling) and majority-vote
+extraction to reliably read the Concept 2 PM5 LCD display.
+
+Usage:
+ rowing-stats ocr --dir cropped/
+ rowing-stats ocr --image path/to/cropped.jpg
+ rowing-stats ocr --dir cropped/ --validate rowing_results.csv
+ rowing-stats ocr --dir cropped/ --output ocr_results.csv
+"""
+
+import argparse
+import os
+import subprocess
+import sys
+import tempfile
+from collections import Counter, defaultdict
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from rowing_stats.errors import (
+ OcrError,
+ RowingStatsError,
+ SetupError,
+ TesseractNotInstalledError,
+)
+from rowing_stats.images import list_images, read_image
+from rowing_stats.parsing import (
+ LabeledTexts,
+ extract_distances,
+ extract_distances_by_method,
+ extract_times,
+ extract_times_by_method,
+ image_base_name,
+ pick_best,
+)
+from rowing_stats.results import load_ground_truth, make_row, write_csv
+
+TESSERACT_TIMEOUT_S = 60
+
+
+@dataclass(frozen=True)
+class ScreenReading:
+ """What was read off one cropped screen, with the votes behind it."""
+
+ time: str | None
+ distance: int | None
+ time_votes: Counter[str]
+ distance_votes: Counter[str]
+ labeled_texts: LabeledTexts
+
+
+def ocr_image(img: np.ndarray, psm: int = 6, whitelist: str = "0123456789:.") -> str:
+ """Run tesseract on a cv2 image and return the text.
+
+ Raises TesseractNotInstalledError if the binary is missing, and OcrError
+ if it times out or exits with an error.
+ """
+ fd, tmp_path = tempfile.mkstemp(suffix=".png")
+ os.close(fd)
+ try:
+ cv2.imwrite(tmp_path, img)
+ result = subprocess.run(
+ [
+ "tesseract",
+ tmp_path,
+ "stdout",
+ "--psm",
+ str(psm),
+ "-c",
+ f"tessedit_char_whitelist={whitelist}",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=TESSERACT_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise TesseractNotInstalledError(
+ "tesseract is not installed or not on PATH "
+ "(see https://tesseract-ocr.github.io/tessdoc/Installation.html)"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise OcrError(f"tesseract timed out after {TESSERACT_TIMEOUT_S}s") from exc
+ finally:
+ os.unlink(tmp_path)
+
+ if result.returncode != 0:
+ raise OcrError(f"tesseract failed: {result.stderr.strip()}")
+ return result.stdout.strip()
+
+
+def preprocess_variants(img: np.ndarray) -> list[tuple[str, np.ndarray]]:
+ """Generate the preprocessed versions of a cropped screen that get OCR'd.
+
+ Returns (label, image) pairs; labels are like 's2_clahe_t120', 's3_otsu',
+ 's3_otsu_inv' (scale factor, then the thresholding used).
+ """
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ variants: list[tuple[str, np.ndarray]] = []
+
+ for scale in [2, 3]:
+ scaled = cv2.resize(
+ gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC
+ )
+
+ # CLAHE + fixed thresholds (only t120/t130 at scale 2 are useful)
+ if scale == 2:
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
+ enhanced = clahe.apply(scaled)
+ for thresh_val in [120, 130]:
+ _, thresh = cv2.threshold(enhanced, thresh_val, 255, cv2.THRESH_BINARY)
+ variants.append((f"s{scale}_clahe_t{thresh_val}", thresh))
+
+ # Otsu
+ blur = cv2.GaussianBlur(scaled, (3, 3), 0)
+ _, otsu = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
+ variants.append((f"s{scale}_otsu", otsu))
+
+ # Inverted Otsu
+ variants.append((f"s{scale}_otsu_inv", 255 - otsu))
+
+ return variants
+
+
+def preprocess_and_ocr(img_path: Path) -> LabeledTexts:
+ """OCR every preprocessed variant of an image.
+
+ Returns a list of (label, text) tuples from different preprocessing pipelines.
+ """
+ img = read_image(img_path)
+ return [(label, ocr_image(variant)) for label, variant in preprocess_variants(img)]
+
+
+def extract_screen_data(img_path: Path) -> ScreenReading:
+ """Extract time and distance from a cropped rowing screen image.
+
+ Raises ImageLoadError if the image cannot be read, or an OcrError if
+ Tesseract fails. A field no variant could read comes back as None.
+ """
+ labeled_texts = preprocess_and_ocr(img_path)
+
+ time_counts = extract_times(labeled_texts)
+ dist_counts = extract_distances(labeled_texts)
+ best_distance = pick_best(dist_counts)
+
+ return ScreenReading(
+ time=pick_best(time_counts),
+ distance=int(best_distance) if best_distance else None,
+ time_votes=time_counts,
+ distance_votes=dist_counts,
+ labeled_texts=labeled_texts,
+ )
+
+
+@dataclass
+class PhotoReading:
+ """The pooled votes from every crop of one original photo."""
+
+ time_votes: Counter[str] = field(default_factory=Counter)
+ distance_votes: Counter[str] = field(default_factory=Counter)
+ labeled_texts: LabeledTexts = field(default_factory=list)
+
+ @property
+ def time(self) -> str | None:
+ return pick_best(self.time_votes)
+
+ @property
+ def distance(self) -> str | None:
+ return pick_best(self.distance_votes)
+
+
+def read_photo(crops: Sequence[Path]) -> PhotoReading:
+ """OCR every crop of one photo and pool their votes.
+
+ A crop that cannot be read is reported and contributes no votes; a setup
+ problem (no tesseract) is raised, since no crop could succeed.
+ """
+ reading = PhotoReading()
+ for crop in crops:
+ try:
+ result = extract_screen_data(crop)
+ except SetupError:
+ raise
+ except RowingStatsError as exc:
+ print(f" ERROR: {exc}", file=sys.stderr)
+ continue
+ reading.time_votes.update(result.time_votes)
+ reading.distance_votes.update(result.distance_votes)
+ reading.labeled_texts.extend(result.labeled_texts)
+ return reading
+
+
+def _new_method_stats() -> dict[str, int]:
+ return {
+ "time_correct": 0, "time_wrong": 0, "time_abstain": 0,
+ "dist_correct": 0, "dist_wrong": 0, "dist_abstain": 0,
+ }
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ prog="rowing-stats ocr",
+ description="Extract rowing data from cropped screen images using Tesseract OCR",
+ )
+ target = parser.add_mutually_exclusive_group(required=True)
+ target.add_argument("--image", type=Path, help="Path to a single cropped image")
+ target.add_argument("--dir", type=Path, help="Path to directory of cropped images")
+ parser.add_argument(
+ "--validate",
+ type=Path,
+ help="Path to rowing_results.csv for validation",
+ )
+ parser.add_argument(
+ "--output", "-o",
+ type=Path,
+ help="Write the readings to this CSV file",
+ )
+ args = parser.parse_args(argv)
+
+ try:
+ if args.dir:
+ image_paths = list_images(args.dir)
+ if not image_paths:
+ print(f"No images found in {args.dir}", file=sys.stderr)
+ return 1
+ else:
+ image_paths = [args.image]
+
+ # Load ground truth if provided
+ truth = load_ground_truth(args.validate) if args.validate else {}
+
+ # Group images by base name (multiple crops per original photo);
+ # all crops of a photo vote together
+ by_base: defaultdict[str, list[Path]] = defaultdict(list)
+ for p in image_paths:
+ by_base[image_base_name(p.name)].append(p)
+
+ correct_time = 0
+ correct_dist = 0
+ with_reference = 0
+
+ # Per-method accuracy tracking against the reference
+ method_stats: defaultdict[str, dict[str, int]] = defaultdict(_new_method_stats)
+ rows = []
+
+ print(f"Processing {len(by_base)} unique images from {len(image_paths)} crops...\n")
+
+ for base, paths in sorted(by_base.items()):
+ gt = truth.get(base)
+ expected_time = gt["time"] if gt else None
+ expected_dist = str(gt["distance_m"]) if gt else None
+
+ reading = read_photo(paths)
+ best_time = reading.time
+ best_dist = reading.distance
+ rows.append(make_row(base, best_time, int(best_dist) if best_dist else None))
+
+ time_ok = best_time == expected_time if gt else None
+ dist_ok = best_dist == expected_dist if gt else None
+
+ if gt:
+ with_reference += 1
+ if time_ok:
+ correct_time += 1
+ if dist_ok:
+ correct_dist += 1
+
+ # Track per-method accuracy against ground truth
+ if gt:
+ times_by_method = extract_times_by_method(reading.labeled_texts)
+ dists_by_method = extract_distances_by_method(reading.labeled_texts)
+
+ for method, times in times_by_method.items():
+ if not times:
+ method_stats[method]["time_abstain"] += 1
+ elif expected_time in times:
+ method_stats[method]["time_correct"] += 1
+ else:
+ method_stats[method]["time_wrong"] += 1
+
+ for method, dists in dists_by_method.items():
+ if not dists:
+ method_stats[method]["dist_abstain"] += 1
+ elif expected_dist in dists:
+ method_stats[method]["dist_correct"] += 1
+ else:
+ method_stats[method]["dist_wrong"] += 1
+
+ # Display
+ status_t = ""
+ status_d = ""
+ if gt:
+ status_t = " OK" if time_ok else f" EXPECTED {expected_time}"
+ status_d = " OK" if dist_ok else f" EXPECTED {expected_dist}"
+
+ print(f" {base}:")
+ print(
+ f" Time: {best_time or '???'}{status_t}"
+ f" (votes: {reading.time_votes.most_common(3)})"
+ )
+ print(
+ f" Distance: {best_dist or '???'}{status_d}"
+ f" (votes: {reading.distance_votes.most_common(3)})"
+ )
+
+ if args.output:
+ write_csv(rows, args.output)
+ print(f"\nWrote {len(rows)} rows to {args.output}")
+ except RowingStatsError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
+ if truth:
+ print("\nAccuracy:")
+ if with_reference:
+ print(
+ f" Time: {correct_time}/{with_reference}"
+ f" ({correct_time / with_reference * 100:.0f}%)"
+ )
+ print(
+ f" Distance: {correct_dist}/{with_reference}"
+ f" ({correct_dist / with_reference * 100:.0f}%)"
+ )
+ without = len(by_base) - with_reference
+ if without:
+ print(f" ({without} images have no reference reading and are not scored)")
+
+ if method_stats:
+ print("\nMethod Accuracy:")
+ print(
+ f" {'Method':<20s} {'Time OK':>8s} {'Time Wrong':>11s} {'Time Abstain':>13s}"
+ f" {'Dist OK':>8s} {'Dist Wrong':>11s} {'Dist Abstain':>13s}"
+ )
+ for method in sorted(method_stats):
+ s = method_stats[method]
+ print(
+ f" {method:<20s} {s['time_correct']:>8d} {s['time_wrong']:>11d}"
+ f" {s['time_abstain']:>13d} {s['dist_correct']:>8d}"
+ f" {s['dist_wrong']:>11d} {s['dist_abstain']:>13d}"
+ )
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/rowing_stats/parsing.py b/src/rowing_stats/parsing.py
new file mode 100644
index 0000000..3574412
--- /dev/null
+++ b/src/rowing_stats/parsing.py
@@ -0,0 +1,100 @@
+"""Turning raw OCR text into a time and a distance by majority vote.
+
+Each cropped screen is OCR'd several times with different preprocessing (see
+ocr.py). Every plausible time and distance found in any of those texts is a
+vote, and the value with the most votes wins. Nothing here touches an image.
+"""
+
+import re
+from collections import Counter
+from pathlib import Path
+
+# (label, text) pairs: which preprocessing variant produced which OCR text
+LabeledTexts = list[tuple[str, str]]
+
+# Plausible rowing times: 10-120 min
+MIN_MINUTES = 10
+MAX_MINUTES = 120
+# Plausible rowing distances, in metres
+MIN_DISTANCE = 1000
+MAX_DISTANCE = 50000
+
+_HMS_RE = re.compile(r"(\d{1,2}):(\d{2}):(\d{2})")
+_MS_RE = re.compile(r"(\d{2}):(\d{2})")
+_DISTANCE_RE = re.compile(r"\b(\d{4,5})\b")
+
+
+def find_times(text: str) -> list[str]:
+ """Return every plausible time in one OCR text, in order of appearance.
+
+ Supports both H:MM:SS (hour+ workouts) and MM:SS formats.
+ All times are normalized to MM:SS format for downstream consistency.
+ """
+ times: list[str] = []
+
+ # Match H:MM:SS patterns first (e.g. 1:00:08), tracking the positions they
+ # consume to avoid double-matching their tails as MM:SS
+ consumed: list[tuple[int, int]] = []
+ for match in _HMS_RE.finditer(text):
+ consumed.append(match.span())
+ hours, mins, secs = (int(g) for g in match.groups())
+ total_mins = hours * 60 + mins
+ if MIN_MINUTES <= total_mins <= MAX_MINUTES and 0 <= secs <= 59:
+ times.append(f"{total_mins}:{secs:02d}")
+
+ # Match MM:SS patterns, skipping anything already matched as H:MM:SS
+ for match in _MS_RE.finditer(text):
+ if any(match.start() >= cs and match.end() <= ce for cs, ce in consumed):
+ continue
+ mins, secs = int(match.group(1)), int(match.group(2))
+ if MIN_MINUTES <= mins <= MAX_MINUTES and 0 <= secs <= 59:
+ times.append(f"{mins}:{secs:02d}")
+ return times
+
+
+def find_distances(text: str) -> list[str]:
+ """Return every plausible distance (a 4-5 digit number) in one OCR text."""
+ return [m for m in _DISTANCE_RE.findall(text)
+ if MIN_DISTANCE <= int(m) <= MAX_DISTANCE]
+
+
+def extract_times(labeled_texts: LabeledTexts) -> Counter[str]:
+ """Count the votes for each time across all OCR texts."""
+ counts: Counter[str] = Counter()
+ for _, text in labeled_texts:
+ counts.update(find_times(text))
+ return counts
+
+
+def extract_distances(labeled_texts: LabeledTexts) -> Counter[str]:
+ """Count the votes for each distance across all OCR texts."""
+ counts: Counter[str] = Counter()
+ for _, text in labeled_texts:
+ counts.update(find_distances(text))
+ return counts
+
+
+def extract_times_by_method(labeled_texts: LabeledTexts) -> dict[str, set[str]]:
+ """Group the times found by the preprocessing variant that produced them."""
+ return {label: set(find_times(text)) for label, text in labeled_texts}
+
+
+def extract_distances_by_method(labeled_texts: LabeledTexts) -> dict[str, set[str]]:
+ """Group the distances found by the preprocessing variant that produced them."""
+ return {label: set(find_distances(text)) for label, text in labeled_texts}
+
+
+def pick_best(counts: Counter[str]) -> str | None:
+ """Pick the candidate with the most votes; the first seen wins a tie."""
+ if not counts:
+ return None
+ return counts.most_common(1)[0][0]
+
+
+def image_base_name(filename: str) -> str:
+ """Extract base image name from cropped filename.
+
+ e.g. 'IMG_5413_screen (1).jpg' -> 'IMG_5413'
+ """
+ # Remove _screen suffix and any (N) copy indicator
+ return re.sub(r"_screen.*", "", Path(filename).stem)
diff --git a/src/rowing_stats/results.py b/src/rowing_stats/results.py
new file mode 100644
index 0000000..c807f73
--- /dev/null
+++ b/src/rowing_stats/results.py
@@ -0,0 +1,101 @@
+"""The results table: one row per workout, as stored in rowing_results.csv."""
+
+import csv
+from collections.abc import Iterable
+from dataclasses import asdict, dataclass, fields
+from pathlib import Path
+
+from rowing_stats.errors import RowingStatsError
+
+# A 30-minute piece covering 7500 m is taken to burn 500 kcal
+CALORIES_PER_METRE = 500.0 / 7500.0
+
+
+@dataclass(frozen=True)
+class WorkoutRow:
+ """One line of the results CSV. Columns that could not be filled are empty."""
+
+ image: str
+ time: str = ""
+ distance_m: int | str = ""
+ pace_per_500m: str = ""
+ calories: int | str = ""
+ date_taken: str = ""
+
+
+CSV_COLUMNS = [f.name for f in fields(WorkoutRow)]
+
+
+def pace_per_500m(total_seconds: int, distance_m: int) -> float:
+ """Seconds taken per 500 m."""
+ return total_seconds / distance_m * 500.0
+
+
+def calories(distance_m: int) -> float:
+ """Estimated calories for a distance."""
+ return distance_m * CALORIES_PER_METRE
+
+
+def format_time(minutes: int, seconds: int) -> str:
+ """Format a duration as MM:SS, with minutes running past 59 for long pieces."""
+ return f"{minutes}:{seconds:02d}"
+
+
+def format_pace(seconds_per_500m: float) -> str:
+ """Format a pace as M:SS.s, e.g. 124.0 -> '2:04.0'."""
+ tenths = round(seconds_per_500m * 10)
+ return f"{tenths // 600}:{tenths % 600 / 10:04.1f}"
+
+
+def parse_time(time: str) -> int:
+ """Convert an MM:SS string to total seconds."""
+ minutes, seconds = time.split(":")
+ return int(minutes) * 60 + int(seconds)
+
+
+def make_row(image: str, time: str | None, distance_m: int | None,
+ date_taken: str | None = None) -> WorkoutRow:
+ """Build a row, deriving pace and calories when both time and distance are known."""
+ pace = ""
+ if time and distance_m:
+ pace = format_pace(pace_per_500m(parse_time(time), distance_m))
+ return WorkoutRow(
+ image=image,
+ time=time or "",
+ distance_m=distance_m if distance_m else "",
+ pace_per_500m=pace,
+ calories=round(calories(distance_m)) if distance_m else "",
+ date_taken=date_taken or "",
+ )
+
+
+def write_csv(rows: Iterable[WorkoutRow], path: Path) -> None:
+ """Write rows to a CSV file with the rowing_results.csv columns."""
+ with path.open("w", newline="") as f:
+ writer = csv.DictWriter(f, fieldnames=CSV_COLUMNS)
+ writer.writeheader()
+ writer.writerows(asdict(row) for row in rows)
+
+
+def load_ground_truth(csv_path: Path) -> dict[str, dict[str, str | int]]:
+ """Load reference readings from a results CSV such as rowing_results.csv.
+
+ Returns dict mapping image base name (e.g. 'IMG_5413') to {time, distance_m}.
+ """
+ truth: dict[str, dict[str, str | int]] = {}
+ try:
+ with csv_path.open(newline="") as f:
+ for row in csv.DictReader(f):
+ # image column is like "IMG_5413.JPEG"
+ base = row["image"].split(".")[0]
+ truth[base] = {
+ "time": row["time"],
+ "distance_m": int(row["distance_m"]),
+ }
+ except OSError as exc:
+ raise RowingStatsError(f"could not read {csv_path}: {exc}") from exc
+ except (KeyError, ValueError, TypeError) as exc:
+ raise RowingStatsError(
+ f"{csv_path} is not a results CSV (needs image, time, distance_m): {exc!r}"
+ ) from exc
+ return truth
diff --git a/src/rowing_stats/tune.py b/src/rowing_stats/tune.py
new file mode 100644
index 0000000..16d6bf4
--- /dev/null
+++ b/src/rowing_stats/tune.py
@@ -0,0 +1,167 @@
+"""
+Optimize the screen detection parameters in crop.py using Optuna.
+
+Uses the CNN classifier from classifier.py as the evaluation function. For
+each trial, runs find_screen() with suggested parameters on all source photos
+and counts how many crops are classified as rowing displays (label=1). Optuna
+maximises this count. Copy the winning values into crop.CropParams.
+
+Requires the `ml` extra (torch, torchvision, optuna).
+
+Usage:
+ rowing-stats tune [--n-trials 300] [--photos-dir photos/]
+"""
+
+import argparse
+import sys
+import tempfile
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import cv2
+import numpy as np
+
+from rowing_stats.classifier import DEFAULT_MODEL_PATH, cnn_predict, load_cnn
+from rowing_stats.crop import DEFAULT_PADDING, JPEG_SUFFIXES, CropParams, find_screen
+from rowing_stats.errors import ImageLoadError, MissingDependencyError, RowingStatsError
+from rowing_stats.images import list_images, read_image
+
+if TYPE_CHECKING:
+ import optuna
+
+
+def load_images(photos_dir: Path) -> list[tuple[Path, np.ndarray]]:
+ """Load all source images once for reuse across trials, skipping unreadable ones."""
+ images = []
+ for path in list_images(photos_dir, JPEG_SUFFIXES):
+ try:
+ images.append((path, read_image(path)))
+ except ImageLoadError as exc:
+ print(f" SKIP: {exc}", file=sys.stderr)
+ return images
+
+
+def suggest_params(trial: "optuna.Trial") -> CropParams:
+ """Draw one set of detection parameters from the search space."""
+ return CropParams(
+ thresh_min=trial.suggest_int("thresh_min", 60, 160, step=10),
+ thresh_max=trial.suggest_int("thresh_max", 160, 250, step=10),
+ morph_kernel_size=trial.suggest_int("morph_kernel_size", 3, 21, step=2),
+ gaussian_kernel_size=trial.suggest_int("gaussian_kernel_size", 3, 11, step=2),
+ canny_low=trial.suggest_int("canny_low", 20, 100, step=10),
+ canny_high=trial.suggest_int("canny_high", 100, 250, step=10),
+ area_ratio_min=trial.suggest_float("area_ratio_min", 0.001, 0.02),
+ area_ratio_max=trial.suggest_float("area_ratio_max", 0.05, 0.30),
+ aspect_min=trial.suggest_float("aspect_min", 0.3, 0.8),
+ aspect_max=trial.suggest_float("aspect_max", 1.2, 2.5),
+ rectangularity_min=trial.suggest_float("rectangularity_min", 0.2, 0.7),
+ edge_density_min=trial.suggest_float("edge_density_min", 0.005, 0.06),
+ )
+
+
+def count_rowing_crops(
+ images: Sequence[tuple[Path, np.ndarray]],
+ params: CropParams,
+ tmp_dir: Path,
+ model_path: Path,
+) -> int:
+ """Crop every image with the given parameters; count those the CNN calls a rowing display."""
+ rowing_count = 0
+ for img_path, img in images:
+ screen = find_screen(img, params)
+ if screen is None:
+ continue
+
+ h_img, w_img = img.shape[:2]
+ x1 = max(0, screen.x - DEFAULT_PADDING)
+ y1 = max(0, screen.y - DEFAULT_PADDING)
+ x2 = min(w_img, screen.x + screen.w + DEFAULT_PADDING)
+ y2 = min(h_img, screen.y + screen.h + DEFAULT_PADDING)
+ cropped = img[y1:y2, x1:x2]
+
+ # Save to temp file for the classifier
+ tmp_path = tmp_dir / f"{img_path.stem}.jpg"
+ cv2.imwrite(str(tmp_path), cropped, [cv2.IMWRITE_JPEG_QUALITY, 95])
+ try:
+ label, _ = cnn_predict(tmp_path, model_path)
+ if label == 1:
+ rowing_count += 1
+ finally:
+ # Clean up immediately to save disk space
+ tmp_path.unlink(missing_ok=True)
+
+ return rowing_count
+
+
+def make_objective(
+ images: Sequence[tuple[Path, np.ndarray]], tmp_dir: Path, model_path: Path
+) -> "Callable[[optuna.Trial], int]":
+ """Create an Optuna objective function closed over images and tmp_dir."""
+
+ def objective(trial: "optuna.Trial") -> int:
+ params = suggest_params(trial)
+
+ # Ensure thresh_min < thresh_max and canny_low < canny_high
+ if params.thresh_min >= params.thresh_max:
+ return 0
+ if params.canny_low >= params.canny_high:
+ return 0
+
+ return count_rowing_crops(images, params, tmp_dir, model_path)
+
+ return objective
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ prog="rowing-stats tune",
+ description="Optimize the screen detection parameters",
+ )
+ parser.add_argument(
+ "--photos-dir", type=Path, default=Path("photos"), help="Directory of source photos"
+ )
+ parser.add_argument(
+ "--n-trials", type=int, default=300, help="Number of Optuna trials"
+ )
+ parser.add_argument(
+ "--model-path",
+ type=Path,
+ default=DEFAULT_MODEL_PATH,
+ help="Path to CNN model weights",
+ )
+ args = parser.parse_args(argv)
+
+ try:
+ try:
+ import optuna
+ except ImportError as exc:
+ raise MissingDependencyError(
+ 'optuna is required. Install with: pip install -e ".[ml]"'
+ ) from exc
+
+ load_cnn(args.model_path) # fail now, not on the first trial, if it is missing
+ images = load_images(args.photos_dir)
+ if not images:
+ raise RowingStatsError(f"No images found in {args.photos_dir}")
+ print(f"Loaded {len(images)} source images from {args.photos_dir}")
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ study = optuna.create_study(direction="maximize")
+ objective = make_objective(images, Path(tmp_dir), args.model_path)
+ study.optimize(objective, n_trials=args.n_trials, show_progress_bar=True)
+ except RowingStatsError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
+ print(f"\n{'=' * 60}")
+ print(f"Best score: {study.best_value} / {len(images)} images classified as rowing")
+ print("Best parameters:")
+ for k, v in sorted(study.best_params.items()):
+ print(f" {k:>25s}: {v}")
+ print(f"{'=' * 60}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..9753f03
--- /dev/null
+++ b/tests/conftest.py
@@ -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
diff --git a/tests/test_classifier.py b/tests/test_classifier.py
new file mode 100644
index 0000000..ca5556d
--- /dev/null
+++ b/tests/test_classifier.py
@@ -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
diff --git a/tests/test_claude.py b/tests/test_claude.py
new file mode 100644
index 0000000..f4ed221
--- /dev/null
+++ b/tests/test_claude.py
@@ -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",
+ ]
diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
index 0000000..09989d8
--- /dev/null
+++ b/tests/test_cli.py
@@ -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
diff --git a/tests/test_crop.py b/tests/test_crop.py
new file mode 100644
index 0000000..b8cdd45
--- /dev/null
+++ b/tests/test_crop.py
@@ -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
diff --git a/tests/test_ocr.py b/tests/test_ocr.py
new file mode 100644
index 0000000..9989ce4
--- /dev/null
+++ b/tests/test_ocr.py
@@ -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
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
new file mode 100644
index 0000000..f2ab210
--- /dev/null
+++ b/tests/test_parsing.py
@@ -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
diff --git a/tests/test_results.py b/tests/test_results.py
new file mode 100644
index 0000000..29a5938
--- /dev/null
+++ b/tests/test_results.py
@@ -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)
diff --git a/tests/test_tune.py b/tests/test_tune.py
new file mode 100644
index 0000000..60bedfe
--- /dev/null
+++ b/tests/test_tune.py
@@ -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