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:
@@ -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
|
||||
Reference in New Issue
Block a user