diff --git a/CLAUDE.md b/CLAUDE.md index d7b7da8..813e625 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,48 +4,47 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -A computer vision + LLM pipeline that extracts rowing machine workout data from photos of Concept 2 PM5 displays. Photos go through screen detection, classification, and OCR-via-LLM to produce structured workout metrics. +A computer vision pipeline that extracts rowing machine workout data (time, distance) from photos of Concept 2 PM5 displays: screen detection, classification, then Tesseract OCR with majority voting. A Claude vision reader produces the reference readings the OCR is validated against. See README.md for the approach and measured limitations. -## Pipeline +## Layout ``` -photos/ → crop_to_screen.py → screen_classifier.py → extract_rowing_data.py → rowing_results.csv +src/rowing_stats/ + cli.py `rowing-stats ` dispatcher; imports a command's module lazily + crop.py find_screen / perspective_correct / crop_screen; CropParams holds the tuned defaults + classifier.py feature-based scorer and CNN (torch imported lazily) + ocr.py tesseract subprocess, preprocessing variants, validation report + parsing.py pure vote counting over OCR text (no image code) + claude.py Claude Haiku reader, reply parsing, sanity bounds + tune.py Optuna search over CropParams, scored by the CNN + results.py results CSV rows, pace/calories, reference loading + images.py list_images / read_image / open_image + errors.py RowingStatsError hierarchy +tests/ pytest; Tesseract and the Claude client are faked +photos/ source photos +train/0, train/1 CNN training crops (not rowing / rowing) +rowing_results.csv reference readings from the Claude reader +screen_classifier_model.pth trained CNN weights ``` -1. **crop_to_screen.py** — Detects and perspective-corrects the LCD screen region using OpenCV edge detection, contour filtering, and morphological operations. Scores candidates by `edge_density × area × rectangularity`. -2. **screen_classifier.py** — Binary classifier (rowing display vs. not). Two modes: a rule-based feature scorer (no training needed) and a 4-layer CNN with batch norm (requires training on `train/` data). -3. **extract_rowing_data.py** — Sends cropped images to Claude Haiku vision API, extracts time/distance, validates against sanity bounds (pace, distance, duration), computes derived metrics (pace/500m, calories), and reads EXIF date. -4. **optimize_crop.py** — Optuna-based hyperparameter tuner for crop_to_screen.py detection parameters (12 params). Evaluates trials by counting CNN-classified rowing displays. - ## Commands ```bash -# Crop screens from photos -python crop_to_screen.py photos/ cropped/ +pip install -r requirements-dev.txt && pip install -e . +pytest -# Classify images (feature-based or CNN) -python screen_classifier.py predict --dir cropped/ -python screen_classifier.py predict --image path/to/img.jpg --mode cnn - -# Train the CNN classifier -python screen_classifier.py train --data-dir train/ - -# Extract rowing data (requires ANTHROPIC_API_KEY) -python extract_rowing_data.py --dir photos/ -python extract_rowing_data.py --image path/to/img.jpg - -# Optimize crop parameters -python optimize_crop.py --n-trials 300 --photos-dir photos/ +rowing-stats crop photos/ cropped/ +rowing-stats classify predict --dir cropped/ [--model cnn] +rowing-stats classify train --data-dir train/ +rowing-stats ocr --dir cropped/ --validate rowing_results.csv +rowing-stats claude --dir photos/ --output rowing_results.csv # requires ANTHROPIC_API_KEY +rowing-stats tune --n-trials 300 --photos-dir photos/ ``` -## Dependencies - -No requirements.txt exists. Key packages: `anthropic`, `torch`, `torchvision`, `opencv-python` (cv2), `Pillow`, `numpy`, `optuna`. - ## Key Details -- The Claude API call in extract_rowing_data.py uses `claude-haiku-4-5-20251001` for cost efficiency on a structured extraction task. -- Validation bounds in extract_rowing_data.py mirror those from a Go handler (`handle_rowing.go`): distance 100–100k meters, time 30s–2hrs, pace 1:20–2:30 /500m. -- Training data lives in `train/0/` (non-rowing, 80 samples) and `train/1/` (rowing displays, 48 samples). -- The trained CNN model is saved as `screen_classifier_model.pth`. -- `.env` contains API keys — it is gitignored and must not be committed. +- Dependencies are pinned in `requirements*.txt` (core, `-claude`, `-ml`, `-dev`) with matching extras in `pyproject.toml`. `anthropic`, `torch`, `torchvision` and `optuna` are optional and must stay lazily imported. +- Raise a `RowingStatsError` subclass rather than printing or exiting from library code. `SetupError` subclasses mean every file would fail, so CLIs stop on them; anything else is reported per file and the batch continues. +- The crop parameters, preprocessing variants and vote counting are tuned to the sample photos. A refactor should leave `rowing-stats crop` output byte-identical and the per-image lines of `rowing-stats ocr --validate` unchanged. +- The Claude call uses `claude-haiku-4-5-20251001`. Validation bounds in claude.py mirror a Go handler (`handle_rowing.go`): distance 100–100k metres, time 30s–2hrs, pace 1:20–2:30 /500m. +- `.env` is gitignored but nothing loads it; the Claude reader takes its key from the environment. diff --git a/README.md b/README.md index b08773a..eb24fc7 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,119 @@ # Rowing Stats -Extract workout data from photos of Concept 2 PM5 rowing machine displays using computer vision and Claude's vision API. +Extract workout data from photos of Concept 2 PM5 rowing machine displays, using computer vision and Tesseract OCR, with Claude's vision API as a reference reader. -## How It Works +## The problem -Photos go through a three-stage pipeline: +After a session on the rowing machine I photograph the monitor. The time and distance on it are only useful for tracking progress once they are in a table, and typing them out from dozens of photos is tedious. This tool turns a folder of those photos into one row per workout. + +The photos are handheld phone shots: the monitor is a small part of the frame, slightly rotated, lit differently each time, and surrounded by other bright rectangles (windows, walls, lockers). The camera roll also contains photos that are not of the monitor at all. + +## The approach ``` -photos/ → crop_to_screen.py → screen_classifier.py → extract_screen_data.py → rowing_results.csv +photos/ → crop → classify → ocr → results CSV + ↘ claude (reference reader) ↗ ``` -1. **Screen Detection** (`crop_to_screen.py`) — Finds and perspective-corrects the LCD screen region using OpenCV edge detection, contour filtering, and morphological operations. Candidates are scored by `edge_density × area × rectangularity`. -2. **Classification** (`screen_classifier.py`) — Filters out non-rowing images. Supports a rule-based feature scorer (no training needed) and a 4-layer CNN with batch norm. -3. **Data Extraction** (`extract_screen_data.py`) — Extracts time and distance from cropped screen images using Tesseract OCR with multiple preprocessing variants (CLAHE, thresholding, scaling) and majority-vote extraction. +Each stage is a module under `src/rowing_stats/` and a subcommand of `rowing-stats`: -There is also `extract_rowing_data.py`, which uses Claude Haiku's vision API instead of Tesseract for data extraction. This serves as a reference/test for validating OCR accuracy but is more expensive to run due to API costs. +| Stage | Module | What it does | +|---|---|---| +| Screen detection | `crop.py` | Thresholds the photo at a sweep of brightness levels and keeps contours with the right size, aspect ratio and rectangularity. The LCD is told apart from other bright regions by its edge density (it is full of digits). Candidates are scored by `edge_density × area × rectangularity`, and the best one is perspective-corrected and saved. | +| Classification | `classifier.py` | Says whether a crop is a rowing display. Two modes: a rule-based scorer on hand-crafted features (contrast, edge density, saturation), and a 4-layer CNN trained on `train/`. | +| Extraction | `ocr.py`, `parsing.py` | Runs Tesseract over six preprocessed versions of each crop (two scales; CLAHE with fixed thresholds, Otsu, inverted Otsu). Every plausible time and distance in any of the six texts is a vote, and the majority wins. | +| Reference reader | `claude.py` | Sends the photo to Claude Haiku 4.5 and asks for the time and distance as JSON, then rejects readings outside sanity bounds. It costs an API call per photo, so it is used to produce the reference readings in `rowing_results.csv` that the OCR is scored against. | +| Tuning | `tune.py` | An Optuna search over the twelve screen detection parameters, maximising how many crops the CNN accepts as rowing displays. The defaults in `crop.CropParams` came from it. | -There is also an Optuna-based hyperparameter tuner (`optimize_crop.py`) for the screen detection parameters. +`results.py` holds the results table and its derived columns (pace, calories), `images.py` the image loading, and `errors.py` the exception types. -## Setup - -### Dependencies - -``` -pip install anthropic torch torchvision opencv-python Pillow numpy optuna -``` - -### API Key - -Create a `.env` file with your Anthropic API key: - -``` -ANTHROPIC_API_KEY=sk-ant-... -``` - -## Usage - -### Full pipeline - -```bash -# 1. Crop screens from photos -python crop_to_screen.py photos/ cropped/ - -# 2. Classify — keep only rowing displays -python screen_classifier.py predict --dir cropped/ - -# 3. Extract workout data via Tesseract OCR -python extract_screen_data.py --dir cropped/ - -# 3b. (Test) Extract via Claude API — more expensive, useful for validating OCR accuracy -python extract_rowing_data.py --dir photos/ -``` - -### Individual commands - -```bash -# Classify a single image (feature-based or CNN) -python screen_classifier.py predict --image path/to/img.jpg -python screen_classifier.py predict --image path/to/img.jpg --mode cnn - -# Extract data from a single image (Tesseract OCR) -python extract_screen_data.py --image path/to/img.jpg - -# Extract data from a single image (Claude API — for testing/validation) -python extract_rowing_data.py --image path/to/img.jpg - -# Train the CNN classifier -python screen_classifier.py train --data-dir train/ - -# Optimize crop detection parameters -python optimize_crop.py --n-trials 300 --photos-dir photos/ -``` - -## Training Data - -The CNN classifier trains on labeled images in `train/`: - -- `train/0/` — non-rowing images (negatives) -- `train/1/` — rowing display images (positives) - -The trained model is saved as `screen_classifier_model.pth`. - -## Validation - -Extracted metrics are validated against sensible bounds: +The Claude reader's sanity bounds: | Metric | Min | Max | | -------- | --------- | --------- | | Distance | 100 m | 100,000 m | | Time | 30 s | 2 hrs | | Pace | 1:20/500m | 2:30/500m | + +## Running it + +You need Python 3.10 or newer and, for the `ocr` command, the [Tesseract](https://tesseract-ocr.github.io/tessdoc/Installation.html) binary on your `PATH` (`apt install tesseract-ocr`, `brew install tesseract`, or `pacman -S tesseract tesseract-data-eng`). + +```sh +python -m venv .venv && source .venv/bin/activate +pip install -r requirements.txt # pinned: enough for crop, classify (features) and ocr +pip install -e . +``` + +Two commands need more, each with its own pinned file: + +```sh +pip install -r requirements-claude.txt # the claude command; also set ANTHROPIC_API_KEY +pip install -r requirements-ml.txt # the CNN classifier and the tune command +``` + +### The pipeline + +```sh +# 1. Crop screens from photos +rowing-stats crop photos/ cropped/ + +# 2. See which crops are rowing displays +rowing-stats classify predict --dir cropped/ +rowing-stats classify predict --dir cropped/ --model cnn + +# 3. Read time and distance with Tesseract, and score against the reference +rowing-stats ocr --dir cropped/ --output ocr_results.csv +rowing-stats ocr --dir cropped/ --validate rowing_results.csv + +# Regenerate the reference with Claude (one paid API call per photo) +rowing-stats claude --dir photos/ --output rowing_results.csv +``` + +### Other commands + +```sh +rowing-stats classify predict --image path/to/img.jpg # a single image +rowing-stats classify extract --image path/to/img.jpg # print its features +rowing-stats ocr --image path/to/crop.jpg +rowing-stats claude --image path/to/img.jpg + +rowing-stats classify train --data-dir train/ # retrain the CNN +rowing-stats tune --n-trials 300 --photos-dir photos/ # search detection parameters +``` + +Every command reports a file it cannot process and carries on with the rest, and exits non-zero if any file failed. A problem that would affect every file (Tesseract not installed, no API key, missing model weights) stops the run with one message. + +### Training data + +The CNN trains on the labelled crops in `train/`: `train/0/` holds non-rowing images (81) and `train/1/` rowing displays (88, several crops per photo). The trained weights are committed as `screen_classifier_model.pth`. + +### Tests + +```sh +pip install -r requirements-dev.txt +pytest +``` + +The tests cover the vote-counting and parsing logic, the results table, the Claude reply parsing and sanity bounds, screen detection on synthetic photos, and each command's handling of unreadable images, missing tools and bad input. Tesseract and the Claude API are faked, so no test needs a key or makes a paid call; one test runs real Tesseract on a committed crop and is skipped if it is not installed. Tests that need torch or optuna are skipped when those are absent. + +## Limitations + +Measured on the 43 photos in `photos/`, against the 34 reference readings in `rowing_results.csv`, with Tesseract 5.5.3: + +| Stage | Result | +|---|---| +| Screen detection | 41 of 43 photos produce a crop | +| OCR time | 31 of 34 correct (91%) | +| OCR distance | 20 of 34 correct (59%) | + +- **The reference is itself a model's reading.** `rowing_results.csv` was produced by the Claude reader and has not been checked by hand, so "correct" means "agrees with Claude". Nine photos have no reference reading and are not scored. +- **The numbers are optimistic.** The detection parameters and the OCR preprocessing variants were chosen on these same photos. There is no held-out set. +- **Distance is unreliable.** The vote takes any 4–5 digit number on the screen as a candidate distance, and the display also shows calories per hour and projected distance, which can outvote the real one. Nothing ties a number to its position or its label. A distance read with a stray leading zero (`07337`) is also counted separately from the same number without it. +- **OCR output is not sanity-checked.** The pace bounds applied to Claude's readings are not applied to Tesseract's, so an implausible pairing such as 30:06 and 1,224 m is written out as read. +- **Only time and distance are read.** Stroke rate, split and calories on the display are ignored; the calories column is an estimate from distance. +- **The rule-based classifier does not reject much.** It accepts 86 of the 88 rowing crops in `train/1/` but also 70 of the 81 non-rowing images in `train/0/`. The CNN gets 88 of 88 and 80 of 81, but those are the images it was trained on. +- **The stages are not joined up.** Classification only prints labels; it does not filter what `ocr` reads, and there is no single command that takes a photo to a row. +- **Workout lengths are assumed.** Times under 10 minutes or over 2 hours, and distances under 1,000 m or over 50,000 m, are never read by the OCR path. +- **The photo date comes from the EXIF `DateTime` tag**, with no timezone, and only the Claude path records it (the crops carry no EXIF). +- **Screen detection assumes a lit, light-background LCD** that fills between about 0.4% and 14% of the frame.