From f8d48ba9af7b3d05734c39249e6d59e6973675c8 Mon Sep 17 00:00:00 2001 From: Adam French Date: Fri, 9 Oct 2026 11:46:17 +0100 Subject: [PATCH] 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 --- .env.example | 6 +- CLAUDE.md | 4 +- DEPLOYMENT.md | 3 +- backend/README.md | 12 +- backend/handlers/handle_rowing.go | 156 +++++++++++++++---------- backend/handlers/handle_rowing_test.go | 94 +++++++++++++++ backend/handlers/store.go | 7 +- backend/main.go | 18 ++- backend/services/claude.go | 9 +- backend/services/email_sync.go | 4 +- docker-compose.yml | 8 +- nginx/nginx.conf.template | 9 ++ nginx/nginx_dev_common.conf.template | 9 ++ python/README.md | 35 +++++- python/app/main.py | 85 +++++++++++++- python/app/rowing.py | 137 ++++++++++++++++++++++ python/requirements.txt | 1 + python/tests/test_rowing.py | 152 ++++++++++++++++++++++++ vue/src/views/admin/CreateRowing.vue | 4 +- 19 files changed, 661 insertions(+), 92 deletions(-) create mode 100644 backend/handlers/handle_rowing_test.go create mode 100644 python/app/rowing.py create mode 100644 python/tests/test_rowing.py diff --git a/.env.example b/.env.example index 356d6ad..1434e41 100644 --- a/.env.example +++ b/.env.example @@ -10,8 +10,8 @@ # variables inside that container. nginx, backend, db, icecast2, # certbot and gitea all do this. # The `python` service deliberately does neither wholesale — it uses an -# explicit `environment:` allow-list of three variables, so it never sees the -# database password or any API key. +# explicit `environment:` allow-list, so it never sees the database password +# or any API key other than the two it uses (TFL_APP_KEY, CLAUDE_API_KEY). # # HOW TO USE # cp .env.example .env then fill in every value. @@ -154,6 +154,8 @@ DOMAIN= EMAIL= # --- Third-party API keys (backend) ------------------------------------------ +# CLAUDE_API_KEY is also passed to the python service, which makes the Claude +# call for the rowing photo reader; the backend uses it for the email pipeline. CLAUDE_API_KEY= STEAM_API_KEY= STEAM_ID= diff --git a/CLAUDE.md b/CLAUDE.md index 99fd992..ab42667 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -48,14 +48,14 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi. **Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode). -**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. +**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. One route, `/internal/rowing/read` (the Claude call behind `POST /api/rowing`), is internal: the Go backend calls it directly over the Docker network and nginx 404s `/py/internal/`. **Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). ## Backend Structure - `main.go` — entry point: wires up DB, services, router -- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, ClaudeClient, Auth, etc. Passed to all handlers +- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, EmailSync, etc. Passed to all handlers - `handlers/handle_*.go` — REST handlers grouped by domain - `graph/schema/*.graphql` — GraphQL schema files (source of truth) - `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout) diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index d98559b..6352dfd 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -237,7 +237,8 @@ Two distinct mechanisms read it, and services use both: `gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own convention for overriding `app.ini` keys), and `python` receives an explicit -three-variable allow-list, so it never sees the database password or any API key. +allow-list, so it never sees the database password or any API key other than +the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY` for the rowing photo reader). **`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two things between this checkout and `adamf@stppi.local:~/deploy/web_server`: diff --git a/backend/README.md b/backend/README.md index 7ef4f2a..9655734 100644 --- a/backend/README.md +++ b/backend/README.md @@ -107,8 +107,9 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends. recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter it, ask Claude to extract structured data, create or advance a `JobApplication`. Runs on a timer and can be triggered by an admin. -- **claude.go** — the shared Anthropic client, used by the email pipeline and - by the rowing photo reader. +- **claude.go** — the Anthropic client, used by the email pipeline. (The + rowing photo reader's Claude call lives in the Python service; `POST /rowing` + reaches it directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/rowing/read`.) - **notes.go** — path-traversal-safe file lookup for the notes directory. - **seed.go** — dev-only test data. Creates an admin with the password `password`, so it must never run in production (`SEED_DB=true` is set only @@ -150,8 +151,8 @@ generated struct rather than the model you expected. are benign (at worst a duplicate upstream fetch), but do not add a field there that would be unsafe to tear. - **Claude output is parsed as JSON** after stripping a possible markdown code - fence — via the shared `services.StripMarkdownFence`, used by both - `handle_rowing.go` and `email_sync.go`. + fence — `services.StripMarkdownFence` in `email_sync.go`, with a port of it + in `python/app/rowing.py` for the rowing photo reader. - **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.** A failed email is recorded with action `"error"` and an attempt counter; while it has attempts left the next sync reprocesses it and updates the same @@ -180,7 +181,8 @@ generated struct rather than the model you expected. | `SEED_DB` | seed dev test data (never in production) | | `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras | | `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth | -| `CLAUDE_API_KEY` | Anthropic API | +| `CLAUDE_API_KEY` | Anthropic API (email pipeline; the python service reads it too) | +| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) | | `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed | | `STEAM_API_KEY` / `STEAM_ID` | Steam presence | | `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) | diff --git a/backend/handlers/handle_rowing.go b/backend/handlers/handle_rowing.go index e15bc89..db53ba4 100644 --- a/backend/handlers/handle_rowing.go +++ b/backend/handlers/handle_rowing.go @@ -1,19 +1,19 @@ package handlers import ( + "bytes" "context" - "encoding/base64" "encoding/json" "errors" + "fmt" "io" "log" "net/http" + "time" "github.com/rwcarlsen/goexif/exif" "adam-french.co.uk/backend/models" - "adam-french.co.uk/backend/services" - "github.com/anthropics/anthropic-sdk-go" "github.com/gin-gonic/gin" "gorm.io/gorm" ) @@ -22,15 +22,87 @@ import ( // the admin uploads a photo of the rowing machine display and Claude reads the // numbers off it. The session date comes from the photo's EXIF metadata, which // also doubles as the deduplication key. +// +// The Claude call itself lives in the Python service (python/app/rowing.py), +// reached directly over the Docker network. Everything that needs the session +// or the database — the admin gate, EXIF, the duplicate check, the sanity +// bounds, the insert — stays here. // ExtractedRowingData is the JSON contract for what Claude reads off the -// display; the keys must match the prompt in CreateRowing. +// display: the body of the Python service's reply, whose keys are the ones +// its prompt asks the model for (RowingReading in python/app/rowing.py). type ExtractedRowingData struct { TimeMinutes uint64 `json:"timeMinutes"` TimeSeconds uint64 `json:"timeSeconds"` Distance uint64 `json:"distance"` } +// rowingReadPath is the Python route. It is internal: nginx refuses +// /py/internal/ and the route itself refuses anything nginx forwarded, so the +// only way in is this direct container-to-container call. +const rowingReadPath = "/internal/rowing/read" + +// rowingReadClient bounds the wait on the Python service. Two minutes sits +// above that side's own worst case (a 30s Claude timeout, retried twice with +// backoff), so a slow Claude surfaces as Python's error rather than as a +// timeout here. +var rowingReadClient = &http.Client{Timeout: 2 * time.Minute} + +// displayReadError is a failure the Python service reported in words that are +// safe and useful to show the admin (its 502 detail), as opposed to a +// transport or decoding failure, which is only logged. +type displayReadError struct{ detail string } + +func (e *displayReadError) Error() string { return e.detail } + +// readRowingDisplay sends the image to the Python service and returns what +// Claude read off it. No plausibility checking happens on either side of this +// call; that is CreateRowing's job. +func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) { + var extracted ExtractedRowingData + + // encoding/json writes a []byte as standard base64, which is the form the + // Anthropic API wants and so what the Python side passes straight through. + body, err := json.Marshal(struct { + MediaType string `json:"media_type"` + Data []byte `json:"data"` + }{mediaType, image}) + if err != nil { + return extracted, err + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+rowingReadPath, bytes.NewReader(body)) + if err != nil { + return extracted, err + } + req.Header.Set("Content-Type", "application/json") + + resp, err := rowingReadClient.Do(req) + if err != nil { + return extracted, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + // FastAPI errors are {"detail": ...}. Only a 502 carries one of the + // reader's own fixed messages; a 422's detail is a list, which fails + // to decode into the string and falls through to the generic error. + var failure struct { + Detail string `json:"detail"` + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10)) + if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" { + return extracted, &displayReadError{detail: failure.Detail} + } + return extracted, fmt.Errorf("rowing reader returned %d: %s", resp.StatusCode, raw) + } + + if err := json.NewDecoder(resp.Body).Decode(&extracted); err != nil { + return extracted, fmt.Errorf("decoding rowing reader response: %w", err) + } + return extracted, nil +} + // GetRowing backs the public GET /rowing with every logged session, newest // first. func (store *Store) GetRowing(ctx *gin.Context) { @@ -47,9 +119,10 @@ func (store *Store) GetRowing(ctx *gin.Context) { // CreateRowing backs the admin-only POST /rowing: it takes a photo of the // rowing machine display, dates it from EXIF, has Claude read the time and -// distance, sanity-checks the result and stores a session. +// distance (via the Python service), sanity-checks the result and stores a +// session. // -// Note it is admin-gated and calls a paid API once per request, so the +// Note it is admin-gated and costs a paid API call once per request, so the // validation below exists to catch misreadings rather than hostile input. func (store *Store) CreateRowing(ctx *gin.Context) { file, err := ctx.FormFile("image") @@ -81,16 +154,17 @@ func (store *Store) CreateRowing(ctx *gin.Context) { } // exif.Decode consumed part of the stream, so rewind before reading the - // bytes to send to Claude. + // bytes to send on for reading. if _, err := f.Seek(0, io.SeekStart); err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"}) return } // Cap the upload before buffering it (and then base64-encoding it, 1.33x - // bigger): the route is admin-only but an unbounded read would still let - // a giant file exhaust the Pi's memory and produce a huge paid API call. - // 10MB is well above any photo this endpoint is meant to take. + // bigger, on its way to the Python service): the route is admin-only but + // an unbounded read would still let a giant file exhaust the Pi's memory + // and produce a huge paid API call. 10MB is well above any photo this + // endpoint is meant to take; the Python side's own limit is sized from it. if file.Size > 10<<20 { ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"}) return @@ -110,13 +184,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) { } // This is the browser's claimed type, not a sniffed one; it is passed // straight through to the Anthropic API, so the allow-list is there to - // keep the API call well-formed rather than to police the file. + // keep the API call well-formed rather than to police the file. The + // Python service enforces the same list; checking here first gives the + // admin a clear 400 instead of that side's validation error. mediaType := file.Header.Get("Content-Type") if !allowedMediaTypes[mediaType] { ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"}) return } - encoded := base64.StdEncoding.EncodeToString(data) // Duplicate guard: two photos of the same session share an EXIF capture // time to the second. Checked before the Claude call so a re-upload costs @@ -137,55 +212,18 @@ func (store *Store) CreateRowing(ctx *gin.Context) { return } - // Build the message with an image + text prompt - message, err := store.ClaudeClient.Messages.New(context.Background(), anthropic.MessageNewParams{ - Model: anthropic.ModelClaudeHaiku4_5, - MaxTokens: 256, - Messages: []anthropic.MessageParam{ - { - Role: "user", - Content: []anthropic.ContentBlockParamUnion{ - // Image block - anthropic.NewImageBlock(anthropic.Base64ImageSourceParam{ - Type: "base64", - MediaType: anthropic.Base64ImageSourceMediaType(mediaType), - Data: encoded, - }), - // Text prompt requesting exactly 2 variables - anthropic.NewTextBlock( - `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.`), - }, - }, - }, - }) + extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data) if err != nil { log.Println(err) - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to process image"}) - return - } - - if len(message.Content) == 0 { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "empty response from image processor"}) - return - } - - // Strip a markdown code fence if the model wrapped its JSON in one - // despite the prompt; shared with the email pipeline, which asks for bare - // JSON in the same way and gets fenced output just as often. - extractedData := ExtractedRowingData{} - raw := services.StripMarkdownFence(message.Content[0].Text) - - err = json.Unmarshal([]byte(raw), &extractedData) - if err != nil { - log.Println(err) - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse image data"}) + // The reader's own messages ("failed to parse image data", ...) are + // passed on; anything else is a plumbing failure the admin can do + // nothing with. + msg := "failed to process image" + var readErr *displayReadError + if errors.As(err, &readErr) { + msg = readErr.detail + } + ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg}) return } diff --git a/backend/handlers/handle_rowing_test.go b/backend/handlers/handle_rowing_test.go new file mode 100644 index 0000000..33ae8d0 --- /dev/null +++ b/backend/handlers/handle_rowing_test.go @@ -0,0 +1,94 @@ +package handlers + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" +) + +// readRowingDisplay is the Go half of the contract with the Python service's +// /internal/rowing/read. CreateRowing itself needs a database and a real +// multipart photo with EXIF, so what is covered is the call: the request the +// Python side receives, and how each kind of reply comes back. + +func rowingReader(t *testing.T, handler http.HandlerFunc) *Store { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + return &Store{PythonURL: srv.URL} +} + +func TestReadRowingDisplayRequestAndReply(t *testing.T) { + var got struct { + MediaType string `json:"media_type"` + Data string `json:"data"` + } + var path string + var forwarded bool + store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) { + path = r.URL.Path + // The Python route treats either header as "came through nginx" and + // answers 404, so this call must never carry them. + forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != "" + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Errorf("decoding request: %v", err) + } + w.Write([]byte(`{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}`)) + }) + + data, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("hello")) + if err != nil { + t.Fatalf("readRowingDisplay: %v", err) + } + if data != (ExtractedRowingData{TimeMinutes: 20, TimeSeconds: 5, Distance: 5000}) { + t.Fatalf("got %+v", data) + } + if path != rowingReadPath { + t.Fatalf("path = %q, want %q", path, rowingReadPath) + } + if forwarded { + t.Fatal("request carried a proxy header the Python route rejects") + } + // "hello" in standard base64, the encoding the Anthropic API expects. + if got.MediaType != "image/jpeg" || got.Data != "aGVsbG8=" { + t.Fatalf("request body = %+v", got) + } +} + +func TestReadRowingDisplayErrors(t *testing.T) { + cases := []struct { + name string + status int + body string + wantDetail string // non-empty: a displayReadError with this message + }{ + {"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"}, + {"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""}, + {"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""}, + {"non-JSON 502 is not relayed", http.StatusBadGateway, `bad gateway`, ""}, + {"malformed success body", http.StatusOK, `not json`, ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(c.status) + w.Write([]byte(c.body)) + }) + + _, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("x")) + if err == nil { + t.Fatal("expected an error") + } + var readErr *displayReadError + if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") { + t.Fatalf("relayed = %v, err = %v", relayed, err) + } + if readErr != nil && readErr.detail != c.wantDetail { + t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail) + } + }) + } +} diff --git a/backend/handlers/store.go b/backend/handlers/store.go index 13480a5..8509258 100644 --- a/backend/handlers/store.go +++ b/backend/handlers/store.go @@ -8,7 +8,6 @@ import ( "time" "adam-french.co.uk/backend/services" - "github.com/anthropics/anthropic-sdk-go" "github.com/zmb3/spotify/v2" spotifyauth "github.com/zmb3/spotify/v2/auth" "gorm.io/gorm" @@ -30,12 +29,16 @@ type Store struct { DB *gorm.DB SpotifyAuth *spotifyauth.Authenticator SpotifyClient *spotify.Client - ClaudeClient *anthropic.Client Auth *services.Auth Notes *services.Notes LoginLimiter *services.RateLimiter EmailSync *services.EmailSyncService + // Base URL of the Python service on the Docker network, no trailing + // slash. Used for the one call that bypasses nginx: reading a rowing + // display photo (see handle_rowing.go). + PythonURL string + // Cached "recently played" tracks, refreshed at most once a minute by the // GraphQL spotifyRecent resolver. A pointer to a slice so that nil can // mean "never fetched" distinctly from "fetched, empty". diff --git a/backend/main.go b/backend/main.go index 3a7327c..5ce5f57 100644 --- a/backend/main.go +++ b/backend/main.go @@ -90,6 +90,8 @@ func main() { spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig) // CLAUDE + // Only the email pipeline uses this client now; the rowing photo reader's + // Claude call moved to the Python service, which reads the same key. claudeAPIKey := os.Getenv("CLAUDE_API_KEY") claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey} claudeClient := services.InitClaude(&claudeConfig) @@ -114,6 +116,20 @@ func main() { steamAPIKey := os.Getenv("STEAM_API_KEY") steamID := os.Getenv("STEAM_ID") + // PYTHON SERVICE + // Called directly over the Docker network, not through nginx, for the + // rowing photo reader. The defaults mirror docker-compose.yml, where both + // variables are optional. + pythonHost := os.Getenv("PYTHON_HOST") + if pythonHost == "" { + pythonHost = "python" + } + pythonPort := os.Getenv("PYTHON_PORT") + if pythonPort == "" { + pythonPort = "8000" + } + pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort) + // EMAIL SYNC // An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30 // minute default stands — a typo here fails quietly. @@ -144,7 +160,7 @@ func main() { // and the GraphQL login mutation. Nginx rate-limits the login route too. loginLimiter := services.NewRateLimiter(5, time.Minute) - store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID} + store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL} // Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in // the Gin context, so the order in the admin group matters. diff --git a/backend/services/claude.go b/backend/services/claude.go index 5be1695..ab13a5e 100644 --- a/backend/services/claude.go +++ b/backend/services/claude.go @@ -10,15 +10,16 @@ type ClaudeConfig struct { APIKey string } -// InitClaude builds the shared Anthropic client. It is used in two places: -// reading a rowing machine display from a photo (handlers.CreateRowing) and -// classifying job-application emails (EmailSyncService.processEmail). +// InitClaude builds the Anthropic client used to classify job-application +// emails (EmailSyncService.processEmail). The other Claude caller, the rowing +// photo reader, lives in the Python service and builds its own client from +// the same CLAUDE_API_KEY. // // No validation happens here: with an empty or wrong API key construction // still succeeds and the failure only surfaces on the first request. func InitClaude(config *ClaudeConfig) *anthropic.Client { // anthropic.NewClient returns a value, not a pointer, so take its address - // to share one client across every caller. + // so it can be handed around without copying. client := anthropic.NewClient(option.WithAPIKey(config.APIKey)) return &client } diff --git a/backend/services/email_sync.go b/backend/services/email_sync.go index fd2c2b8..56c110c 100644 --- a/backend/services/email_sync.go +++ b/backend/services/email_sync.go @@ -888,8 +888,8 @@ If isJobEmail is false, only include that field. No text, no markdown, no explan // a plain "```" otherwise. It is deliberately forgiving: unfenced input is // returned unchanged apart from surrounding whitespace. // -// Shared with handlers.CreateRowing, which prompts for bare JSON in the same -// way and gets the same fenced output. +// python/app/rowing.py carries a port of this for the rowing photo reader, +// which prompts for bare JSON in the same way and gets the same fenced output. func StripMarkdownFence(raw string) string { raw = strings.TrimSpace(raw) raw = strings.TrimPrefix(raw, "```json") diff --git a/docker-compose.yml b/docker-compose.yml index 967a450..5f3eb8a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -394,8 +394,11 @@ services: # OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own # routes are written relative to /. # Note this service uses `environment:` with an explicit allow-list rather - # than `env_file: ./.env` — it only gets the three variables it needs and - # never sees the database password, Spotify secrets, or API keys. + # than `env_file: ./.env` — it only gets the variables it needs and never + # sees the database password, Spotify secrets, or the other API keys. + # CLAUDE_API_KEY is the one secret on the list: the rowing photo reader + # (POST /internal/rowing/read, called by the backend, blocked at nginx) makes + # the Claude call that used to live in the Go backend. python: build: context: ./python @@ -408,6 +411,7 @@ services: - PYTHON_PORT=${PYTHON_PORT:-8000} - ROOT_PATH=/py - TFL_APP_KEY=${TFL_APP_KEY:-} + - CLAUDE_API_KEY=${CLAUDE_API_KEY:-} healthcheck: test: ["CMD", "python", "-c", "import urllib.request,os; urllib.request.urlopen(f\"http://localhost:{os.environ.get('PYTHON_PORT','8000')}/health\")"] interval: 30s diff --git a/nginx/nginx.conf.template b/nginx/nginx.conf.template index 58c80c0..2a69a6e 100644 --- a/nginx/nginx.conf.template +++ b/nginx/nginx.conf.template @@ -519,6 +519,15 @@ http { proxy_set_header X-Forwarded-Proto $scheme; } + # /py/internal/: routes the Go backend calls directly over app-network + # (the rowing photo reader, which spends a paid Claude call and has no + # auth of its own). Never proxied. ^~ so no regex location can claim + # the path first. The Python side also refuses anything carrying the + # X-Real-IP / X-Forwarded-For headers set below, as a second layer. + location ^~ /py/internal/ { + return 404; + } + location /py/ { limit_req zone=api burst=20 nodelay; # Hotel search blocks for up to a few minutes while it calls Travelodge and TfL diff --git a/nginx/nginx_dev_common.conf.template b/nginx/nginx_dev_common.conf.template index 48d6ab1..f2b7111 100644 --- a/nginx/nginx_dev_common.conf.template +++ b/nginx/nginx_dev_common.conf.template @@ -231,6 +231,15 @@ proxy_set_header X-Forwarded-Proto $scheme; } + # /py/internal/: routes the Go backend calls directly over app-network + # (the rowing photo reader, which spends a paid Claude call and has no + # auth of its own). Never proxied. ^~ so no regex location can claim + # the path first. The Python side also refuses anything carrying the + # X-Real-IP / X-Forwarded-For headers set below, as a second layer. + location ^~ /py/internal/ { + return 404; + } + location /py/ { limit_req zone=api burst=20 nodelay; # Hotel search blocks for up to a few minutes while it calls Travelodge and TfL diff --git a/python/README.md b/python/README.md index 0c2f11e..e407928 100644 --- a/python/README.md +++ b/python/README.md @@ -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": +""}` 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 diff --git a/python/app/main.py b/python/app/main.py index e142638..54a64c7 100644 --- a/python/app/main.py +++ b/python/app/main.py @@ -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 diff --git a/python/app/rowing.py b/python/app/rowing.py new file mode 100644 index 0000000..d260bf4 --- /dev/null +++ b/python/app/rowing.py @@ -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 diff --git a/python/requirements.txt b/python/requirements.txt index fd4cdcd..d5e3566 100644 --- a/python/requirements.txt +++ b/python/requirements.txt @@ -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 diff --git a/python/tests/test_rowing.py b/python/tests/test_rowing.py new file mode 100644 index 0000000..6a28725 --- /dev/null +++ b/python/tests/test_rowing.py @@ -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 diff --git a/vue/src/views/admin/CreateRowing.vue b/vue/src/views/admin/CreateRowing.vue index eaea9ec..be3857b 100644 --- a/vue/src/views/admin/CreateRowing.vue +++ b/vue/src/views/admin/CreateRowing.vue @@ -1,7 +1,7 @@