Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
77 lines
2.6 KiB
Python
77 lines
2.6 KiB
Python
"""Read a rowing machine display from a photo with Claude.
|
|
|
|
The Go handler does auth, EXIF, dedup and bounds; this only turns pixels into
|
|
three numbers.
|
|
"""
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
# `_client` is the seam the tests replace.
|
|
from .claude import MODEL, NotConfigured, ReadError, ask_json, strip_markdown_fence
|
|
from .claude import client as _client
|
|
|
|
__all__ = ["MODEL", "NotConfigured", "ReadError", "RowingReading", "read_display", "strip_markdown_fence"]
|
|
|
|
# The answer is a three-key JSON object, so this is a ceiling, not a target.
|
|
MAX_TOKENS = 256
|
|
|
|
# Keys must match RowingReading below and ExtractedRowingData in
|
|
# backend/handlers/handle_rowing.go.
|
|
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 and the Go
|
|
handler unmarshals. A key the model left out defaults to 0, which the Go
|
|
side's sanity bounds then reject - the same outcome as when Go parsed the
|
|
model's output itself.
|
|
"""
|
|
|
|
timeMinutes: int = Field(0, ge=0)
|
|
timeSeconds: int = Field(0, ge=0)
|
|
distance: int = Field(0, ge=0)
|
|
|
|
|
|
def read_display(media_type: str, data: str) -> RowingReading:
|
|
"""Ask Claude for the elapsed time and distance shown in an image.
|
|
|
|
Args:
|
|
media_type: one of the image types the Anthropic API accepts; the
|
|
caller is responsible for the allow-list.
|
|
data: the image, base64-encoded (no data: prefix).
|
|
|
|
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 ask_json(
|
|
RowingReading,
|
|
max_tokens=MAX_TOKENS,
|
|
messages=[
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{
|
|
"type": "image",
|
|
"source": {"type": "base64", "media_type": media_type, "data": data},
|
|
},
|
|
{"type": "text", "text": PROMPT},
|
|
],
|
|
}
|
|
],
|
|
failed="failed to process image",
|
|
empty="empty response from image processor",
|
|
unparseable="failed to parse image data",
|
|
get_client=_client,
|
|
)
|