Add Claude Haiku baseline

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-09 11:49:13 +01:00
co-authored by Claude Opus 5.5
parent 685ee9bf3d
commit e2330c6f77
9 changed files with 443 additions and 10 deletions
+15 -2
View File
@@ -21,6 +21,10 @@ Each photo goes through four stages, one module each under `src/rowing_stats/`:
`pipeline.py` chains the stages for one file, and `cli.py` runs it over many files and writes text, JSON or CSV. `pipeline.py` chains the stages for one file, and `cli.py` runs it over many files and writes text, JSON or CSV.
### Haiku baseline
`haiku_baseline.py` is the alternative the pipeline is measured against: send the whole photo to Claude Haiku 4.5 with a short prompt asking for the elapsed time and distance as JSON. There is no display detection or preprocessing. It reads only those two fields, makes one paid API call per photo, and needs a network connection and an API key, which is the trade-off the local pipeline exists to avoid. Both methods produce the same output rows, so their CSVs can be compared directly.
## Running it ## 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 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`).
@@ -38,6 +42,13 @@ 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 rowing-stats --debug-dir debug photos/ # also save each stage's image
``` ```
To run the Haiku baseline instead, install its extra dependency and set `ANTHROPIC_API_KEY` (or `CLAUDE_API_KEY`):
```sh
pip install -r requirements-baseline.txt
rowing-stats --method haiku --format csv -o baseline.csv photos/
```
Example: Example:
```console ```console
@@ -52,7 +63,7 @@ $ rowing-stats --format json photos/IMG_5414.JPEG
] ]
``` ```
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 the run stops immediately. Fields that could not be read are left out (empty in CSV). A file that cannot be processed is reported on stderr and skipped, and the exit code is 1 if any file failed. If Tesseract itself is missing, or the baseline has no API key, the run stops immediately.
The same pipeline is available from Python: The same pipeline is available from Python:
@@ -76,7 +87,7 @@ pip install -r requirements-dev.txt
pytest 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 tests cover the parsing and cleaning logic, image loading failures (missing, corrupt and truncated files), display detection on synthetic images, and the CLI's output and exit codes. Tesseract is stubbed out in all but one test, which runs the real pipeline on a sample photo and is skipped if Tesseract is not installed. The baseline's tests use a fake Anthropic client, so no test makes an API call or needs a key.
## Limitations ## Limitations
@@ -97,6 +108,8 @@ The causes, roughly in order of impact:
- **Global thresholding.** A single Otsu threshold turns glare and shadow gradients into solid black patches that hide digits. - **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. - **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: 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. - 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.
+2 -1
View File
@@ -16,7 +16,8 @@ dependencies = [
] ]
[project.optional-dependencies] [project.optional-dependencies]
dev = ["pytest>=8.0"] baseline = ["anthropic>=1.0"]
dev = ["pytest>=8.0", "anthropic>=1.0"]
notebook = ["ipykernel", "matplotlib"] notebook = ["ipykernel", "matplotlib"]
[project.scripts] [project.scripts]
+3
View File
@@ -0,0 +1,3 @@
# Only needed for the Claude Haiku baseline (rowing-stats --method haiku).
-r requirements.txt
anthropic==1.12.1
+1 -1
View File
@@ -1,2 +1,2 @@
-r requirements.txt -r requirements-baseline.txt
pytest==9.1.0 pytest==9.1.0
+4
View File
@@ -3,7 +3,9 @@
from rowing_stats.errors import ( from rowing_stats.errors import (
DisplayNotFoundError, DisplayNotFoundError,
ImageLoadError, ImageLoadError,
NotConfigured,
OcrError, OcrError,
ReadError,
RowingStatsError, RowingStatsError,
TesseractNotInstalledError, TesseractNotInstalledError,
) )
@@ -16,7 +18,9 @@ __all__ = [
"DisplayNotFoundError", "DisplayNotFoundError",
"ExtractionResult", "ExtractionResult",
"ImageLoadError", "ImageLoadError",
"NotConfigured",
"OcrError", "OcrError",
"ReadError",
"RowingStatsError", "RowingStatsError",
"TesseractNotInstalledError", "TesseractNotInstalledError",
"WorkoutStats", "WorkoutStats",
+31 -6
View File
@@ -6,6 +6,7 @@ Usage:
rowing-stats photos/IMG_5485.JPEG photos/IMG_5550.JPEG rowing-stats photos/IMG_5485.JPEG photos/IMG_5550.JPEG
rowing-stats --format csv -o stats.csv photos/ rowing-stats --format csv -o stats.csv photos/
rowing-stats --debug-dir debug ... # save intermediate images rowing-stats --debug-dir debug ... # save intermediate images
rowing-stats --method haiku photos/ # read with Claude instead of OCR
""" """
import argparse import argparse
@@ -18,7 +19,11 @@ from dataclasses import fields
from pathlib import Path from pathlib import Path
from typing import TextIO from typing import TextIO
from rowing_stats.errors import RowingStatsError, TesseractNotInstalledError from rowing_stats.errors import (
NotConfigured,
RowingStatsError,
TesseractNotInstalledError,
)
from rowing_stats.ocr import DEFAULT_PSM from rowing_stats.ocr import DEFAULT_PSM
from rowing_stats.parsing import WorkoutStats from rowing_stats.parsing import WorkoutStats
from rowing_stats.pipeline import ExtractionResult, process_file from rowing_stats.pipeline import ExtractionResult, process_file
@@ -46,7 +51,7 @@ def write_text(results: Sequence[ExtractionResult], out: TextIO) -> None:
for result in results: for result in results:
out.write(f"\n{'=' * 60}\n") out.write(f"\n{'=' * 60}\n")
out.write(f"File: {result.file}\n") out.write(f"File: {result.file}\n")
out.write("Raw OCR output:\n") out.write("Raw output:\n")
out.write(f"{result.raw_text}\n") out.write(f"{result.raw_text}\n")
out.write("Parsed stats:\n") out.write("Parsed stats:\n")
for k, v in result.to_dict().items(): for k, v in result.to_dict().items():
@@ -65,6 +70,20 @@ def write_csv(results: Sequence[ExtractionResult], out: TextIO) -> None:
WRITERS = {"text": write_text, "json": write_json, "csv": write_csv} 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: def build_parser() -> argparse.ArgumentParser:
@@ -74,14 +93,20 @@ def build_parser() -> argparse.ArgumentParser:
) )
parser.add_argument("paths", nargs="*", type=Path, parser.add_argument("paths", nargs="*", type=Path,
help=f"image files or directories (default: {DEFAULT_PHOTOS_DIR}/)") 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", parser.add_argument("--format", choices=sorted(WRITERS), default="text",
help="output format (default: text)") help="output format (default: text)")
parser.add_argument("-o", "--output", type=Path, parser.add_argument("-o", "--output", type=Path,
help="write results to this file instead of stdout") help="write results to this file instead of stdout")
parser.add_argument("--debug-dir", type=Path, parser.add_argument("--debug-dir", type=Path,
help="save intermediate images (contours, crop, OCR input) here") help="save intermediate images (contours, crop, OCR input) here "
"(ocr only)")
parser.add_argument("--psm", type=int, default=DEFAULT_PSM, parser.add_argument("--psm", type=int, default=DEFAULT_PSM,
help=f"Tesseract page segmentation mode (default: {DEFAULT_PSM})") help=f"Tesseract page segmentation mode (default: {DEFAULT_PSM}; "
"ocr only)")
parser.add_argument("-v", "--verbose", action="store_true", parser.add_argument("-v", "--verbose", action="store_true",
help="log each file as it is processed") help="log each file as it is processed")
return parser return parser
@@ -103,8 +128,8 @@ def main(argv: Sequence[str] | None = None) -> int:
for path in paths: for path in paths:
logger.info("processing %s", path) logger.info("processing %s", path)
try: try:
results.append(process_file(path, debug_dir=args.debug_dir, psm=args.psm)) results.append(extract(path, args))
except TesseractNotInstalledError as exc: except (TesseractNotInstalledError, NotConfigured) as exc:
# Environment problem, not a bad photo — every other file would fail too # Environment problem, not a bad photo — every other file would fail too
logger.error("%s", exc) logger.error("%s", exc)
return 1 return 1
+8
View File
@@ -19,3 +19,11 @@ class OcrError(RowingStatsError):
class TesseractNotInstalledError(OcrError): class TesseractNotInstalledError(OcrError):
"""The tesseract binary is not installed or not on PATH.""" """The tesseract binary is not installed or not on PATH."""
class ReadError(RowingStatsError):
"""The Claude baseline could not read the display."""
class NotConfigured(ReadError):
"""The Claude baseline has no API key, or its SDK is not installed."""
+200
View File
@@ -0,0 +1,200 @@
"""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(),
)
+179
View File
@@ -0,0 +1,179 @@
"""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