Compare commits

13 Commits
Author SHA1 Message Date
adamfandClaude Opus 5.5 36fae9cdc3 Rewrite README for the packaged pipeline
Cover the problem, the approach, how to run it and its measured
limitations, and correct what no longer matched the code (the --mode
flag, the .env file, the training directory). Update CLAUDE.md to the
new layout and commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:08:54 +01:00
adamfandClaude Opus 5.5 7b19d8f3e9 Restructure scripts into the rowing_stats package
Move the five top-level scripts into src/rowing_stats, one module per
pipeline stage, behind a single 'rowing-stats' command with a subcommand
each (crop, classify, ocr, claude, tune). Add type hints throughout,
packaging metadata, pinned requirements files, and a test suite.

Failures are now typed exceptions under RowingStatsError instead of
prints, None returns and sys.exit: unreadable or missing images, photos
with no detectable screen, a missing tesseract binary, tesseract
failures, unusable Claude replies, and missing optional dependencies,
model weights or API credentials. Each command reports a bad file and
carries on, stops once on a setup problem, and returns a non-zero exit
code when something failed.

Crops, classifier labels and OCR votes are unchanged. Other changes:
- crop.find_screen takes a CropParams, so the tuner searches the real
  detection code instead of a copy of it.
- OCR validation scores only images that have a reference reading;
  images without one were counted as wrong.
- 'classify train --data-dir train/' works with the repository layout
  (it looked for train/train), and the CNN weights path defaults to the
  committed screen_classifier_model.pth instead of a missing model.pth.
- The CNN is loaded once per run rather than once per image.
- ocr and claude can write their readings with --output.
- crop no longer defaults to /mnt/user-data paths.
- Pure vote-counting moved to parsing.py; the unused 'expected' argument
  that let a caller steer the vote is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:08:01 +01:00
adamf c447cc41ea Optimise parameters 2026-03-16 15:20:59 +00:00
adamf ee8fa0960d Prioritize older images & make use MM:SS format 2026-03-16 14:00:35 +00:00
adamf 7383209804 Ignore api keys 2026-03-16 13:46:26 +00:00
adamf 3733f1e99f Claude cause quick 2026-03-16 13:46:18 +00:00
adamf f0184319c6 Crops to rowing machine screen - can be trained with optimize_crop.py and screen_classifier 2026-03-16 13:46:02 +00:00
adamf 2e386a4297 Uses claude to achieve extracting rowing times and distance 2026-03-16 13:44:57 +00:00
adamf 1624a7a40a Add temp files for training classifier 2026-03-16 13:44:09 +00:00
adamf 4abcb10194 Make new file for each step of processing 2026-03-16 11:54:37 +00:00
adamf ef0abd57d4 plot image 2026-01-27 11:28:15 +00:00
adamf a58c86ddee ignore pycache 2026-01-27 11:27:56 +00:00
adamf 25bb27f32a init commit 2026-01-26 19:07:38 +00:00
231 changed files with 2918 additions and 1416 deletions
+2 -1
View File
@@ -2,6 +2,7 @@ __pycache__/
*.egg-info/
.pytest_cache/
.venv/
.env
.idea/
.ipynb_checkpoints/
/cropped/
/debug/
+50
View File
@@ -0,0 +1,50 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
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.
## Layout
```
src/rowing_stats/
cli.py `rowing-stats <command>` 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
```
## Commands
```bash
pip install -r requirements-dev.txt && pip install -e .
pytest
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/
```
## Key Details
- 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.
+71 -70
View File
@@ -1,84 +1,92 @@
# rowing-stats
# Rowing Stats
Extract workout stats from photos of a Concept2 PM5 rowing monitor, using OpenCV to find the display and Tesseract to read it.
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.
## 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.
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 small in the frame, slightly rotated, and often has glare or reflections on the LCD.
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
Each photo goes through four stages, one module each under `src/rowing_stats/`:
```
photos/ → crop → classify → ocr → results CSV
↘ claude (reference reader) ↗
```
Each stage is a module under `src/rowing_stats/` and a subcommand of `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). |
| 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. |
`pipeline.py` chains the stages for one file, and `cli.py` runs it over many files and writes text, JSON or CSV.
`results.py` holds the results table and its derived columns (pace, calories), `images.py` the image loading, and `errors.py` the exception types.
### Haiku baseline
The Claude reader's sanity bounds:
`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.
| 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 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`).
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 versions
pip install -r requirements.txt # pinned: enough for crop, classify (features) and ocr
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`):
Two commands need more, each with its own pinned file:
```sh
pip install -r requirements-baseline.txt
rowing-stats --method haiku --format csv -o baseline.csv photos/
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
```
Example:
### The pipeline
```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
}
]
```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
```
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.
### Other commands
The same pipeline is available from Python:
```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
```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}")
rowing-stats classify train --data-dir train/ # retrain the CNN
rowing-stats tune --n-trials 300 --photos-dir photos/ # search detection parameters
```
`notebooks/pipeline_walkthrough.ipynb` shows the intermediate image at each stage (`pip install -e ".[notebook]"`).
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
@@ -87,32 +95,25 @@ 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.
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
Extraction is unreliable. On the 65 sample photos in `photos/`, with Tesseract 5.5.3:
Measured on the 43 photos in `photos/`, against the 34 reference readings in `rowing_results.csv`, with Tesseract 5.5.3:
| | Photos |
| Stage | Result |
|---|---|
| Display region not found | 8 |
| Display found, no field parsed | 22 |
| At least one field parsed | 35 |
| Screen detection | 41 of 43 photos produce a crop |
| OCR time | 31 of 34 correct (91%) |
| OCR distance | 20 of 34 correct (59%) |
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).
- **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.
-121
View File
@@ -1,121 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "dc4ef0c3",
"metadata": {},
"source": [
"# Pipeline walkthrough\n",
"\n",
"Step through the extraction pipeline on a single photo to see what each stage produces.\n",
"Requires `pip install -e \".[notebook]\"` from the repository root."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "221851b3",
"metadata": {},
"outputs": [],
"source": [
"import math\n",
"from pathlib import Path\n",
"\n",
"import cv2 as cv\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"from rowing_stats.display import crop_display\n",
"from rowing_stats.image_io import get_datetime_taken, load_image, pil_to_cv\n",
"from rowing_stats.ocr import ocr_image, preprocess_for_ocr\n",
"from rowing_stats.parsing import parse_stats"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "438ecbd5",
"metadata": {},
"outputs": [],
"source": [
"def plot_images(imgs: list[np.ndarray]):\n",
" \"\"\"\n",
" Plot a list of images in a single matplotlib figure.\n",
"\n",
" Parameters\n",
" ----------\n",
" imgs : list[np.ndarray]\n",
" List of images (H×W greyscale or H×W×3 BGR arrays).\n",
" \"\"\"\n",
" if not imgs:\n",
" return\n",
"\n",
" n = len(imgs)\n",
" cols = math.ceil(math.sqrt(n))\n",
" rows = math.ceil(n / cols)\n",
"\n",
" fig, axes = plt.subplots(rows, cols, figsize=(cols * 5, rows * 5))\n",
" axes = np.atleast_1d(axes).ravel()\n",
"\n",
" for ax, img in zip(axes, imgs):\n",
" if img.ndim == 2:\n",
" ax.imshow(img, cmap=\"gray\")\n",
" else:\n",
" ax.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))\n",
" ax.axis(\"off\")\n",
"\n",
" # Hide any unused subplots\n",
" for ax in axes[len(imgs):]:\n",
" ax.axis(\"off\")\n",
"\n",
" plt.tight_layout()\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "da8bada5",
"metadata": {},
"outputs": [],
"source": [
"photos_path = Path(\"../photos\")\n",
"img = load_image(photos_path / \"IMG_5413.JPEG\")\n",
"arr = pil_to_cv(img)\n",
"print(get_datetime_taken(img))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cb01649f",
"metadata": {},
"outputs": [],
"source": [
"warped = crop_display(arr)\n",
"plot_images([arr, warped, preprocess_for_ocr(warped)])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5dd910f8",
"metadata": {},
"outputs": [],
"source": [
"text = ocr_image(warped)\n",
"print(text)\n",
"parse_stats(text)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 718 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 619 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 631 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 695 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 480 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 718 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 638 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 837 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 822 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 926 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 709 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 714 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 542 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 892 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 892 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 743 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 773 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 963 KiB

+4 -5
View File
@@ -5,20 +5,19 @@ build-backend = "setuptools.build_meta"
[project]
name = "rowing-stats"
version = "0.1.0"
description = "Extract rowing stats from photos of a Concept2 PM5 monitor using OpenCV and Tesseract OCR"
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",
"pytesseract>=0.3.10",
]
[project.optional-dependencies]
baseline = ["anthropic>=1.0"]
dev = ["pytest>=8.0", "anthropic>=1.0"]
notebook = ["ipykernel", "matplotlib"]
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"
-3
View File
@@ -1,3 +0,0 @@
# Only needed for the Claude Haiku baseline (rowing-stats --method haiku).
-r requirements.txt
anthropic==1.12.1
+3
View File
@@ -0,0 +1,3 @@
# Adds what `rowing-stats claude` needs.
-r requirements.txt
anthropic==1.12.1
+3 -1
View File
@@ -1,2 +1,4 @@
-r requirements-baseline.txt
# Everything, plus the test runner.
-r requirements-claude.txt
-r requirements-ml.txt
pytest==9.1.0
+5
View File
@@ -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
+3 -3
View File
@@ -1,6 +1,6 @@
# Exact versions the pipeline was developed and tested against (Python 3.14).
# Also requires the Tesseract binary (tested with 5.5.3) — see README.
# 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
pytesseract==0.3.13
+35
View File
@@ -0,0 +1,35 @@
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
IMG_5414.JPEG,30:06,7337,2:03.1,489,2025-11-06 19:17:40
IMG_5416.JPEG,40:05,9671,2:04.3,645,2025-11-07 15:06:23
IMG_5417.JPEG,35:07,8629,2:02.1,575,2025-11-08 12:02:51
IMG_5418.JPEG,30:06,7352,2:02.8,490,2025-11-08 15:32:17
IMG_5428.JPEG,35:06,8543,2:03.3,570,2025-11-13 17:12:54
IMG_5443.JPEG,30:07,7383,2:02.4,492,2025-11-18 18:15:02
IMG_5448.JPEG,30:06,7488,2:00.6,499,2025-11-29 16:21:54
IMG_5449.JPEG,30:06,7450,2:01.2,497,2025-11-30 19:51:28
IMG_5451.JPEG,20:07,5060,1:59.3,337,2025-12-02 20:37:48
IMG_5454.JPEG,30:06,7650,1:58.0,510,2025-12-04 22:05:44
IMG_5457.JPEG,30:04,7613,1:58.5,508,2025-12-10 20:17:27
IMG_5460.JPEG,30:07,7601,1:58.9,507,2025-12-12 18:50:41
IMG_5461.JPEG,15:05,3907,1:55.8,260,2025-12-13 00:22:41
IMG_5463.JPEG,30:05,7551,1:59.5,503,2025-12-16 00:05:34
IMG_5464.JPEG,15:06,3791,1:59.5,253,2025-12-17 17:43:48
IMG_5468.JPEG,30:06,7284,2:04.0,486,2025-12-20 23:00:16
IMG_5471.JPEG,30:06,7586,1:59.0,506,2025-12-23 09:49:22
IMG_5472.JPEG,30:07,7504,2:00.4,500,2025-12-24 11:58:45
IMG_5474.JPEG,30:06,7493,2:00.5,500,2025-12-27 10:33:33
IMG_5475.JPEG,30:05,7475,2:00.7,498,2025-12-28 12:59:48
IMG_5476.JPEG,33:37,7972,2:06.5,531,2025-12-29 09:17:36
IMG_5477.JPEG,30:06,7504,2:00.3,500,2025-12-29 13:25:33
IMG_5479.JPEG,30:06,7663,1:57.8,511,2026-01-05 17:14:00
IMG_5483.JPEG,30:07,7575,1:59.3,505,2026-01-07 23:05:19
IMG_5484.JPEG,15:09,3816,1:59.1,254,2026-01-08 19:30:33
IMG_5485.JPEG,20:05,4802,2:05.5,320,2026-01-10 20:22:14
IMG_5486.JPEG,30:07,7453,2:01.2,497,2026-01-11 19:21:03
IMG_5488.JPEG,30:06,7496,2:00.5,500,2026-01-12 18:12:31
IMG_5489.JPEG,30:06,7318,2:03.4,488,2026-01-13 18:35:20
IMG_5513.JPEG,30:29,7586,2:00.5,506,2026-01-18 18:12:02
IMG_5519.JPEG,30:07,7547,1:59.7,503,2026-01-21 18:45:42
IMG_5522.JPEG,30:07,7407,2:02.0,494,2026-01-23 20:02:53
IMG_5523.JPEG,30:06,7559,1:59.5,504,2026-01-25 17:34:42
1 image time distance_m pace_per_500m calories date_taken
2 IMG_5413.JPEG 30:06 7283 2:04.0 486 2025-11-05 12:08:00
3 IMG_5414.JPEG 30:06 7337 2:03.1 489 2025-11-06 19:17:40
4 IMG_5416.JPEG 40:05 9671 2:04.3 645 2025-11-07 15:06:23
5 IMG_5417.JPEG 35:07 8629 2:02.1 575 2025-11-08 12:02:51
6 IMG_5418.JPEG 30:06 7352 2:02.8 490 2025-11-08 15:32:17
7 IMG_5428.JPEG 35:06 8543 2:03.3 570 2025-11-13 17:12:54
8 IMG_5443.JPEG 30:07 7383 2:02.4 492 2025-11-18 18:15:02
9 IMG_5448.JPEG 30:06 7488 2:00.6 499 2025-11-29 16:21:54
10 IMG_5449.JPEG 30:06 7450 2:01.2 497 2025-11-30 19:51:28
11 IMG_5451.JPEG 20:07 5060 1:59.3 337 2025-12-02 20:37:48
12 IMG_5454.JPEG 30:06 7650 1:58.0 510 2025-12-04 22:05:44
13 IMG_5457.JPEG 30:04 7613 1:58.5 508 2025-12-10 20:17:27
14 IMG_5460.JPEG 30:07 7601 1:58.9 507 2025-12-12 18:50:41
15 IMG_5461.JPEG 15:05 3907 1:55.8 260 2025-12-13 00:22:41
16 IMG_5463.JPEG 30:05 7551 1:59.5 503 2025-12-16 00:05:34
17 IMG_5464.JPEG 15:06 3791 1:59.5 253 2025-12-17 17:43:48
18 IMG_5468.JPEG 30:06 7284 2:04.0 486 2025-12-20 23:00:16
19 IMG_5471.JPEG 30:06 7586 1:59.0 506 2025-12-23 09:49:22
20 IMG_5472.JPEG 30:07 7504 2:00.4 500 2025-12-24 11:58:45
21 IMG_5474.JPEG 30:06 7493 2:00.5 500 2025-12-27 10:33:33
22 IMG_5475.JPEG 30:05 7475 2:00.7 498 2025-12-28 12:59:48
23 IMG_5476.JPEG 33:37 7972 2:06.5 531 2025-12-29 09:17:36
24 IMG_5477.JPEG 30:06 7504 2:00.3 500 2025-12-29 13:25:33
25 IMG_5479.JPEG 30:06 7663 1:57.8 511 2026-01-05 17:14:00
26 IMG_5483.JPEG 30:07 7575 1:59.3 505 2026-01-07 23:05:19
27 IMG_5484.JPEG 15:09 3816 1:59.1 254 2026-01-08 19:30:33
28 IMG_5485.JPEG 20:05 4802 2:05.5 320 2026-01-10 20:22:14
29 IMG_5486.JPEG 30:07 7453 2:01.2 497 2026-01-11 19:21:03
30 IMG_5488.JPEG 30:06 7496 2:00.5 500 2026-01-12 18:12:31
31 IMG_5489.JPEG 30:06 7318 2:03.4 488 2026-01-13 18:35:20
32 IMG_5513.JPEG 30:29 7586 2:00.5 506 2026-01-18 18:12:02
33 IMG_5519.JPEG 30:07 7547 1:59.7 503 2026-01-21 18:45:42
34 IMG_5522.JPEG 30:07 7407 2:02.0 494 2026-01-23 20:02:53
35 IMG_5523.JPEG 30:06 7559 1:59.5 504 2026-01-25 17:34:42
Binary file not shown.
+1 -28
View File
@@ -1,30 +1,3 @@
"""Extract rowing stats from photos of a Concept2 PM5 monitor."""
from rowing_stats.errors import (
DisplayNotFoundError,
ImageLoadError,
NotConfigured,
OcrError,
ReadError,
RowingStatsError,
TesseractNotInstalledError,
)
from rowing_stats.parsing import WorkoutStats, clean_ocr_text, parse_stats
from rowing_stats.pipeline import ExtractionResult, process_file
"""Extract workout data from photos of a Concept 2 PM5 rowing machine display."""
__version__ = "0.1.0"
__all__ = [
"DisplayNotFoundError",
"ExtractionResult",
"ImageLoadError",
"NotConfigured",
"OcrError",
"ReadError",
"RowingStatsError",
"TesseractNotInstalledError",
"WorkoutStats",
"clean_ocr_text",
"parse_stats",
"process_file",
]
+479
View File
@@ -0,0 +1,479 @@
"""
Rowing Machine Display Classifier
==================================
Binary classifier: 1 = rowing machine display, 0 = not rowing machine.
Two modes:
1. Feature-based (works immediately, no training needed)
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)
rowing-stats classify predict --image path/to/image.jpg
# 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 functools
import json
import sys
from collections.abc import Sequence
from pathlib import Path
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: Path) -> dict[str, float]:
"""Extract hand-crafted features that distinguish rowing displays."""
img = open_image(image_path).convert("RGB")
gray = img.convert("L")
# Resize for consistent analysis
gray_resized = gray.resize((256, 256))
img_resized = img.resize((256, 256))
pixels = np.array(gray_resized, dtype=np.float64)
color_pixels = np.array(img_resized, dtype=np.float64)
features = {}
# 1. Contrast: rowing displays have high contrast (dark text on light bg)
features["std_dev"] = float(np.std(pixels))
# 2. Bimodality: displays tend toward two clusters (text vs background)
hist, _ = np.histogram(pixels, bins=32, range=(0, 256))
hist_norm = hist / hist.sum()
features["entropy"] = float(
-np.sum(hist_norm[hist_norm > 0] * np.log2(hist_norm[hist_norm > 0]))
)
# 3. Edge density: text/numbers create lots of edges
edges = gray_resized.filter(ImageFilter.FIND_EDGES)
edge_pixels = np.array(edges, dtype=np.float64)
features["edge_density"] = float(np.mean(edge_pixels > 30))
# 4. Horizontal line features: displays have horizontal separators
sobel_h = gray_resized.filter(
ImageFilter.Kernel(
size=(3, 3), kernel=[-1, -2, -1, 0, 0, 0, 1, 2, 1], scale=1, offset=128
)
)
sobel_pixels = np.abs(np.array(sobel_h, dtype=np.float64) - 128)
features["h_line_strength"] = float(np.mean(sobel_pixels > 20))
# 5. Color saturation: rowing displays are typically low-saturation
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.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)
features["dark_pixel_ratio"] = float(np.mean(pixels < 80))
# 7. Bright pixel ratio: displays have bright background regions
features["bright_pixel_ratio"] = float(np.mean(pixels > 180))
# 8. Texture uniformity via local variance
blurred = np.array(
gray_resized.filter(ImageFilter.GaussianBlur(5)), dtype=np.float64
)
local_var = np.mean((pixels - blurred) ** 2)
features["local_variance"] = float(local_var)
return features
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).
"""
feats = extract_features(image_path)
if verbose:
print("\n Feature values:")
for k, v in feats.items():
print(f" {k:>20s}: {v:.4f}")
score = 0.0
# Rowing displays: high contrast
if feats["std_dev"] > 50:
score += 0.15
if feats["std_dev"] > 70:
score += 0.10
# High edge density (text/numbers)
if feats["edge_density"] > 0.08:
score += 0.15
if feats["edge_density"] > 0.15:
score += 0.10
# Horizontal lines (separators between rows of data)
if feats["h_line_strength"] > 0.06:
score += 0.10
# Low saturation (monochrome-ish displays)
if feats["mean_saturation"] < 0.15:
score += 0.10
# Bimodal histogram (text vs background)
if feats["entropy"] < 3.8:
score += 0.10
# Has both dark and bright regions
if feats["dark_pixel_ratio"] > 0.15 and feats["bright_pixel_ratio"] > 0.15:
score += 0.15
# High local variance = structured content
if feats["local_variance"] > 200:
score += 0.10
score = min(score, 1.0)
label = 1 if score >= 0.45 else 0
confidence = score if label == 1 else 1.0 - score
return label, confidence
# ---------------------------------------------------------------------------
# CNN-based classifier (requires training)
# ---------------------------------------------------------------------------
def _require_torch() -> None:
"""Raise MissingDependencyError unless torch and torchvision can be imported."""
try:
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) -> None:
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(128, 256, 3, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.AdaptiveAvgPool2d((4, 4)),
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(256 * 4 * 4, 128),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(128, 1),
)
def forward(self, x: "torch.Tensor") -> "torch.Tensor":
return self.classifier(self.features(x))
return RowingCNN()
def train_cnn(
data_dir: Path,
epochs: int = 20,
lr: float = 1e-3,
save_path: Path = DEFAULT_MODEL_PATH,
val_dir: Path | None = None,
) -> None:
"""
Train the CNN. Expects data_dir with structure:
data_dir/
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
from torchvision import datasets, transforms
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Training on: {device}")
transform_train = transforms.Compose(
[
transforms.Resize((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(10),
transforms.ColorJitter(brightness=0.2, contrast=0.2),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
transform_val = transforms.Compose(
[
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
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
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)}")
model = get_cnn_model().to(device)
criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)
best_acc = 0.0
for epoch in range(epochs):
model.train()
running_loss, correct, total = 0.0, 0, 0
for inputs, labels in train_loader:
inputs, labels = inputs.to(device), labels.float().to(device)
optimizer.zero_grad()
outputs = model(inputs).squeeze(1)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
preds = (torch.sigmoid(outputs) > 0.5).long()
correct += (preds == labels.long()).sum().item()
total += labels.size(0)
scheduler.step()
train_acc = correct / total
avg_loss = running_loss / total
line = f" Epoch {epoch + 1:>3d}/{epochs} loss={avg_loss:.4f} train_acc={train_acc:.3f}"
if val_loader:
model.eval()
val_correct, val_total = 0, 0
with torch.no_grad():
for inputs, labels in val_loader:
inputs, labels = inputs.to(device), labels.float().to(device)
outputs = model(inputs).squeeze(1)
preds = (torch.sigmoid(outputs) > 0.5).long()
val_correct += (preds == labels.long()).sum().item()
val_total += labels.size(0)
val_acc = val_correct / val_total
line += f" val_acc={val_acc:.3f}"
if val_acc > best_acc:
best_acc = val_acc
torch.save(model.state_dict(), save_path)
line += " *saved*"
else:
torch.save(model.state_dict(), save_path)
print(line)
print(f"\nModel saved to {save_path}")
@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()
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(
[
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
img = open_image(image_path).convert("RGB")
tensor = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
output = model(tensor).squeeze()
prob = torch.sigmoid(output).item()
label = 1 if prob > 0.5 else 0
confidence = prob if label == 1 else 1.0 - prob
return label, confidence
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
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")
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", 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", 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", 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", type=Path, required=True)
return parser
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]
# Classify each image
rowing_count = 0
errors = 0
for img_path in image_paths:
try:
if args.model == "features":
label, conf = feature_based_predict(img_path, verbose=args.verbose)
else:
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
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
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__":
sys.exit(main())
+331
View File
@@ -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<base>.+?)(?:\s+\((?P<num>\d+)\))?(?P<ext>\.\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())
+25 -139
View File
@@ -1,152 +1,38 @@
"""
Extract rowing stats from Concept2 PM5 monitor photos using OpenCV + Tesseract OCR.
"""The `rowing-stats` command: one subcommand per pipeline stage."""
Usage:
rowing-stats # process every image in photos/
rowing-stats photos/IMG_5485.JPEG photos/IMG_5550.JPEG
rowing-stats --format csv -o stats.csv photos/
rowing-stats --debug-dir debug ... # save intermediate images
rowing-stats --method haiku photos/ # read with Claude instead of OCR
"""
import argparse
import csv
import json
import logging
import importlib
import sys
from collections.abc import Sequence
from dataclasses import fields
from pathlib import Path
from typing import TextIO
from rowing_stats.errors import (
NotConfigured,
RowingStatsError,
TesseractNotInstalledError,
)
from rowing_stats.ocr import DEFAULT_PSM
from rowing_stats.parsing import WorkoutStats
from rowing_stats.pipeline import ExtractionResult, process_file
logger = logging.getLogger("rowing_stats")
IMAGE_SUFFIXES = {".jpeg", ".jpg", ".png"}
DEFAULT_PHOTOS_DIR = Path("photos")
CSV_COLUMNS = ["file", "datetime", *(f.name for f in fields(WorkoutStats))]
# 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 collect_paths(inputs: Sequence[Path]) -> list[Path]:
"""Expand directories into the image files they contain; keep files as given."""
paths: list[Path] = []
for item in inputs:
if item.is_dir():
paths.extend(sorted(p for p in item.iterdir()
if p.suffix.lower() in IMAGE_SUFFIXES))
else:
paths.append(item)
return paths
def write_text(results: Sequence[ExtractionResult], out: TextIO) -> None:
for result in results:
out.write(f"\n{'=' * 60}\n")
out.write(f"File: {result.file}\n")
out.write("Raw output:\n")
out.write(f"{result.raw_text}\n")
out.write("Parsed stats:\n")
for k, v in result.to_dict().items():
out.write(f" {k}: {v}\n")
def write_json(results: Sequence[ExtractionResult], out: TextIO) -> None:
json.dump([r.to_dict() for r in results], out, indent=2)
out.write("\n")
def write_csv(results: Sequence[ExtractionResult], out: TextIO) -> None:
writer = csv.DictWriter(out, fieldnames=CSV_COLUMNS)
writer.writeheader()
writer.writerows(r.to_dict() for r in results)
WRITERS = {"text": write_text, "json": write_json, "csv": write_csv}
METHODS = ("ocr", "haiku")
def extract(path: Path, args: argparse.Namespace) -> ExtractionResult:
"""Run the chosen extraction method on one file."""
if args.method == "haiku":
try:
from rowing_stats import haiku_baseline
except ImportError as exc:
raise NotConfigured(
'the haiku baseline needs the anthropic SDK: pip install -e ".[baseline]"'
) from exc
return haiku_baseline.process_file(path)
return process_file(path, debug_dir=args.debug_dir, psm=args.psm)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="rowing-stats",
description="Extract rowing stats from photos of a Concept2 PM5 monitor.",
)
parser.add_argument("paths", nargs="*", type=Path,
help=f"image files or directories (default: {DEFAULT_PHOTOS_DIR}/)")
parser.add_argument("--method", choices=METHODS, default="ocr",
help="ocr: OpenCV + Tesseract (default); haiku: the Claude Haiku "
"baseline, which reads elapsed time and distance only and "
"makes one paid API call per image")
parser.add_argument("--format", choices=sorted(WRITERS), default="text",
help="output format (default: text)")
parser.add_argument("-o", "--output", type=Path,
help="write results to this file instead of stdout")
parser.add_argument("--debug-dir", type=Path,
help="save intermediate images (contours, crop, OCR input) here "
"(ocr only)")
parser.add_argument("--psm", type=int, default=DEFAULT_PSM,
help=f"Tesseract page segmentation mode (default: {DEFAULT_PSM}; "
"ocr only)")
parser.add_argument("-v", "--verbose", action="store_true",
help="log each file as it is processed")
return parser
def usage() -> str:
lines = ["usage: rowing-stats <command> [options]", "", "commands:"]
lines += [f" {name:<10}{help_}" for name, (_, help_) in COMMANDS.items()]
lines += ["", "Run 'rowing-stats <command> --help' for a command's options."]
return "\n".join(lines)
def main(argv: Sequence[str] | None = None) -> int:
"""Run the CLI. Returns 0 if every file was processed, 1 if any failed."""
args = build_parser().parse_args(argv)
logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING,
format="%(levelname)s: %(message)s", stream=sys.stderr)
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
paths = collect_paths(args.paths or [DEFAULT_PHOTOS_DIR])
if not paths:
logger.error("no images found")
return 1
results: list[ExtractionResult] = []
failures = 0
for path in paths:
logger.info("processing %s", path)
try:
results.append(extract(path, args))
except (TesseractNotInstalledError, NotConfigured) as exc:
# Environment problem, not a bad photo — every other file would fail too
logger.error("%s", exc)
return 1
except RowingStatsError as exc:
logger.error("%s: %s", path.name, exc)
failures += 1
writer = WRITERS[args.format]
if args.output is not None:
with args.output.open("w", newline="") as fh:
writer(results, fh)
else:
writer(results, sys.stdout)
if failures:
logger.warning("%d of %d files could not be processed", failures, len(paths))
return 1 if failures else 0
module = importlib.import_module(COMMANDS[args[0]][0])
return module.main(args[1:])
if __name__ == "__main__":
+247
View File
@@ -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())
-77
View File
@@ -1,77 +0,0 @@
"""Locating the PM5's LCD in a photo and warping it to a flat square."""
from pathlib import Path
import cv2 as cv
import numpy as np
from rowing_stats.errors import DisplayNotFoundError
WARPED_SIZE = 400
MIN_AREA_FRACTION = 0.01
MIN_ASPECT = 0.9
MAX_ASPECT = 1.1
def order_points(pts: np.ndarray) -> np.ndarray:
"""Order four corner points as top-left, top-right, bottom-right, bottom-left."""
pts = pts.reshape(4, 2)
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)] # top-left
rect[2] = pts[np.argmax(s)] # bottom-right
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)] # top-right
rect[3] = pts[np.argmax(diff)] # bottom-left
return rect
def find_display_candidates(arr: np.ndarray) -> list[np.ndarray]:
"""Return the bounding boxes of every large, roughly square contour."""
blur = cv.GaussianBlur(arr, (7, 7), 0)
edges = cv.Canny(blur, 50, 100)
contours, _ = cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
img_area = arr.shape[0] * arr.shape[1]
candidates = []
for cnt in contours:
rect = cv.minAreaRect(cnt)
(_, (w, h), _) = rect
if w == 0 or h == 0:
continue
box = cv.boxPoints(rect).reshape((-1, 1, 2))
if cv.contourArea(box) < MIN_AREA_FRACTION * img_area:
continue
if MIN_ASPECT < w / h < MAX_ASPECT:
candidates.append(box)
return candidates
def crop_display(arr: np.ndarray, debug_prefix: Path | None = None) -> np.ndarray:
"""
Detect the square LCD display on the PM5 monitor and perspective-warp it
to a WARPED_SIZE×WARPED_SIZE image.
Raises DisplayNotFoundError if no square region is found. If debug_prefix
is given, the candidate outlines and the warped crop are written next to it.
"""
candidates = find_display_candidates(arr)
if not candidates:
raise DisplayNotFoundError("could not detect display region")
if debug_prefix is not None:
dbg = arr.copy()
cv.drawContours(dbg, [c.astype(np.int32) for c in candidates], -1, (0, 255, 0), 3)
cv.imwrite(f"{debug_prefix}_contours.png", dbg)
best = max(candidates, key=cv.contourArea)
rect = order_points(best)
last = WARPED_SIZE - 1
dst = np.array([[0, 0], [last, 0], [last, last], [0, last]], dtype="float32")
mat = cv.getPerspectiveTransform(rect, dst)
warped = cv.warpPerspective(arr, mat, (WARPED_SIZE, WARPED_SIZE))
if debug_prefix is not None:
cv.imwrite(f"{debug_prefix}_warped.png", warped)
return warped
+25 -9
View File
@@ -1,4 +1,8 @@
"""Exceptions raised by the extraction pipeline."""
"""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):
@@ -9,21 +13,33 @@ class ImageLoadError(RowingStatsError):
"""The file is missing, unreadable, or not a decodable image."""
class DisplayNotFoundError(RowingStatsError):
"""No LCD-shaped region could be located in the photo."""
class ScreenNotFoundError(RowingStatsError):
"""No LCD-like region could be located in the photo."""
class OcrError(RowingStatsError):
"""Tesseract failed while reading the image."""
"""Tesseract failed while reading an image."""
class TesseractNotInstalledError(OcrError):
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 ReadError(RowingStatsError):
"""The Claude baseline could not read the display."""
class MissingDependencyError(SetupError):
"""An optional Python dependency for this command is not installed."""
class NotConfigured(ReadError):
"""The Claude baseline has no API key, or its SDK 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."""
-200
View File
@@ -1,200 +0,0 @@
"""Read a rowing machine display from a photo with Claude.
The baseline the OpenCV + Tesseract pipeline is measured against: hand the
whole photo to Claude Haiku and ask for the elapsed time and distance. It
reads only those two fields, costs an API call per photo, and needs a key and
a network connection - but it needs no display detection at all.
Requires the `baseline` extra (`pip install -e ".[baseline]"`), which is why
nothing else in the package imports this module at import time.
"""
import base64
import functools
import logging
import os
from pathlib import Path
import anthropic
from pydantic import BaseModel, Field, ValidationError
from rowing_stats.errors import ImageLoadError, NotConfigured, ReadError
from rowing_stats.image_io import get_datetime_taken, load_image
from rowing_stats.parsing import WorkoutStats
from rowing_stats.pipeline import ExtractionResult
log = logging.getLogger(__name__)
MODEL = "claude-haiku-4-5"
# 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), so
# the worst case is roughly three of these plus backoff.
TIMEOUT_S = 30.0
# The first of these that is set is used as the API key.
API_KEY_ENV_VARS = ("CLAUDE_API_KEY", "ANTHROPIC_API_KEY")
# The image types the Anthropic API accepts for an image block, by file suffix.
MEDIA_TYPES = {
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
}
# The keys named here are the JSON contract: RowingReading's field names below
# must match them.
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."""
class RowingReading(BaseModel):
"""What Claude read off the display.
camelCase on purpose: these are the keys the prompt asks for. A key the
model left out defaults to 0, which `to_stats` reports as not found.
"""
timeMinutes: int = Field(0, ge=0)
timeSeconds: int = Field(0, ge=0)
distance: int = Field(0, ge=0)
def to_stats(self) -> WorkoutStats:
"""Convert to the pipeline's stats, in the format the monitor shows."""
return WorkoutStats(
elapsed_time=format_elapsed(self.timeMinutes, self.timeSeconds),
distance_m=self.distance or None,
)
def format_elapsed(minutes: int, seconds: int) -> str | None:
"""Format a duration as the PM5 shows it: M:SS, or H:MM:SS from an hour up."""
total = minutes * 60 + seconds
if total == 0:
return None
hours, rest = divmod(total, 3600)
mins, secs = divmod(rest, 60)
if hours:
return f"{hours}:{mins:02}:{secs:02}"
return f"{mins}:{secs:02}"
@functools.lru_cache(maxsize=1)
def _client() -> anthropic.Anthropic:
"""Build the Anthropic client on first use.
Lazy so that a missing key only breaks the baseline, and only when it is
actually asked to read something.
"""
key = next((os.environ[v] for v in API_KEY_ENV_VARS if os.environ.get(v)), "")
if not key:
raise NotConfigured(f"none of {', '.join(API_KEY_ENV_VARS)} is set")
return anthropic.Anthropic(api_key=key, timeout=TIMEOUT_S)
def strip_markdown_fence(raw: str) -> str:
"""Remove a surrounding markdown code fence from a model's response.
The prompt asks for bare JSON and the model fences it anyway often enough
to matter. "```json" is tried before a plain "```", and unfenced input
comes back unchanged apart from surrounding whitespace.
"""
raw = raw.strip()
raw = raw.removeprefix("```json")
raw = raw.removeprefix("```")
raw = raw.removesuffix("```")
return raw.strip()
def ask_claude(media_type: str, data: str) -> str:
"""Send an image to Claude and return the text of its reply.
Args:
media_type: one of the image types the Anthropic API accepts.
data: the image, base64-encoded (no data: prefix).
Raises:
NotConfigured: no API key.
ReadError: the API call failed, or the reply was empty.
"""
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": data},
},
{"type": "text", "text": PROMPT},
],
}
],
)
except anthropic.APIStatusError as e:
log.warning("Claude API error %s: %s", e.status_code, e.message)
raise ReadError("failed to process image") from e
except anthropic.APIConnectionError as e:
log.warning("Claude API unreachable: %s", e)
raise ReadError("failed to process image") from e
text = next((block.text for block in message.content if block.type == "text"), None)
if text is None:
raise ReadError("empty response from image processor")
return text
def parse_reading(text: str) -> RowingReading:
"""Parse Claude's reply, raising ReadError if it is not the JSON asked for."""
try:
return RowingReading.model_validate_json(strip_markdown_fence(text))
except ValidationError as e:
log.warning("unparseable model output %r: %s", text, e)
raise ReadError("failed to parse image data") from e
def read_display(media_type: str, data: str) -> RowingReading:
"""Ask Claude for the elapsed time and distance shown in an image.
Raises:
NotConfigured: no API key.
ReadError: the API call failed, or the reply was empty or not the JSON
object that was asked for.
"""
return parse_reading(ask_claude(media_type, data))
def process_file(path: Path) -> ExtractionResult:
"""
Read one photo with Claude: the baseline's counterpart to
`rowing_stats.pipeline.process_file`.
Raises ImageLoadError if the file is not an image the API accepts, and
NotConfigured or ReadError as `read_display` does.
"""
media_type = MEDIA_TYPES.get(path.suffix.lower())
if media_type is None:
raise ImageLoadError(f"unsupported image type '{path.suffix}'")
# Decode locally first: a corrupt file should not cost an API call
img = load_image(path)
data = base64.standard_b64encode(path.read_bytes()).decode("ascii")
text = ask_claude(media_type, data)
return ExtractionResult(
file=path.name,
taken_at=get_datetime_taken(img),
raw_text=text,
stats=parse_reading(text).to_stats(),
)
-43
View File
@@ -1,43 +0,0 @@
"""Loading photos and reading their EXIF metadata."""
from datetime import datetime
from pathlib import Path
import cv2 as cv
import numpy as np
from PIL import Image, UnidentifiedImageError
from rowing_stats.errors import ImageLoadError
EXIF_DATETIME_TAG = 306
EXIF_DATETIME_FORMAT = "%Y:%m:%d %H:%M:%S"
def load_image(path: Path) -> Image.Image:
"""Open and fully decode an image, 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("file not found") from exc
except UnidentifiedImageError as exc:
raise ImageLoadError("not a recognised image format") from exc
except OSError as exc:
raise ImageLoadError(f"could not read image ({exc})") from exc
return img
def pil_to_cv(img: Image.Image) -> np.ndarray:
"""Convert a PIL image to an OpenCV BGR array."""
return cv.cvtColor(np.array(img.convert("RGB")), cv.COLOR_RGB2BGR)
def get_datetime_taken(img: Image.Image) -> datetime | None:
"""Return the EXIF timestamp of a photo, or None if absent or malformed."""
raw = img.getexif().get(EXIF_DATETIME_TAG)
if not isinstance(raw, str):
return None
try:
return datetime.strptime(raw.strip(), EXIF_DATETIME_FORMAT)
except ValueError:
return None
+43
View File
@@ -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
+335 -42
View File
@@ -1,59 +1,352 @@
"""Preparing the cropped display for Tesseract and running OCR on it."""
"""
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 as cv
import cv2
import numpy as np
import pytesseract as tess
from rowing_stats.errors import OcrError, TesseractNotInstalledError
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
UPSCALE = 3
# PSM 11: sparse text — find as much text as possible in no particular order.
# The display is a grid of unrelated numbers, not a paragraph or a single word.
# No character whitelist: with one, Tesseract drops the spaces between fields
# ("30:06 29" comes back as "30:0629") and the parser can no longer split them.
DEFAULT_PSM = 11
TESSERACT_TIMEOUT_S = 60
def preprocess_for_ocr(warped: np.ndarray) -> np.ndarray:
"""Turn the warped BGR display crop into a binarised image for Tesseract."""
gray = cv.cvtColor(warped, cv.COLOR_BGR2GRAY)
@dataclass(frozen=True)
class ScreenReading:
"""What was read off one cropped screen, with the votes behind it."""
# Scale up — Tesseract works better on larger text
gray = cv.resize(gray, (gray.shape[1] * UPSCALE, gray.shape[0] * UPSCALE),
interpolation=cv.INTER_CUBIC)
# Bilateral filter: smooths noise while preserving edges
gray = cv.bilateralFilter(gray, 9, 75, 75)
# Contrast enhancement via histogram equalization
gray = cv.equalizeHist(gray)
# Otsu threshold is clean and effective for LCD displays
_, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
return thresh
time: str | None
distance: int | None
time_votes: Counter[str]
distance_votes: Counter[str]
labeled_texts: LabeledTexts
def ocr_image(warped: np.ndarray, debug_prefix: Path | None = None,
psm: int = DEFAULT_PSM) -> str:
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.
"""
OCR the warped display crop and return Tesseract's raw text.
Raises TesseractNotInstalledError if the tesseract binary is missing, or
OcrError if it exits with an error.
"""
thresh = preprocess_for_ocr(warped)
if debug_prefix is not None:
cv.imwrite(f"{debug_prefix}_ocr_input.png", thresh)
fd, tmp_path = tempfile.mkstemp(suffix=".png")
os.close(fd)
try:
return tess.image_to_string(thresh, config=f"--psm {psm}")
except tess.TesseractNotFoundError as exc:
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 tess.TesseractError as exc:
raise OcrError(f"tesseract failed: {exc}") 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())
+93 -80
View File
@@ -1,87 +1,100 @@
"""Turning raw OCR text into structured workout stats."""
"""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 dataclasses import asdict, dataclass
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")
@dataclass(frozen=True)
class WorkoutStats:
"""Fields read off the PM5 display. Anything not recognised stays None."""
def find_times(text: str) -> list[str]:
"""Return every plausible time in one OCR text, in order of appearance.
elapsed_time: str | None = None
stroke_rate_spm: int | None = None
distance_m: int | None = None
split_500m: str | None = None
avg_split_500m: str | None = None
cal_per_hr: int | None = None
calories: int | None = None
projected_m: int | None = None
def to_dict(self) -> dict[str, str | int]:
"""Return only the fields that were found."""
return {k: v for k, v in asdict(self).items() if v is not None}
# A pace such as 2:03 or 2:00.5
_PACE = r"\d:[0-5]\d(?:\.\d)?"
# Elapsed time – H:MM:SS or MM:SS, but not a pace (decimal, or labelled /500m or ave)
_ELAPSED_RE = re.compile(
r"\b(\d{1,2}:[0-5]\d(?::[0-5]\d)?)\b(?!\.\d)(?!\s*/\s*500)(?!\s*ave)",
re.IGNORECASE,
)
# Stroke rate – 2-digit number near s/m or S/m
_STROKE_RATE_RE = re.compile(r"\b(\d{2})\s*s[/\\]m", re.IGNORECASE)
# Distance in metres – but not the "500m" of a "/500m" pace label
_DISTANCE_RE = re.compile(r"(?<!/)(?<!/\s)\b(\d{3,5})\s*m\b", re.IGNORECASE)
_SPLIT_RE = re.compile(rf"\b({_PACE})\s*/\s*500")
_AVG_SPLIT_RE = re.compile(rf"\b({_PACE})\s*ave", re.IGNORECASE)
# Cal/hr (e.g. 958 Cal/hr or 1229 Cal/hr)
_CAL_PER_HR_RE = re.compile(r"\b(\d{3,4})\s*cal\s*[/\\]\s*hr", re.IGNORECASE)
# Total calories – "Cal" not followed by "/hr"
_CALORIES_RE = re.compile(r"\b(\d{2,4})\s*cal\b(?!\s*[/\\])", re.IGNORECASE)
_PROJECTED_RE = re.compile(r"\b(\d{4,5})\s*projected", re.IGNORECASE)
_FIVE_DIGIT_RE = re.compile(r"\b(\d{5})\b")
def clean_ocr_text(text: str) -> str:
"""Collapse all runs of whitespace (including newlines) to single spaces."""
return " ".join(text.split())
def parse_stats(text: str) -> WorkoutStats:
"""Parse raw OCR output into structured stats."""
full = clean_ocr_text(text)
elapsed = _ELAPSED_RE.search(full)
stroke_rate = _STROKE_RATE_RE.search(full)
distance = _DISTANCE_RE.search(full)
split = _SPLIT_RE.search(full)
avg_split = _AVG_SPLIT_RE.search(full)
cal_per_hr = _CAL_PER_HR_RE.search(full)
calories = _CALORIES_RE.search(full)
return WorkoutStats(
elapsed_time=elapsed.group(1) if elapsed else None,
stroke_rate_spm=int(stroke_rate.group(1)) if stroke_rate else None,
distance_m=int(distance.group(1)) if distance else None,
split_500m=split.group(1) if split else None,
avg_split_500m=avg_split.group(1) if avg_split else None,
cal_per_hr=int(cal_per_hr.group(1)) if cal_per_hr else None,
calories=int(calories.group(1)) if calories else None,
projected_m=_parse_projected(full, distance),
)
def _parse_projected(full: str, distance: re.Match[str] | None) -> int | None:
Supports both H:MM:SS (hour+ workouts) and MM:SS formats.
All times are normalized to MM:SS format for downstream consistency.
"""
Projected metres: the number labelled "projected", else the last unlabelled
5-digit number that is not the one already claimed as the distance.
"""
labelled = _PROJECTED_RE.search(full)
if labelled:
return int(labelled.group(1))
times: list[str] = []
distance_span = distance.span(1) if distance else None
unlabelled = [m for m in _FIVE_DIGIT_RE.finditer(full) if m.span(1) != distance_span]
return int(unlabelled[-1].group(1)) if unlabelled else None
# 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)
-52
View File
@@ -1,52 +0,0 @@
"""End-to-end extraction for a single photo."""
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from rowing_stats.display import crop_display
from rowing_stats.image_io import get_datetime_taken, load_image, pil_to_cv
from rowing_stats.ocr import DEFAULT_PSM, ocr_image
from rowing_stats.parsing import WorkoutStats, parse_stats
@dataclass(frozen=True)
class ExtractionResult:
file: str
taken_at: datetime | None
raw_text: str
stats: WorkoutStats
def to_dict(self) -> dict[str, str | int]:
"""Flatten to a JSON-serialisable dict, omitting fields that were not found."""
out: dict[str, str | int] = {"file": self.file}
if self.taken_at is not None:
out["datetime"] = self.taken_at.isoformat()
out.update(self.stats.to_dict())
return out
def process_file(path: Path, debug_dir: Path | None = None,
psm: int = DEFAULT_PSM) -> ExtractionResult:
"""
Load a photo, locate the display, OCR it and parse the stats.
Raises a RowingStatsError subclass if the image cannot be read, no display
is found, or OCR fails. If debug_dir is given, intermediate images are
written there.
"""
debug_prefix = None
if debug_dir is not None:
debug_dir.mkdir(parents=True, exist_ok=True)
debug_prefix = debug_dir / path.stem
img = load_image(path)
warped = crop_display(pil_to_cv(img), debug_prefix)
text = ocr_image(warped, debug_prefix, psm=psm)
return ExtractionResult(
file=path.name,
taken_at=get_datetime_taken(img),
raw_text=text,
stats=parse_stats(text),
)
+101
View File
@@ -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
+167
View File
@@ -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())
+23 -11
View File
@@ -1,20 +1,32 @@
from pathlib import Path
import cv2 as cv
import cv2
import numpy as np
import pytest
@pytest.fixture
def monitor_photo() -> np.ndarray:
"""A synthetic photo: dark background with one light, square 'display'."""
arr = np.full((600, 800, 3), 30, dtype=np.uint8)
cv.rectangle(arr, (300, 200), (500, 400), (200, 200, 200), thickness=-1)
return arr
REPO = Path(__file__).parent.parent
@pytest.fixture
def monitor_photo_path(tmp_path: Path, monitor_photo: np.ndarray) -> Path:
path = tmp_path / "monitor.png"
cv.imwrite(str(path), monitor_photo)
def photo() -> np.ndarray:
"""A synthetic photo: dark wall, one bright 'screen' with digits on it."""
image = np.full((600, 800, 3), 40, dtype=np.uint8)
cv2.rectangle(image, (300, 200), (500, 380), (220, 220, 220), thickness=-1)
for row, text in enumerate(["30:06", "7283", "2:04"]):
cv2.putText(image, text, (320, 250 + row * 50), cv2.FONT_HERSHEY_SIMPLEX,
1.2, (20, 20, 20), 3)
return image
@pytest.fixture
def photo_path(tmp_path: Path, photo: np.ndarray) -> Path:
path = tmp_path / "IMG_0001.jpg"
cv2.imwrite(str(path), photo)
return path
@pytest.fixture
def corrupt_path(tmp_path: Path) -> Path:
path = tmp_path / "corrupt.jpg"
path.write_text("this is not a JPEG")
return path
+108
View File
@@ -0,0 +1,108 @@
import json
import cv2
import numpy as np
import pytest
from conftest import REPO
from rowing_stats import classifier
from rowing_stats.errors import ImageLoadError, ModelLoadError
FEATURES = {"std_dev", "entropy", "edge_density", "h_line_strength", "mean_saturation",
"dark_pixel_ratio", "bright_pixel_ratio", "local_variance"}
ROWING = REPO / "train" / "1" / "IMG_5523_screen.jpg"
@pytest.fixture
def flat_path(tmp_path):
"""A featureless grey image: nothing like a display."""
path = tmp_path / "flat.png"
cv2.imwrite(str(path), np.full((200, 200, 3), 128, dtype=np.uint8))
return path
def test_extract_features(flat_path):
feats = classifier.extract_features(flat_path)
assert set(feats) == FEATURES
assert feats["std_dev"] == 0.0
assert feats["edge_density"] < 0.05 # only the image border registers
assert feats["mean_saturation"] == 0.0
def test_extract_features_handles_black_pixels_without_warning(tmp_path):
path = tmp_path / "black.png"
cv2.imwrite(str(path), np.zeros((50, 50, 3), dtype=np.uint8))
with np.errstate(all="raise"): # saturation divides by the max channel
assert classifier.extract_features(path)["mean_saturation"] == 0.0
def test_feature_classifier_tells_a_display_from_a_flat_image(flat_path):
assert classifier.feature_based_predict(ROWING)[0] == 1
label, confidence = classifier.feature_based_predict(flat_path)
assert label == 0
assert 0.5 <= confidence <= 1.0
def test_unreadable_image(corrupt_path, tmp_path):
with pytest.raises(ImageLoadError, match="not a readable image"):
classifier.extract_features(corrupt_path)
with pytest.raises(ImageLoadError, match="file not found"):
classifier.feature_based_predict(tmp_path / "missing.jpg")
def test_cli_predict_dir_skips_unreadable_files(flat_path, corrupt_path, capsys):
code = classifier.main(["predict", "--dir", str(flat_path.parent)])
captured = capsys.readouterr()
assert code == 1
assert "flat.png → NOT ROWING MACHINE" in captured.out
assert "Summary: 1 images | 0 rowing | 1 not rowing" in captured.out
assert "corrupt.jpg: not a readable image" in captured.err
def test_cli_extract_prints_features(flat_path, capsys):
assert classifier.main(["extract", "--image", str(flat_path)]) == 0
assert set(json.loads(capsys.readouterr().out)) == FEATURES
def test_cli_predict_requires_exactly_one_target(flat_path):
with pytest.raises(SystemExit):
classifier.main(["predict"])
with pytest.raises(SystemExit):
classifier.main(["predict", "--image", str(flat_path), "--dir", "."])
# --- CNN (needs the ml extra) ------------------------------------------------
def test_cnn_predict_with_the_committed_weights():
pytest.importorskip("torchvision")
model_path = REPO / classifier.DEFAULT_MODEL_PATH
label, confidence = classifier.cnn_predict(ROWING, model_path)
assert label == 1 and confidence > 0.5
not_rowing = sorted((REPO / "train" / "0").iterdir())[0]
assert classifier.cnn_predict(not_rowing, model_path)[0] == 0
def test_cnn_missing_or_invalid_weights(tmp_path, capsys):
pytest.importorskip("torchvision")
with pytest.raises(ModelLoadError, match="not found"):
classifier.cnn_predict(ROWING, tmp_path / "nope.pth")
garbage = tmp_path / "garbage.pth"
garbage.write_bytes(b"not a checkpoint")
with pytest.raises(ModelLoadError, match="could not load"):
classifier.cnn_predict(ROWING, garbage)
# The CLI reports it once and stops, rather than once per image
code = classifier.main(["predict", "--dir", str(ROWING.parent), "--model", "cnn",
"--model-path", str(tmp_path / "nope.pth")])
assert code == 1
assert capsys.readouterr().err.count("CNN weights not found") == 1
def test_train_rejects_a_directory_without_class_folders(tmp_path, capsys):
pytest.importorskip("torchvision")
assert classifier.main(["train", "--data-dir", str(tmp_path)]) == 1
assert "must contain 0/ and 1/" in capsys.readouterr().err
+253
View File
@@ -0,0 +1,253 @@
"""Tests for the Claude reader.
No Claude call happens here: `claude._client` is replaced with a fake whose
`messages.create` returns a canned reply, so what is under test is everything
around the call - the request that is built, how the reply is parsed and
validated, and how failures are reported.
"""
import base64
from pathlib import Path
from types import SimpleNamespace
import pytest
from PIL import Image
from rowing_stats import claude
from rowing_stats.errors import ClaudeUnavailableError, ExtractionError, ImageLoadError
GOOD_REPLY = '{"timeMinutes": 30, "timeSeconds": 6, "distance": 7283}'
def text_reply(text):
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
@pytest.fixture
def fake_claude(monkeypatch):
"""Stand in for the Anthropic client; returns the list of calls it received.
Set `fake_claude.reply` to a message-like object, or to an exception
instance to have the call raise it.
"""
pytest.importorskip("anthropic")
state = SimpleNamespace(calls=[], reply=text_reply(GOOD_REPLY))
def create(**kwargs):
state.calls.append(kwargs)
if isinstance(state.reply, Exception):
raise state.reply
return state.reply
client = SimpleNamespace(messages=SimpleNamespace(create=create))
monkeypatch.setattr(claude, "_client", lambda: client)
return state
@pytest.fixture
def dated_photo(tmp_path) -> Path:
path = tmp_path / "IMG_5413.jpeg"
img = Image.new("RGB", (8, 8), "white")
exif = img.getexif()
exif[claude.ExifBase.DateTime] = "2025:11:05 12:08:00"
img.save(path, exif=exif)
return path
# --- reply parsing ----------------------------------------------------------
@pytest.mark.parametrize("raw, expected", [
('{"a": 1}', '{"a": 1}'),
(' {"a": 1}\n', '{"a": 1}'),
('```json\n{"a": 1}\n```', '{"a": 1}'),
('```\n{"a": 1}\n```', '{"a": 1}'),
('```json\n{"a": 1}', '{"a": 1}'),
])
def test_strip_markdown_fence(raw, expected):
assert claude.strip_markdown_fence(raw) == expected
def test_parse_reply():
assert claude.parse_reply(GOOD_REPLY) == (30, 6, 7283)
assert claude.parse_reply(f"```json\n{GOOD_REPLY}\n```") == (30, 6, 7283)
assert claude.parse_reply('{"timeMinutes": "30", "timeSeconds": 6.0, "distance": 7283}') \
== (30, 6, 7283)
@pytest.mark.parametrize("raw", [
"I can't read that display.",
"",
'{"timeMinutes": 30, "timeSeconds": 6}', # key missing
'{"timeMinutes": null, "timeSeconds": 6, "distance": 7283}',
'{"timeMinutes": "thirty", "timeSeconds": 6, "distance": 7283}',
"[30, 6, 7283]", # not an object
])
def test_parse_reply_rejects_anything_else(raw):
with pytest.raises(ExtractionError, match="Unparseable reply"):
claude.parse_reply(raw)
# --- sanity bounds ----------------------------------------------------------
def test_validate_reading_derives_metrics():
data = claude.validate_reading(30, 6, 7283)
assert data.total_seconds == 1806
assert data.time_per_500m == 123.99
assert data.calories == 485.53
assert data.date_taken is None
@pytest.mark.parametrize("minutes, seconds, distance, message", [
(30, 6, 0, "Invalid distance: 0"),
(0, 25, 99, "Anomalous distance: 99"),
(30, 6, 100_001, "Anomalous distance"),
(0, 29, 100, "Anomalous time: 29s"),
(120, 1, 30_000, "Anomalous time: 7201s"),
(30, 6, 12_000, "Anomalous pace"), # 1:15 /500m: faster than anyone rows
(30, 6, 5_000, "Anomalous pace"), # 3:01 /500m: a digit was dropped
(30, 6, 728, "Anomalous pace"),
])
def test_validate_reading_rejects_implausible_values(minutes, seconds, distance, message):
with pytest.raises(ExtractionError, match=message):
claude.validate_reading(minutes, seconds, distance)
@pytest.mark.parametrize("minutes, seconds, distance", [
(0, 30, 150), # shortest allowed, 1:40 pace
(120, 0, 30_000), # two hours exactly, 2:00 pace
(40, 0, 15_000), # 1:20 pace exactly
(50, 0, 10_000), # 2:30 pace exactly
])
def test_validate_reading_accepts_the_boundaries(minutes, seconds, distance):
assert claude.validate_reading(minutes, seconds, distance).distance == distance
# --- dates and file selection -----------------------------------------------
@pytest.mark.parametrize("raw, expected", [
("2025:11:05 12:08:00", "2025-11-05 12:08:00"),
(" 2025:11:05 12:08:00 ", "2025-11-05 12:08:00"),
("yesterday", None),
("", None),
(None, None),
])
def test_format_exif_date(raw, expected):
assert claude.format_exif_date(raw) == expected
def test_get_exif_date(dated_photo, tmp_path, corrupt_path):
assert claude.get_exif_date(dated_photo) == "2025:11:05 12:08:00"
undated = tmp_path / "undated.png"
Image.new("RGB", (8, 8)).save(undated)
assert claude.get_exif_date(undated) is None
with pytest.raises(ImageLoadError):
claude.get_exif_date(corrupt_path)
def test_keep_latest_versions():
names = ["IMG_1_screen.jpg", "IMG_1_screen (1).jpg", "IMG_1_screen (3).jpg",
"IMG_2_screen (10).jpg", "IMG_2_screen (9).jpg", "IMG_3_screen.jpg"]
kept = claude._keep_latest_versions([Path(n) for n in names])
assert [p.name for p in kept] == [
"IMG_1_screen (3).jpg", "IMG_2_screen (10).jpg", "IMG_3_screen.jpg"]
# --- the call ---------------------------------------------------------------
def test_extract_rowing_data_sends_image_then_prompt(fake_claude, dated_photo):
data = claude.extract_rowing_data(dated_photo)
assert (data.time_minutes, data.time_seconds, data.distance) == (30, 6, 7283)
assert data.date_taken == "2025:11:05 12:08:00"
(call,) = fake_claude.calls
assert call["model"] == claude.MODEL
image, prompt = call["messages"][0]["content"]
assert image["source"]["media_type"] == "image/jpeg"
assert base64.standard_b64decode(image["source"]["data"]) == dated_photo.read_bytes()
assert prompt == {"type": "text", "text": claude.PROMPT}
def test_bad_images_never_reach_the_api(fake_claude, tmp_path, corrupt_path):
heic = tmp_path / "photo.heic"
heic.touch()
with pytest.raises(ImageLoadError, match="unsupported image type"):
claude.extract_rowing_data(heic)
with pytest.raises(ImageLoadError, match="not a readable image"):
claude.extract_rowing_data(corrupt_path)
with pytest.raises(ImageLoadError, match="file not found"):
claude.extract_rowing_data(tmp_path / "missing.jpg")
assert fake_claude.calls == []
def test_unusable_replies(fake_claude, dated_photo):
fake_claude.reply = SimpleNamespace(content=[])
with pytest.raises(ExtractionError, match="Empty response"):
claude.extract_rowing_data(dated_photo)
fake_claude.reply = text_reply('{"timeMinutes": 30, "timeSeconds": 6, "distance": 728}')
with pytest.raises(ExtractionError, match="Anomalous pace"):
claude.extract_rowing_data(dated_photo)
def _api_error(cls, status):
import httpx2 as httpx
request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
return cls("nope", response=httpx.Response(status, request=request), body=None)
def test_api_failures_are_reported_per_image(fake_claude, dated_photo):
import anthropic
import httpx2 as httpx
fake_claude.reply = _api_error(anthropic.RateLimitError, 429)
with pytest.raises(ExtractionError, match="Claude API error 429"):
claude.extract_rowing_data(dated_photo)
fake_claude.reply = anthropic.APIConnectionError(
request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"))
with pytest.raises(ExtractionError, match="unreachable"):
claude.extract_rowing_data(dated_photo)
def test_credential_problems_stop_the_run(fake_claude, dated_photo, capsys):
import anthropic
fake_claude.reply = _api_error(anthropic.AuthenticationError, 401)
with pytest.raises(ClaudeUnavailableError, match="rejected the credentials"):
claude.extract_rowing_data(dated_photo)
fake_claude.reply = TypeError("Could not resolve authentication method.")
with pytest.raises(ClaudeUnavailableError, match="ANTHROPIC_API_KEY"):
claude.extract_rowing_data(dated_photo)
# From the CLI: reported once, not once per image
Image.new("RGB", (8, 8)).save(dated_photo.with_name("second.png"))
assert claude.main(["--dir", str(dated_photo.parent)]) == 1
assert len(fake_claude.calls) == 3
assert capsys.readouterr().err.count("ANTHROPIC_API_KEY") == 1
def test_an_unrelated_type_error_is_not_swallowed(fake_claude, dated_photo):
fake_claude.reply = TypeError("unexpected keyword argument")
with pytest.raises(TypeError):
claude.extract_rowing_data(dated_photo)
def test_cli_writes_the_results_csv(fake_claude, dated_photo, corrupt_path, capsys):
output = dated_photo.parent / "results.csv"
code = claude.main(["--dir", str(dated_photo.parent), "--output", str(output)])
out = capsys.readouterr().out
assert code == 1 # the corrupt file failed
assert "ERROR: corrupt.jpg: not a readable image" in out
assert "Time: 30:06" in out and "Pace: 2:04.0 /500m" in out
assert output.read_text().splitlines() == [
"image,time,distance_m,pace_per_500m,calories,date_taken",
"IMG_5413.jpeg,30:06,7283,2:04.0,486,2025-11-05 12:08:00",
]
+24
View File
@@ -0,0 +1,24 @@
from rowing_stats import cli
def test_no_command_prints_usage(capsys):
assert cli.main([]) == 2
out = capsys.readouterr().out
for command in cli.COMMANDS:
assert command in out
def test_help(capsys):
assert cli.main(["--help"]) == 0
assert "usage: rowing-stats" in capsys.readouterr().out
def test_unknown_command(capsys):
assert cli.main(["frobnicate"]) == 2
assert "unknown command 'frobnicate'" in capsys.readouterr().err
def test_dispatches_to_the_subcommand(tmp_path, capsys):
# An empty directory: the crop command runs and reports there is nothing to do
assert cli.main(["crop", str(tmp_path)]) == 1
assert "No images found" in capsys.readouterr().err
+84
View File
@@ -0,0 +1,84 @@
import cv2
import numpy as np
import pytest
from rowing_stats import crop
from rowing_stats.crop import CropParams, crop_screen, find_screen, order_corners
from rowing_stats.errors import ImageLoadError, ScreenNotFoundError
def test_order_corners_returns_tl_tr_br_bl():
shuffled = np.array([[90, 80], [10, 15], [12, 85], [95, 12]], dtype="float32")
assert order_corners(shuffled).tolist() == [[10, 15], [95, 12], [90, 80], [12, 85]]
def test_find_screen_locates_the_display(photo):
screen = find_screen(photo)
assert screen is not None
# The fixture draws the display at (300, 200)-(500, 380)
assert abs(screen.x - 300) <= 5 and abs(screen.y - 200) <= 5
assert abs(screen.w - 200) <= 10 and abs(screen.h - 180) <= 10
def test_find_screen_blank_image_is_none():
assert find_screen(np.full((600, 800, 3), 40, dtype=np.uint8)) is None
def test_find_screen_ignores_a_bright_region_with_no_content():
# A window or wall: right size and shape, but no text edges inside it
image = np.full((600, 800, 3), 40, dtype=np.uint8)
cv2.rectangle(image, (300, 200), (500, 380), (220, 220, 220), thickness=-1)
assert find_screen(image) is None
def test_find_screen_respects_params(photo):
assert find_screen(photo, CropParams(area_ratio_min=0.1)) is None
assert find_screen(photo, CropParams(aspect_max=1.0)) is None
assert find_screen(photo, CropParams(edge_density_min=0.9)) is None
def test_crop_screen_writes_padded_crop(photo_path, tmp_path):
out = tmp_path / "crop.jpg"
w, h = crop_screen(photo_path, out, padding=15)
saved = cv2.imread(str(out))
assert saved.shape[:2] == (h + 30, w + 30)
assert saved.mean() > 120 # the light display, not the dark wall
def test_crop_screen_unreadable_image(corrupt_path, tmp_path):
with pytest.raises(ImageLoadError, match="not a readable image"):
crop_screen(corrupt_path, tmp_path / "out.jpg")
with pytest.raises(ImageLoadError, match="file not found"):
crop_screen(tmp_path / "missing.jpg", tmp_path / "out.jpg")
assert not (tmp_path / "out.jpg").exists()
def test_crop_screen_no_screen(tmp_path):
blank = tmp_path / "blank.jpg"
cv2.imwrite(str(blank), np.full((600, 800, 3), 40, dtype=np.uint8))
with pytest.raises(ScreenNotFoundError):
crop_screen(blank, tmp_path / "out.jpg")
def test_cli_reports_each_file_and_keeps_going(photo_path, corrupt_path, tmp_path, capsys):
blank = tmp_path / "blank.jpg"
cv2.imwrite(str(blank), np.full((600, 800, 3), 40, dtype=np.uint8))
out_dir = tmp_path / "out"
code = crop.main([str(tmp_path), str(out_dir)])
out = capsys.readouterr().out
assert code == 1 # one file was unreadable
assert "OK: IMG_0001.jpg -> IMG_0001_screen.jpg" in out
assert "SKIP: No screen detected in blank.jpg" in out
assert "ERROR: corrupt.jpg: not a readable image" in out
assert "Done: 1/3 screens cropped" in out
assert [p.name for p in out_dir.iterdir()] == ["IMG_0001_screen.jpg"]
def test_cli_no_images(tmp_path, capsys):
assert crop.main([str(tmp_path)]) == 1
assert crop.main([str(tmp_path / "missing")]) == 1
err = capsys.readouterr().err
assert "No images found" in err and "is not a directory" in err
-43
View File
@@ -1,43 +0,0 @@
import numpy as np
import pytest
from rowing_stats.display import WARPED_SIZE, crop_display, order_points
from rowing_stats.errors import DisplayNotFoundError
def test_order_points_returns_tl_tr_br_bl():
shuffled = np.array([[90, 80], [10, 15], [12, 85], [95, 12]], dtype="float32")
assert order_points(shuffled).tolist() == [[10, 15], [95, 12], [90, 80], [12, 85]]
def test_crop_display_warps_square_region(monitor_photo):
warped = crop_display(monitor_photo)
assert warped.shape == (WARPED_SIZE, WARPED_SIZE, 3)
# The crop should be the light display, not the dark background
assert warped[50:350, 50:350].mean() > 150
def test_crop_display_blank_image_raises():
blank = np.zeros((600, 800, 3), dtype=np.uint8)
with pytest.raises(DisplayNotFoundError):
crop_display(blank)
def test_crop_display_ignores_non_square_region():
arr = np.full((600, 800, 3), 30, dtype=np.uint8)
arr[250:350, 100:700] = 200 # wide banner, 6:1
with pytest.raises(DisplayNotFoundError):
crop_display(arr)
def test_crop_display_ignores_tiny_square():
arr = np.full((600, 800, 3), 30, dtype=np.uint8)
arr[300:320, 400:420] = 200 # well under 1% of the frame
with pytest.raises(DisplayNotFoundError):
crop_display(arr)
def test_crop_display_writes_debug_images(monitor_photo, tmp_path):
crop_display(monitor_photo, debug_prefix=tmp_path / "shot")
assert (tmp_path / "shot_contours.png").is_file()
assert (tmp_path / "shot_warped.png").is_file()
-179
View File
@@ -1,179 +0,0 @@
"""Tests for the Claude Haiku baseline.
No Claude call happens here: `haiku_baseline._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 how failures are reported.
"""
import base64
from types import SimpleNamespace
import pytest
anthropic = pytest.importorskip("anthropic")
import httpx2 as httpx # noqa: E402
from rowing_stats import cli, haiku_baseline # noqa: E402
from rowing_stats.errors import ImageLoadError, NotConfigured, ReadError # noqa: E402
from rowing_stats.parsing import WorkoutStats # noqa: E402
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.
"""
state = SimpleNamespace(
calls=[],
reply=text_reply('{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}'),
)
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(haiku_baseline, "_client", lambda: client)
return state
@pytest.fixture
def no_api_key(monkeypatch):
for var in haiku_baseline.API_KEY_ENV_VARS:
monkeypatch.delenv(var, raising=False)
haiku_baseline._client.cache_clear()
yield
haiku_baseline._client.cache_clear()
# --- fence stripping --------------------------------------------------------
@pytest.mark.parametrize("raw, want", [
('{"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, want):
assert haiku_baseline.strip_markdown_fence(raw) == want
# --- reading -> stats -------------------------------------------------------
@pytest.mark.parametrize("minutes, seconds, want", [
(30, 6, "30:06"),
(2, 30, "2:30"),
(0, 45, "0:45"),
(60, 33, "1:00:33"), # as the monitor shows it from an hour up
(125, 0, "2:05:00"),
(0, 0, None), # the model left the time out
])
def test_format_elapsed(minutes, seconds, want):
assert haiku_baseline.format_elapsed(minutes, seconds) == want
def test_reading_to_stats_treats_zero_as_not_found():
reading = haiku_baseline.RowingReading(timeMinutes=30, timeSeconds=6)
assert reading.to_stats() == WorkoutStats(elapsed_time="30:06")
# --- read_display -----------------------------------------------------------
def test_read_display_sends_image_then_prompt(fake_claude):
reading = haiku_baseline.read_display("image/png", "QUJD")
assert (reading.timeMinutes, reading.timeSeconds, reading.distance) == (20, 5, 5000)
(call,) = fake_claude.calls
assert call["model"] == haiku_baseline.MODEL
image, prompt = call["messages"][0]["content"]
assert image == {"type": "image",
"source": {"type": "base64", "media_type": "image/png", "data": "QUJD"}}
assert prompt == {"type": "text", "text": haiku_baseline.PROMPT}
def test_read_display_accepts_fenced_json(fake_claude):
fake_claude.reply = text_reply(
'```json\n{"timeMinutes": 1, "timeSeconds": 2, "distance": 300}\n```')
assert haiku_baseline.read_display("image/jpeg", "QUJD").distance == 300
def test_read_display_missing_key_defaults_to_zero(fake_claude):
fake_claude.reply = text_reply('{"timeMinutes": 1, "timeSeconds": 2}')
assert haiku_baseline.read_display("image/jpeg", "QUJD").distance == 0
@pytest.mark.parametrize("reply, message", [
(SimpleNamespace(content=[]), "empty response from image processor"),
(text_reply("I can't read that display."), "failed to parse image data"),
(text_reply('{"timeMinutes": -1, "timeSeconds": 2, "distance": 300}'),
"failed to parse image data"),
(anthropic.APIConnectionError(
request=httpx.Request("POST", "https://api.anthropic.com/v1/messages")),
"failed to process image"),
])
def test_read_display_failures(fake_claude, reply, message):
fake_claude.reply = reply
with pytest.raises(ReadError, match=message):
haiku_baseline.read_display("image/jpeg", "QUJD")
def test_missing_api_key_is_not_configured(no_api_key):
with pytest.raises(NotConfigured):
haiku_baseline.read_display("image/jpeg", "QUJD")
@pytest.mark.parametrize("var", haiku_baseline.API_KEY_ENV_VARS)
def test_api_key_is_read_from_either_variable(no_api_key, monkeypatch, var):
monkeypatch.setenv(var, "sk-test")
assert haiku_baseline._client().api_key == "sk-test"
# --- process_file and the CLI ----------------------------------------------
def test_process_file(fake_claude, monitor_photo_path):
result = haiku_baseline.process_file(monitor_photo_path)
assert result.file == "monitor.png"
assert result.stats == WorkoutStats(elapsed_time="20:05", distance_m=5000)
assert result.raw_text == '{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}'
source = fake_claude.calls[0]["messages"][0]["content"][0]["source"]
assert source["media_type"] == "image/png"
assert base64.standard_b64decode(source["data"]) == monitor_photo_path.read_bytes()
def test_process_file_does_not_call_claude_for_a_bad_image(fake_claude, tmp_path):
corrupt = tmp_path / "corrupt.jpeg"
corrupt.write_text("not a JPEG")
heic = tmp_path / "photo.heic"
heic.touch()
with pytest.raises(ImageLoadError, match="not a recognised image"):
haiku_baseline.process_file(corrupt)
with pytest.raises(ImageLoadError, match="unsupported image type"):
haiku_baseline.process_file(heic)
assert fake_claude.calls == []
def test_cli_method_haiku(fake_claude, monitor_photo_path, capsys):
assert cli.main(["--method", "haiku", "--format", "csv", str(monitor_photo_path)]) == 0
assert capsys.readouterr().out.splitlines()[1] == "monitor.png,,20:05,,5000,,,,,"
def test_cli_method_haiku_stops_without_api_key(no_api_key, monitor_photo_path, caplog):
assert cli.main(["--method", "haiku", str(monitor_photo_path),
str(monitor_photo_path)]) == 1
assert caplog.text.count("is set") == 1
-70
View File
@@ -1,70 +0,0 @@
from datetime import datetime
import numpy as np
import pytest
from PIL import Image
from rowing_stats.errors import ImageLoadError
from rowing_stats.image_io import (
EXIF_DATETIME_TAG,
get_datetime_taken,
load_image,
pil_to_cv,
)
def test_load_image_missing_file(tmp_path):
with pytest.raises(ImageLoadError, match="not found"):
load_image(tmp_path / "nope.jpeg")
def test_load_image_not_an_image(tmp_path):
path = tmp_path / "notes.jpeg"
path.write_text("this is not a JPEG")
with pytest.raises(ImageLoadError, match="not a recognised image"):
load_image(path)
def test_load_image_truncated_file(tmp_path):
whole = tmp_path / "whole.jpeg"
Image.new("RGB", (64, 64), "white").save(whole)
truncated = tmp_path / "truncated.jpeg"
truncated.write_bytes(whole.read_bytes()[:200])
with pytest.raises(ImageLoadError, match="could not read"):
load_image(truncated)
def test_load_image_directory(tmp_path):
with pytest.raises(ImageLoadError):
load_image(tmp_path)
def test_pil_to_cv_swaps_channels_to_bgr():
arr = pil_to_cv(Image.new("RGB", (2, 3), (255, 0, 0)))
assert arr.shape == (3, 2, 3)
assert arr[0, 0].tolist() == [0, 0, 255]
def test_pil_to_cv_handles_greyscale_and_alpha():
assert pil_to_cv(Image.new("L", (2, 2))).shape == (2, 2, 3)
assert pil_to_cv(Image.new("RGBA", (2, 2))).shape == (2, 2, 3)
assert pil_to_cv(Image.new("L", (2, 2))).dtype == np.uint8
def _with_exif_datetime(value: str) -> Image.Image:
img = Image.new("RGB", (2, 2))
img.getexif()[EXIF_DATETIME_TAG] = value
return img
def test_get_datetime_taken():
img = _with_exif_datetime("2025:11:15 22:16:05")
assert get_datetime_taken(img) == datetime(2025, 11, 15, 22, 16, 5)
def test_get_datetime_taken_missing():
assert get_datetime_taken(Image.new("RGB", (2, 2))) is None
def test_get_datetime_taken_malformed():
assert get_datetime_taken(_with_exif_datetime("yesterday")) is None
+171
View File
@@ -0,0 +1,171 @@
import shutil
import subprocess
from pathlib import Path
import cv2
import numpy as np
import pytest
from conftest import REPO
from rowing_stats import ocr
from rowing_stats.errors import ImageLoadError, OcrError, TesseractNotInstalledError
VARIANT_LABELS = ["s2_clahe_t120", "s2_clahe_t130", "s2_otsu", "s2_otsu_inv",
"s3_otsu", "s3_otsu_inv"]
@pytest.fixture
def screen_path(tmp_path: Path, photo: np.ndarray) -> Path:
path = tmp_path / "IMG_0001_screen.jpg"
cv2.imwrite(str(path), photo[200:380, 300:500])
return path
@pytest.fixture
def fake_tesseract(monkeypatch):
"""Replace the tesseract call with canned texts, one per variant in order."""
texts = ["30:06\n7283", "30:06\n7288", "30:06\n7283", "", "38:06\n7283", "30:06"]
calls = iter(texts * 10)
monkeypatch.setattr(ocr, "ocr_image", lambda img: next(calls))
def test_preprocess_variants(photo):
variants = ocr.preprocess_variants(photo)
assert [label for label, _ in variants] == VARIANT_LABELS
for label, img in variants:
scale = int(label[1])
assert img.shape == (600 * scale, 800 * scale)
assert set(np.unique(img).tolist()) <= {0, 255} # binarised
by_label = dict(variants)
assert np.array_equal(by_label["s3_otsu_inv"], 255 - by_label["s3_otsu"])
def test_extract_screen_data_takes_the_majority(screen_path, fake_tesseract):
reading = ocr.extract_screen_data(screen_path)
assert reading.time == "30:06"
assert reading.distance == 7283
assert reading.time_votes == {"30:06": 4, "38:06": 1}
assert reading.distance_votes == {"7283": 3, "7288": 1}
assert [label for label, _ in reading.labeled_texts] == VARIANT_LABELS
def test_extract_screen_data_nothing_legible(screen_path, monkeypatch):
monkeypatch.setattr(ocr, "ocr_image", lambda img: "")
reading = ocr.extract_screen_data(screen_path)
assert reading.time is None and reading.distance is None
def test_extract_screen_data_unreadable_image(corrupt_path, tmp_path, fake_tesseract):
with pytest.raises(ImageLoadError, match="not a readable image"):
ocr.extract_screen_data(corrupt_path)
with pytest.raises(ImageLoadError, match="file not found"):
ocr.extract_screen_data(tmp_path / "missing.jpg")
def _run_raising(exc):
def run(*args, **kwargs):
raise exc
return run
def test_ocr_image_reports_missing_tesseract(photo, monkeypatch):
monkeypatch.setattr(subprocess, "run", _run_raising(FileNotFoundError("tesseract")))
with pytest.raises(TesseractNotInstalledError, match="not installed"):
ocr.ocr_image(photo)
def test_ocr_image_reports_timeout(photo, monkeypatch):
monkeypatch.setattr(subprocess, "run",
_run_raising(subprocess.TimeoutExpired("tesseract", 60)))
with pytest.raises(OcrError, match="timed out"):
ocr.ocr_image(photo)
def test_ocr_image_reports_failure_and_cleans_up(photo, monkeypatch):
seen = []
def run(cmd, **kwargs):
seen.append(Path(cmd[1]))
assert seen[0].is_file() # the image was written for tesseract
return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="bad image\n")
monkeypatch.setattr(subprocess, "run", run)
with pytest.raises(OcrError, match="tesseract failed: bad image"):
ocr.ocr_image(photo)
assert not seen[0].exists() # and removed afterwards
def test_ocr_image_passes_psm_and_whitelist(photo, monkeypatch):
def run(cmd, **kwargs):
assert cmd[0] == "tesseract" and cmd[2:] == [
"stdout", "--psm", "6", "-c", "tessedit_char_whitelist=0123456789:."]
return subprocess.CompletedProcess(cmd, 0, stdout=" 30:06\n", stderr="")
monkeypatch.setattr(subprocess, "run", run)
assert ocr.ocr_image(photo) == "30:06"
def test_read_photo_pools_crops_and_skips_unreadable_ones(
screen_path, corrupt_path, fake_tesseract, capsys):
second = screen_path.with_name("IMG_0001_screen (1).jpg")
shutil.copy(screen_path, second)
reading = ocr.read_photo([screen_path, corrupt_path, second])
assert reading.time_votes == {"30:06": 8, "38:06": 2}
assert reading.time == "30:06" and reading.distance == "7283"
assert len(reading.labeled_texts) == 12
assert "corrupt.jpg: not a readable image" in capsys.readouterr().err
def test_read_photo_stops_when_tesseract_is_missing(screen_path, monkeypatch):
monkeypatch.setattr(subprocess, "run", _run_raising(FileNotFoundError("tesseract")))
with pytest.raises(TesseractNotInstalledError):
ocr.read_photo([screen_path, screen_path])
def test_cli_validation_scores_only_images_with_a_reference(
screen_path, fake_tesseract, tmp_path, capsys):
shutil.copy(screen_path, tmp_path / "IMG_0002_screen.jpg")
shutil.copy(screen_path, tmp_path / "IMG_0003_screen.jpg")
reference = tmp_path / "reference.csv"
reference.write_text("image,time,distance_m\n"
"IMG_0001.JPEG,30:06,7283\n"
"IMG_0002.JPEG,30:06,9999\n")
output = tmp_path / "ocr.csv"
code = ocr.main(["--dir", str(tmp_path), "--validate", str(reference),
"--output", str(output)])
out = capsys.readouterr().out
assert code == 0
assert "Processing 3 unique images from 3 crops" in out
assert "Time: 30:06 OK" in out
assert "Distance: 7283 EXPECTED 9999" in out
assert "Time: 2/2 (100%)" in out
assert "Distance: 1/2 (50%)" in out
assert "(1 images have no reference reading and are not scored)" in out
assert output.read_text().splitlines()[1] == "IMG_0001,30:06,7283,2:04.0,486,"
def test_cli_stops_cleanly_when_tesseract_is_missing(screen_path, monkeypatch, capsys):
monkeypatch.setattr(subprocess, "run", _run_raising(FileNotFoundError("tesseract")))
assert ocr.main(["--image", str(screen_path)]) == 1
assert "tesseract is not installed" in capsys.readouterr().err
def test_cli_bad_inputs(tmp_path, screen_path, capsys):
assert ocr.main(["--dir", str(tmp_path / "missing")]) == 1
assert ocr.main(["--image", str(screen_path), "--validate", str(tmp_path / "no.csv")]) == 1
err = capsys.readouterr().err
assert "is not a directory" in err and "could not read" in err
@pytest.mark.skipif(shutil.which("tesseract") is None, reason="tesseract not installed")
def test_real_tesseract_reads_a_sample_screen():
"""End-to-end on a committed crop whose reference reading is 30:06 / 7559 m."""
reading = ocr.extract_screen_data(REPO / "train" / "1" / "IMG_5523_screen.jpg")
assert reading.time == "30:06"
assert reading.distance == 7559
+94 -113
View File
@@ -1,136 +1,117 @@
from collections import Counter
import pytest
from rowing_stats.parsing import WorkoutStats, clean_ocr_text, parse_stats
# What a clean read of the calories screen looks like
CALORIES_SCREEN = """
1:00:33 28 s/m
770 Cal/hr
844 Cal
13879 m
6 split Cal
26911 projected m 2:00:00
"""
# What a clean read of the pace screen looks like
PACE_SCREEN = """
30:06 29 s/m
2:03.5 /500m
7283 m
2:04.1 ave /500m
"""
@pytest.mark.parametrize("raw, expected", [
("", ""),
(" \n\t ", ""),
("30:06", "30:06"),
(" 30:06 \n\n 29 s/m\n", "30:06 29 s/m"),
("a\tb\r\nc", "a b c"),
])
def test_clean_ocr_text_collapses_whitespace(raw, expected):
assert clean_ocr_text(raw) == expected
def test_parses_calories_screen():
assert parse_stats(CALORIES_SCREEN) == WorkoutStats(
elapsed_time="1:00:33",
stroke_rate_spm=28,
distance_m=13879,
cal_per_hr=770,
calories=844,
projected_m=26911,
)
def test_parses_pace_screen():
assert parse_stats(PACE_SCREEN) == WorkoutStats(
elapsed_time="30:06",
stroke_rate_spm=29,
distance_m=7283,
split_500m="2:03.5",
avg_split_500m="2:04.1",
)
@pytest.mark.parametrize("text", ["", " \n ", "glgg", ".vMes:AJ", "Egggi::igg"])
def test_garbage_yields_no_stats(text):
assert parse_stats(text) == WorkoutStats()
assert parse_stats(text).to_dict() == {}
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"),
("1:00:33", "1:00:33"),
("5:07 29", "5:07"),
("30:06 then 45:10", "30:06"), # first one wins
("30:99", None), # seconds out of range
("2:03 /500m", None), # a pace, not elapsed time
("2:03.5", None),
("2:04 ave", None),
("2:03 /500m 30:06", "30:06"),
("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_elapsed_time(text, expected):
assert parse_stats(text).elapsed_time == expected
def test_find_times_mm_ss(text, expected):
assert find_times(text) == expected
@pytest.mark.parametrize("text, expected", [
("29 s/m", 29),
("29S/m", 29),
("29 s\\m", 29),
("9 s/m", None),
("29", None),
("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_stroke_rate(text, expected):
assert parse_stats(text).stroke_rate_spm == expected
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 m", 7283),
("13879m", 13879),
("7283 M", 7283),
("2:03 /500m", None), # the 500m of a pace label
("2:03 / 500m", None),
("2:03 /500m 7283 m", 7283),
("42 m", None),
("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_distance(text, expected):
assert parse_stats(text).distance_m == expected
def test_find_distances(text, expected):
assert find_distances(text) == expected
def test_split_and_average_split_are_distinguished():
stats = parse_stats("2:03 /500m 2:05.2 ave /500m")
assert stats.split_500m == "2:03"
assert stats.avg_split_500m == "2:05.2"
LABELED = [
("s2_otsu", "30:06 29\n7283"),
("s2_otsu_inv", "30:06\n7288"),
("s3_otsu", "38:06\n7283"),
("s3_otsu_inv", ""),
]
@pytest.mark.parametrize("text, cal_per_hr, calories", [
("958 Cal/hr", 958, None), # must not be read as total calories
("1229 cal/hr 467 Cal", 1229, 467),
("467 Cal", None, 467),
("467 Cal 1229 Cal/hr", 1229, 467),
("958 Cal\\hr", 958, None),
])
def test_calories_and_cal_per_hr(text, cal_per_hr, calories):
stats = parse_stats(text)
assert stats.cal_per_hr == cal_per_hr
assert stats.calories == calories
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})
@pytest.mark.parametrize("text, expected", [
("26911 projected m", 26911),
("9800 projected", 9800),
("13879 26911", 26911), # unlabelled: last 5-digit number
("13879 m", None), # already claimed as the distance
("13879 m 26911", 26911),
("1234", None),
])
def test_projected(text, expected):
assert parse_stats(text).projected_m == expected
def test_majority_wins():
assert pick_best(extract_times(LABELED)) == "30:06"
assert pick_best(extract_distances(LABELED)) == "7283"
def test_to_dict_omits_missing_fields():
assert parse_stats("30:06 29 s/m").to_dict() == {
"elapsed_time": "30:06",
"stroke_rate_spm": 29,
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
-126
View File
@@ -1,126 +0,0 @@
import json
import shutil
from pathlib import Path
import pytesseract
import pytest
from PIL import Image
from rowing_stats import cli, ocr, pipeline
from rowing_stats.errors import (
DisplayNotFoundError,
ImageLoadError,
OcrError,
TesseractNotInstalledError,
)
from rowing_stats.parsing import WorkoutStats
PHOTOS = Path(__file__).parent.parent / "photos"
@pytest.fixture
def fake_ocr(monkeypatch):
"""Replace Tesseract with a canned read so tests don't need the binary."""
monkeypatch.setattr(pipeline, "ocr_image",
lambda warped, debug_prefix=None, psm=0: "30:06 29 s/m\n7283 m\n")
def test_process_file(monitor_photo_path, fake_ocr):
result = pipeline.process_file(monitor_photo_path)
assert result.file == "monitor.png"
assert result.taken_at is None
assert result.stats == WorkoutStats(elapsed_time="30:06", stroke_rate_spm=29,
distance_m=7283)
assert result.to_dict() == {"file": "monitor.png", "elapsed_time": "30:06",
"stroke_rate_spm": 29, "distance_m": 7283}
def test_process_file_unreadable_image(tmp_path, fake_ocr):
path = tmp_path / "broken.jpeg"
path.write_bytes(b"\x00\x01\x02")
with pytest.raises(ImageLoadError):
pipeline.process_file(path)
def test_process_file_no_display(tmp_path, fake_ocr):
path = tmp_path / "blank.png"
Image.new("RGB", (800, 600), "black").save(path)
with pytest.raises(DisplayNotFoundError):
pipeline.process_file(path)
def test_ocr_image_reports_missing_tesseract(monitor_photo, monkeypatch):
def missing(*args, **kwargs):
raise pytesseract.TesseractNotFoundError()
monkeypatch.setattr(ocr.tess, "image_to_string", missing)
with pytest.raises(TesseractNotInstalledError, match="not installed"):
ocr.ocr_image(monitor_photo)
def test_ocr_image_wraps_tesseract_failure(monitor_photo, monkeypatch):
def fail(*args, **kwargs):
raise pytesseract.TesseractError(1, "boom")
monkeypatch.setattr(ocr.tess, "image_to_string", fail)
with pytest.raises(OcrError, match="boom"):
ocr.ocr_image(monitor_photo)
def test_preprocess_for_ocr_is_binary_and_upscaled(monitor_photo):
out = ocr.preprocess_for_ocr(monitor_photo)
assert out.shape == (600 * ocr.UPSCALE, 800 * ocr.UPSCALE)
assert set(out.ravel().tolist()) <= {0, 255}
def test_collect_paths_expands_directories(tmp_path):
for name in ("b.JPEG", "a.jpg", "c.png", "notes.txt"):
(tmp_path / name).touch()
single = tmp_path / "elsewhere.jpeg"
assert cli.collect_paths([tmp_path / "missing.jpeg", single]) == [
tmp_path / "missing.jpeg", single]
assert [p.name for p in cli.collect_paths([tmp_path])] == ["a.jpg", "b.JPEG", "c.png"]
def test_cli_json_output_and_exit_code(monitor_photo_path, tmp_path, fake_ocr,
capsys, caplog):
broken = tmp_path / "broken.jpeg"
broken.write_text("nope")
code = cli.main(["--format", "json", str(monitor_photo_path), str(broken)])
assert code == 1 # one file failed...
assert "broken.jpeg: not a recognised image format" in caplog.text
assert json.loads(capsys.readouterr().out) == [{ # ...but the other is reported
"file": "monitor.png", "elapsed_time": "30:06",
"stroke_rate_spm": 29, "distance_m": 7283,
}]
def test_cli_csv_output_to_file(monitor_photo_path, tmp_path, fake_ocr):
out = tmp_path / "stats.csv"
assert cli.main(["--format", "csv", "-o", str(out), str(monitor_photo_path)]) == 0
header, row = out.read_text().splitlines()
assert header.split(",") == cli.CSV_COLUMNS
assert row == "monitor.png,,30:06,29,7283,,,,,"
def test_cli_no_images(tmp_path, caplog):
assert cli.main([str(tmp_path)]) == 1
assert "no images found" in caplog.text
def test_cli_stops_when_tesseract_missing(monitor_photo_path, monkeypatch, caplog):
def missing(*args, **kwargs):
raise TesseractNotInstalledError("tesseract is not installed or not on PATH")
monkeypatch.setattr(pipeline, "ocr_image", missing)
assert cli.main([str(monitor_photo_path), str(monitor_photo_path)]) == 1
assert caplog.text.count("not installed") == 1
@pytest.mark.skipif(shutil.which("tesseract") is None, reason="tesseract not installed")
def test_real_photo_end_to_end(tmp_path):
"""Smoke test against a real photo with one field Tesseract reads reliably."""
result = pipeline.process_file(PHOTOS / "IMG_5413.JPEG", debug_dir=tmp_path)
assert result.file == "IMG_5413.JPEG"
assert result.taken_at is not None
assert result.stats.elapsed_time == "30:06"
assert (tmp_path / "IMG_5413_ocr_input.png").is_file()
+90
View File
@@ -0,0 +1,90 @@
import pytest
from conftest import REPO
from rowing_stats.errors import RowingStatsError
from rowing_stats.results import (
CSV_COLUMNS,
WorkoutRow,
calories,
format_pace,
format_time,
load_ground_truth,
make_row,
pace_per_500m,
parse_time,
write_csv,
)
@pytest.mark.parametrize("seconds, expected", [
(124.0, "2:04.0"),
(123.14, "2:03.1"),
(119.5, "1:59.5"),
(119.97, "2:00.0"), # rounds up into the next minute, not "1:60.0"
(60.0, "1:00.0"),
])
def test_format_pace(seconds, expected):
assert format_pace(seconds) == expected
def test_time_round_trip():
assert format_time(30, 6) == "30:06"
assert format_time(60, 33) == "60:33" # minutes run past the hour
assert parse_time("30:06") == 1806
assert parse_time("60:33") == 3633
def test_derived_metrics_match_the_committed_results():
# First row of rowing_results.csv: 30:06, 7283 m -> 2:04.0, 486 kcal
assert format_pace(pace_per_500m(1806, 7283)) == "2:04.0"
assert round(calories(7283)) == 486
def test_make_row_derives_pace_and_calories():
assert make_row("IMG_5413.JPEG", "30:06", 7283, "2025-11-05 12:08:00") == WorkoutRow(
image="IMG_5413.JPEG", time="30:06", distance_m=7283,
pace_per_500m="2:04.0", calories=486, date_taken="2025-11-05 12:08:00",
)
def test_make_row_leaves_gaps_for_missing_fields():
assert make_row("a", "30:06", None) == WorkoutRow(image="a", time="30:06")
assert make_row("a", None, 7283) == WorkoutRow(image="a", distance_m=7283, calories=486)
assert make_row("a", None, None) == WorkoutRow(image="a")
def test_csv_round_trip(tmp_path):
path = tmp_path / "out.csv"
write_csv([make_row("IMG_1.JPEG", "30:06", 7283), make_row("IMG_2.JPEG", "40:05", 9671)],
path)
header, first, _ = path.read_text().splitlines()
assert header.split(",") == CSV_COLUMNS
assert first == "IMG_1.JPEG,30:06,7283,2:04.0,486,"
assert load_ground_truth(path) == {
"IMG_1": {"time": "30:06", "distance_m": 7283},
"IMG_2": {"time": "40:05", "distance_m": 9671},
}
def test_load_ground_truth_reads_the_committed_reference():
truth = load_ground_truth(REPO / "rowing_results.csv")
assert len(truth) == 34
assert truth["IMG_5413"] == {"time": "30:06", "distance_m": 7283}
def test_load_ground_truth_missing_file(tmp_path):
with pytest.raises(RowingStatsError, match="could not read"):
load_ground_truth(tmp_path / "nope.csv")
@pytest.mark.parametrize("content", [
"name,value\nx,1\n", # wrong columns
"image,time,distance_m\nIMG_1.JPEG,30:06,far\n", # distance not a number
"image,time,distance_m\nIMG_1.JPEG,30:06\n", # short row
])
def test_load_ground_truth_rejects_other_csvs(tmp_path, content):
path = tmp_path / "bad.csv"
path.write_text(content)
with pytest.raises(RowingStatsError, match="not a results CSV"):
load_ground_truth(path)
+48
View File
@@ -0,0 +1,48 @@
import pytest
from rowing_stats import tune
from rowing_stats.crop import CropParams
def test_load_images_skips_unreadable_files(photo_path, corrupt_path, capsys):
images = tune.load_images(photo_path.parent)
assert [path.name for path, _ in images] == ["IMG_0001.jpg"]
assert "corrupt.jpg" in capsys.readouterr().err
def test_count_rowing_crops(photo_path, photo, tmp_path, monkeypatch):
seen = []
def fake_predict(path, model_path):
seen.append(path)
assert path.is_file() # the crop exists while it is classified
return 1, 0.9
monkeypatch.setattr(tune, "cnn_predict", fake_predict)
images = [(photo_path, photo), (photo_path, photo)]
assert tune.count_rowing_crops(images, CropParams(), tmp_path, tmp_path / "m.pth") == 2
assert not any(path.exists() for path in seen) # and is removed afterwards
# Parameters that find no screen classify nothing
assert tune.count_rowing_crops(images, CropParams(area_ratio_min=0.1), tmp_path,
tmp_path / "m.pth") == 0
assert len(seen) == 2
def test_objective_rejects_inverted_ranges(photo_path, photo, tmp_path, monkeypatch):
optuna = pytest.importorskip("optuna")
monkeypatch.setattr(tune, "cnn_predict", lambda path, model_path: (1, 0.9))
objective = tune.make_objective([(photo_path, photo)], tmp_path, tmp_path / "m.pth")
defaults = dict(vars(CropParams()))
assert objective(optuna.trial.FixedTrial(defaults)) == 1
assert objective(optuna.trial.FixedTrial({**defaults, "thresh_min": 160,
"thresh_max": 160})) == 0
assert objective(optuna.trial.FixedTrial({**defaults, "canny_low": 100,
"canny_high": 100})) == 0
def test_cli_missing_weights(tmp_path, capsys):
pytest.importorskip("torchvision")
assert tune.main(["--model-path", str(tmp_path / "nope.pth"), "--n-trials", "1"]) == 1
assert "CNN weights not found" in capsys.readouterr().err
Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Some files were not shown because too many files have changed in this diff Show More