Files
stpweb/python/app/rowing.py
adamfandClaude Opus 5.5 307268fbea Put every Claude call behind one helper in the Python service
rowing.py and jobs.py repeated the same call, error mapping, fence
stripping and validation; that now lives in claude.ask_json, and the
internal routes share one wrapper and one exception handler in main.py.

Add /internal/email/classify, which takes over the email pipeline's
Claude call from the Go backend (prompt ported verbatim, plus a sentence
fencing the email off as data).

The internal-only guard is now a dependency, so a request that came
through nginx gets 404 even when its body is invalid, where it used to
get 422.

requirements-dev.txt adds pytest and httpx on top of requirements.txt so
the tests run on a host; the image still installs only requirements.txt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 14:39:18 +01:00

85 lines
3.2 KiB
Python

"""Read a rowing machine display from a photo with Claude.
This is the image half of the Go backend's admin-only POST /rowing. The Go
handler keeps everything that needs the database or the session cookie - the
admin gate, the EXIF date, the duplicate check, the sanity bounds, the insert -
and hands the image here only once it has decided the Claude call is worth
paying for. This module just turns pixels into three numbers.
Like `travelodge`, it never imports FastAPI; `main` is the HTTP skin.
"""
from pydantic import BaseModel, Field
# Re-exported under the names this module has always had: the tests reach the
# exceptions and the fence stripping through `rowing`. `_client` is the seam
# they replace to fake the API, which is why it is handed to ask_json below
# rather than left to its default.
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
# The keys named here are the JSON contract: RowingReading's field names below
# and ExtractedRowingData in backend/handlers/handle_rowing.go 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 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,
)