Move the rowing photo Claude call to the Python service

POST /rowing in the Go backend no longer calls the Anthropic SDK. It keeps
the admin gate, EXIF date, duplicate check, sanity bounds and insert, and
sends the image to a new internal Python route, POST /internal/rowing/read,
which makes the Claude call and returns the three numbers it read.

The route spends a paid call and has no auth of its own, so nginx 404s
/py/internal/ and the route refuses anything carrying the proxy headers
nginx adds. The python container now receives CLAUDE_API_KEY.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-09 11:46:17 +01:00
co-authored by Claude Opus 5.5
parent 8d7606bbe8
commit f8d48ba9af
19 changed files with 661 additions and 92 deletions
+30 -5
View File
@@ -1,7 +1,8 @@
# Python API service
A small FastAPI app (`app/main.py`) served by uvicorn on port 8000 inside the
`python` container. Most of it is one feature: **cheap Travelodge finder** —
`python` container. It also hosts one internal route, the **rowing display
reader** (see below). Most of it is one feature: **cheap Travelodge finder** —
given a London location and dates it pulls live room prices from Travelodge and
adds the cost of getting there from a chosen station on TfL, so you can rank
hotels by what the night *actually* costs, not just the room.
@@ -12,9 +13,11 @@ hotels by what the night *actually* costs, not just the room.
| --- | --- |
| `app/main.py` | HTTP skin: request models/validation, response cache, one-at-a-time guard, NDJSON framing, route handlers |
| `app/travelodge.py` | All the real work: upstream calls, caching, rate limiting, fare maths, the two search generators |
| `app/rowing.py` | The Claude call that reads time and distance off a photo of a rowing machine display |
| `app/__init__.py` | Empty; makes `app` a package so `app.main:app` resolves |
`travelodge.py` never imports FastAPI and can be driven from a plain script.
`travelodge.py` and `rowing.py` never import FastAPI and can be driven from a
plain script.
## Endpoints
@@ -30,6 +33,7 @@ Paths below are as the service sees them; from a browser prefix everything with
| POST | `/hotels/search` | Blocking search; returns once every shortlisted hotel is priced |
| POST | `/hotels/search/stream` | Same search as NDJSON progress lines |
| POST | `/hotels/scan/stream` | Cheapest night across a date range, NDJSON |
| POST | `/internal/rowing/read` | **Internal.** Read a rowing display photo with Claude |
Interactive schema: `/py/docs` (Swagger UI), `/py/openapi.json`.
@@ -59,6 +63,26 @@ already running and 502 on upstream failure.
Only **one** live search or scan runs process-wide at a time (the TfL budget
can't be shared), and identical requests are cached for 10 minutes.
### Rowing display reader (internal)
`POST /internal/rowing/read` takes `{"media_type": "image/jpeg", "data":
"<base64>"}` and returns `{"timeMinutes", "timeSeconds", "distance"}` as read
by Claude (`claude-haiku-4-5`). It is the image half of the Go backend's
admin-only `POST /api/rowing`: the Go handler does the admin check, the EXIF
date, the duplicate check, the sanity bounds and the insert, and calls this
only once it has decided the paid call is worth making. Nothing here judges
whether the numbers are plausible.
It is the only route in this service that is **not public**, and it has no
auth of its own, so two things keep it internal: nginx answers `/py/internal/`
with a 404, and the route 404s any request carrying the `X-Real-IP` /
`X-Forwarded-For` headers nginx adds to everything it proxies. The Go backend
calls the container directly (`http://python:8000/...`) and sends neither.
Errors: 502 with a fixed `detail` (`failed to process image`, `empty response
from image processor`, `failed to parse image data`) that the Go handler
relays to the admin; 503 if `CLAUDE_API_KEY` is unset.
## Behind nginx
`nginx/nginx.conf.template` proxies `/py/` to this container and **strips the
@@ -73,8 +97,8 @@ braces version of the same thing. The internal deadlines in `travelodge.py`
(200s for a search, 240s for a scan) exist to finish *before* that 300s cut, and
return partial results with `summary.truncated = true` instead of dying.
Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, and the
optional `TFL_APP_KEY` (see below). Dev mode mounts `python/app` and runs
Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, the optional
`TFL_APP_KEY` (see below), and `CLAUDE_API_KEY` for the rowing reader. Dev mode mounts `python/app` and runs
uvicorn with `--reload`.
## Running locally
@@ -96,7 +120,8 @@ uvicorn app.main:app --reload --port 8000
# http://localhost:8000/docs (no /py prefix when run directly)
```
Dependencies are `fastapi`, `uvicorn[standard]` and `requests` — nothing else.
Dependencies are `fastapi`, `uvicorn[standard]`, `requests` and `anthropic` —
nothing else.
## How the pricing works
+80 -5
View File
@@ -13,10 +13,13 @@ Endpoints
POST /hotels/search blocking cheapest-Travelodge search
POST /hotels/search/stream same search, streamed as NDJSON
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
POST /internal/rowing/read read a rowing display photo with Claude
(Go backend only - not reachable through nginx)
All the hotel work lives in `travelodge`; this module is the HTTP skin around
it - request validation, a response cache, the one-search-at-a-time guard, and
the NDJSON framing. Consumed by vue/src/views/hotels/ (SingleStayPanel.vue,
the NDJSON framing. The rowing reader lives in `rowing` and is the one route
here that is not public: see the "Internal" section at the bottom. Consumed by vue/src/views/hotels/ (SingleStayPanel.vue,
CheapestNightPanel.vue, useHotelForm.js), which fetch these paths with the /py
prefix. Field names in the models below are part of that contract.
"""
@@ -25,18 +28,18 @@ import json
import re
import threading
from datetime import date, datetime, timedelta, timezone
from typing import Optional
from typing import Literal, Optional
from zoneinfo import ZoneInfo
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, field_validator, model_validator
from . import travelodge
from . import rowing, travelodge
app = FastAPI(
title="Python API",
version="0.3.0",
version="0.4.0",
docs_url="/docs",
openapi_url="/openapi.json",
)
@@ -640,3 +643,75 @@ def hotel_scan_stream(req: HotelScanRequest) -> StreamingResponse:
as a final "error" line.
"""
return _ndjson(_scan_events(req))
# --------------------------------------------------------------------------- #
# Internal: rowing display reader
# --------------------------------------------------------------------------- #
# 10MB of image (the Go handler's upload cap) once base64-encoded, rounded up.
MAX_IMAGE_B64_CHARS = 14_000_000
class RowingReadRequest(BaseModel):
"""An image for Claude to read, as the Go backend sends it."""
# The types the Anthropic API accepts for an image block. The Go handler
# checks the same list first so the admin gets its friendlier 400.
media_type: Literal["image/jpeg", "image/png", "image/gif", "image/webp"]
data: str = Field(..., min_length=1, max_length=MAX_IMAGE_B64_CHARS, description="Base64 image bytes")
def _internal_only(request: Request) -> None:
"""Refuse a request that arrived through nginx.
Every other route in this service is public, but this one spends a paid
Claude call per request and has no auth of its own - the admin check
happens in the Go backend, which calls this container directly over
app-network. Two layers keep the outside world off it, because either alone
is one config edit away from being lost:
1. nginx answers /py/internal/ with a 404 (both templates).
2. nginx stamps X-Real-IP and X-Forwarded-For on everything it proxies
here, and a client cannot make it omit them; the Go backend sends
neither. So their presence means the request came from outside.
404 rather than 403, so the route is indistinguishable from one that does
not exist.
"""
if "x-real-ip" in request.headers or "x-forwarded-for" in request.headers:
raise HTTPException(status_code=404, detail="Not Found")
@app.post(
"/internal/rowing/read",
response_model=rowing.RowingReading,
summary="Read time and distance off a rowing machine display",
description=(
"Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through nginx. "
"Sends the image to Claude and returns the three numbers it read. No plausibility checking "
"happens here - the caller owns the sanity bounds."
),
responses={
502: {"description": "Claude failed, or its reply was not the expected JSON"},
503: {"description": "CLAUDE_API_KEY is not set"},
},
)
def rowing_read(req: RowingReadRequest, request: Request) -> rowing.RowingReading:
"""Read a rowing display photo.
A plain `def`, so FastAPI runs it in the threadpool and the blocking Claude
call does not stall the event loop the hotel streams are served from.
Raises:
HTTPException: 404 (came through nginx), 503 (no API key) or 502
(Claude failed or returned something unparseable). The 502 detail
is one of rowing.ReadError's fixed messages, which the Go handler
passes on to the admin verbatim.
"""
_internal_only(request)
try:
return rowing.read_display(req.media_type, req.data)
except rowing.NotConfigured as e:
raise HTTPException(status_code=503, detail=str(e)) from None
except rowing.ReadError as e:
raise HTTPException(status_code=502, detail=str(e)) from None
+137
View File
@@ -0,0 +1,137 @@
"""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.
"""
import functools
import logging
import os
import anthropic
from pydantic import BaseModel, Field, ValidationError
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; the Go caller's own
# timeout is set above that so it sees this module's error, not its own.
TIMEOUT_S = 30.0
# 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)
class ReadError(Exception):
"""The display could not be read; the message is safe to show the admin."""
class NotConfigured(ReadError):
"""CLAUDE_API_KEY is not set in this container."""
@functools.lru_cache(maxsize=1)
def _client() -> anthropic.Anthropic:
"""Build the Anthropic client on first use.
Lazy so that a missing key only breaks this feature: the hotel finder must
still boot without it. The key is passed explicitly because the stack's
variable is CLAUDE_API_KEY, not the ANTHROPIC_API_KEY the SDK looks for.
"""
key = os.environ.get("CLAUDE_API_KEY", "")
if not key:
raise NotConfigured("CLAUDE_API_KEY is not 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. Mirrors services.StripMarkdownFence in the Go backend (still
used by the email pipeline): "```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 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.
"""
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")
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
+1
View File
@@ -1,6 +1,7 @@
fastapi==0.115.6
uvicorn[standard]==0.34.0
requests==2.32.3
anthropic==1.12.1
# Dev only, deliberately commented out so the image stays slim: the test suite
# (python/tests) needs pytest. Install it with `pip install pytest` locally and
+152
View File
@@ -0,0 +1,152 @@
"""Tests for the rowing display reader and its internal-only route.
No Claude call happens here: `rowing._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, how
failures map to status codes, and the guard that keeps the route off the public
internet.
"""
from types import SimpleNamespace
import anthropic
import httpx2 as httpx
import pytest
from fastapi.testclient import TestClient
from app import main, rowing
BODY = {"media_type": "image/jpeg", "data": "aGVsbG8="}
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(rowing, "_client", lambda: client)
return state
@pytest.fixture
def http():
return TestClient(main.app)
# --- fence stripping (must agree with services.StripMarkdownFence in Go) ---
@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 rowing.strip_markdown_fence(raw) == want
# --- read_display ---------------------------------------------------------
def test_read_display_sends_image_then_prompt(fake_claude):
reading = rowing.read_display("image/png", "QUJD")
assert (reading.timeMinutes, reading.timeSeconds, reading.distance) == (20, 5, 5000)
(call,) = fake_claude.calls
assert call["model"] == rowing.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": rowing.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 rowing.read_display("image/jpeg", "QUJD").distance == 300
def test_read_display_missing_key_defaults_to_zero(fake_claude):
"""The Go side turns a zero distance into its own 400; it must not fail here."""
fake_claude.reply = text_reply('{"timeMinutes": 1, "timeSeconds": 2}')
assert rowing.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(rowing.ReadError, match=message):
rowing.read_display("image/jpeg", "QUJD")
def test_missing_api_key_is_not_configured(monkeypatch):
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
rowing._client.cache_clear()
with pytest.raises(rowing.NotConfigured):
rowing.read_display("image/jpeg", "QUJD")
# --- the route ------------------------------------------------------------
def test_route_returns_reading(fake_claude, http):
res = http.post("/internal/rowing/read", json=BODY)
assert res.status_code == 200
assert res.json() == {"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}
@pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"])
def test_route_refuses_requests_proxied_by_nginx(fake_claude, http, header):
"""nginx sets these on everything it forwards; the Go backend sets neither."""
res = http.post("/internal/rowing/read", json=BODY, headers={header: "203.0.113.9"})
assert res.status_code == 404
assert fake_claude.calls == []
def test_route_rejects_unsupported_media_type(fake_claude, http):
res = http.post("/internal/rowing/read", json={**BODY, "media_type": "image/heic"})
assert res.status_code == 422
assert fake_claude.calls == []
def test_route_maps_read_error_to_502(fake_claude, http):
fake_claude.reply = text_reply("no numbers here")
res = http.post("/internal/rowing/read", json=BODY)
assert res.status_code == 502
assert res.json() == {"detail": "failed to parse image data"}
def test_route_maps_missing_key_to_503(monkeypatch, http):
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
rowing._client.cache_clear()
res = http.post("/internal/rowing/read", json=BODY)
assert res.status_code == 503