Files
adamfandClaude Opus 5.5 e2330c6f77 Add Claude Haiku baseline
Port the display reader from the web server's rowing module as a second
extraction method: send the whole photo to claude-haiku-4-5 and ask for
elapsed time and distance as JSON. The prompt, model and reply parsing
are unchanged; what is new is reading from a file, converting the reply
to WorkoutStats so both methods produce the same rows, and accepting
ANTHROPIC_API_KEY as well as CLAUDE_API_KEY.

Select it with 'rowing-stats --method haiku'. The anthropic SDK is an
optional extra, imported only when the baseline is used, so the OCR
pipeline still installs and runs without it or an API key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:49:13 +01:00

119 lines
6.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# rowing-stats
Extract workout stats from photos of a Concept2 PM5 rowing monitor, using OpenCV to find the display and Tesseract to read it.
## The problem
After a session on the rowing machine I take a photo of the monitor. The numbers on it (time, distance, stroke rate, calories) are only useful for tracking progress if they end up in a table, and typing them out by hand from dozens of photos is tedious. This tool takes a folder of those photos and produces one row of stats per photo, timestamped from the photo's EXIF data.
The photos are handheld phone shots: the monitor is small in the frame, slightly rotated, and often has glare or reflections on the LCD.
## The approach
Each photo goes through four stages, one module each under `src/rowing_stats/`:
| Stage | Module | What it does |
|---|---|---|
| Load | `image_io.py` | Decode the image with Pillow and read the EXIF timestamp. |
| Locate | `display.py` | Blur, run Canny edge detection, and keep contours whose bounding box is roughly square and covers at least 1% of the frame. The largest is taken to be the LCD and perspective-warped to a flat 400×400 crop. |
| Read | `ocr.py` | Upscale 3×, bilateral-filter, equalise the histogram, Otsu-threshold to black and white, then run Tesseract in sparse-text mode (`--psm 11`). |
| Parse | `parsing.py` | Collapse whitespace and pull each field out of the text with a regular expression keyed on its unit label (`s/m`, `m`, `/500m`, `Cal/hr`, and so on). |
`pipeline.py` chains the stages for one file, and `cli.py` runs it over many files and writes text, JSON or CSV.
### Haiku baseline
`haiku_baseline.py` is the alternative the pipeline is measured against: send the whole photo to Claude Haiku 4.5 with a short prompt asking for the elapsed time and distance as JSON. There is no display detection or preprocessing. It reads only those two fields, makes one paid API call per photo, and needs a network connection and an API key, which is the trade-off the local pipeline exists to avoid. Both methods produce the same output rows, so their CSVs can be compared directly.
## Running it
You need Python 3.10 or newer and 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 versions
pip install -e .
```
```sh
rowing-stats # every image in photos/
rowing-stats photos/IMG_5413.JPEG # specific files or directories
rowing-stats --format csv -o stats.csv photos/ # text (default), json or csv
rowing-stats --debug-dir debug photos/ # also save each stage's image
```
To run the Haiku baseline instead, install its extra dependency and set `ANTHROPIC_API_KEY` (or `CLAUDE_API_KEY`):
```sh
pip install -r requirements-baseline.txt
rowing-stats --method haiku --format csv -o baseline.csv photos/
```
Example:
```console
$ rowing-stats --format json photos/IMG_5414.JPEG
[
{
"file": "IMG_5414.JPEG",
"datetime": "2025-11-06T19:17:40",
"elapsed_time": "30:06",
"calories": 474
}
]
```
Fields that could not be read are left out (empty in CSV). A file that cannot be processed is reported on stderr and skipped, and the exit code is 1 if any file failed. If Tesseract itself is missing, or the baseline has no API key, the run stops immediately.
The same pipeline is available from Python:
```python
from pathlib import Path
from rowing_stats import RowingStatsError, process_file
try:
result = process_file(Path("photos/IMG_5414.JPEG"))
print(result.stats.elapsed_time, result.taken_at)
except RowingStatsError as exc: # unreadable image, no display found, OCR failure
print(f"skipped: {exc}")
```
`notebooks/pipeline_walkthrough.ipynb` shows the intermediate image at each stage (`pip install -e ".[notebook]"`).
### Tests
```sh
pip install -r requirements-dev.txt
pytest
```
The tests cover the parsing and cleaning logic, image loading failures (missing, corrupt and truncated files), display detection on synthetic images, and the CLI's output and exit codes. Tesseract is stubbed out in all but one test, which runs the real pipeline on a sample photo and is skipped if Tesseract is not installed. The baseline's tests use a fake Anthropic client, so no test makes an API call or needs a key.
## Limitations
Extraction is unreliable. On the 65 sample photos in `photos/`, with Tesseract 5.5.3:
| | Photos |
|---|---|
| Display region not found | 8 |
| Display found, no field parsed | 22 |
| At least one field parsed | 35 |
No photo yields a complete set of fields. Per field: elapsed time 18, projected distance 19, distance 5, calories 5; stroke rate, split, average split and Cal/hr are never read. These are counts of fields *parsed*, not fields verified correct. There is no hand-labelled ground truth, and some values are visible misreads (an elapsed time of `0:06` where the leading digit was lost, for example). Treat the output as a first draft to check against the photo, not as data.
The causes, roughly in order of impact:
- **Display detection picks the wrong square.** The largest square contour is often the whole monitor housing rather than the LCD, so the crop includes buttons and the logo and the digits are too small to read. When the LCD's edge is broken by glare, no square is found at all.
- **Whole-screen OCR.** Tesseract is run once over the entire crop. Small unit labels (`s/m`, `Cal/hr`, `/500m`) are rarely recognised, and the parser depends on them to tell fields apart. Cropping each row of the fixed PM5 layout and reading it separately with a digits-only model would remove that dependency.
- **Global thresholding.** A single Otsu threshold turns glare and shadow gradients into solid black patches that hide digits.
- **Heuristic parsing.** An unlabelled five-digit number is assumed to be the projected distance, which is wrong when it is really the distance with its `m` label missed.
The Haiku baseline has not yet been run over the sample photos, so there are no baseline numbers to set against the table above.
Other known gaps:
- Only the PM5's default workout screens are handled. Fields are matched by label, so other display modes (watts, force curve, pace boat) are ignored.
- EXIF orientation is not applied; photos are assumed to be stored upright.
- The photo timestamp comes from the EXIF `DateTime` tag and carries no timezone.
- Values are not sanity-checked beyond their format (a stroke rate of 99 would be accepted).