From 63608f130ceead55227d5936dca0f48aae109aa3 Mon Sep 17 00:00:00 2001 From: Adam French Date: Tue, 20 Oct 2026 01:56:54 +0100 Subject: [PATCH] Review recorded explanations of a solution on the site The admin can upload a recording of themselves explaining a problem's solution out loud (mp3, m4a, wav, webm, ogg or flac, up to 25 MB) and get interview-style feedback, committed as reviews/.md so every attempt is kept. Claude can't take audio, so the recording is transcribed first by an OpenAI-compatible endpoint (whisper-1 by default; TRANSCRIBE_API_KEY, with TRANSCRIBE_URL for a self-hosted server). Pace, pauses, filler words and when complexity first comes up are measured from the word timestamps and given to Claude with the timestamped transcript, the statement and optionally the code. The reply covers the verdict, scores in five areas, the approach and its complexity, missed edge cases, delivery and what to work on. Recordings are kept for playback in an S3 bucket (Garage) when the S3_* settings are given, and are thrown away otherwise. Reviews are admin-only. The job runs in the background like Explain, and the statement fetch and save-error handling are now shared between the two. Co-Authored-By: Claude Opus 5.5 --- site/.env.example | 19 ++ site/CLAUDE.md | 1 + site/README.md | 23 +- site/cmd/usacosite/main.go | 39 ++- site/docker-compose.yml | 5 + site/go.mod | 12 + site/go.sum | 28 ++ site/internal/audiostore/audiostore.go | 127 ++++++++ site/internal/audiostore/audiostore_test.go | 73 +++++ site/internal/handlers/explain.go | 61 ++-- site/internal/handlers/handlers.go | 33 +- site/internal/handlers/review.go | 309 ++++++++++++++++++ site/internal/handlers/review_test.go | 305 ++++++++++++++++++ site/internal/index/index.go | 73 ++++- site/internal/index/index_test.go | 18 +- site/internal/review/review.go | 336 ++++++++++++++++++++ site/internal/review/review_test.go | 179 +++++++++++ site/internal/transcribe/metrics.go | 153 +++++++++ site/internal/transcribe/transcribe.go | 198 ++++++++++++ site/internal/transcribe/transcribe_test.go | 149 +++++++++ site/web/src/api.js | 18 +- site/web/src/components/Explanation.vue | 10 +- site/web/src/components/ReviewList.vue | 139 ++++++++ site/web/src/views/ProblemList.vue | 1 + site/web/src/views/ProblemPage.vue | 126 +++++++- 25 files changed, 2381 insertions(+), 54 deletions(-) create mode 100644 site/internal/audiostore/audiostore.go create mode 100644 site/internal/audiostore/audiostore_test.go create mode 100644 site/internal/handlers/review.go create mode 100644 site/internal/handlers/review_test.go create mode 100644 site/internal/review/review.go create mode 100644 site/internal/review/review_test.go create mode 100644 site/internal/transcribe/metrics.go create mode 100644 site/internal/transcribe/transcribe.go create mode 100644 site/internal/transcribe/transcribe_test.go create mode 100644 site/web/src/components/ReviewList.vue diff --git a/site/.env.example b/site/.env.example index 1413c7f..fac5f2b 100644 --- a/site/.env.example +++ b/site/.env.example @@ -47,3 +47,22 @@ AUTH_VALIDATE_URL= CLAUDE_API_KEY= # Model for explanations (default claude-opus-5-5). CLAUDE_MODEL= + +# --- Recording reviews ------------------------------------------------------ +# A review needs CLAUDE_API_KEY and a transcriber: anything that speaks +# OpenAI's /v1/audio/transcriptions. Blank key turns reviews off. +# OPENAI_API_KEY is read when TRANSCRIBE_API_KEY is blank. +TRANSCRIBE_API_KEY= +# Default https://api.openai.com; a self-hosted faster-whisper server's URL +# works too (with any non-blank key). +TRANSCRIBE_URL= +# Default whisper-1, which gives the word timestamps the pace and pause +# metrics come from. +TRANSCRIBE_MODEL= +# Optional: where recordings are kept for playback. All five or none; with +# none, a recording is thrown away once transcribed. Use a private bucket. +S3_ENDPOINT= +S3_REGION= +S3_BUCKET= +S3_ACCESS_KEY_ID= +S3_SECRET_ACCESS_KEY= diff --git a/site/CLAUDE.md b/site/CLAUDE.md index 2ed4c3d..532dff0 100644 --- a/site/CLAUDE.md +++ b/site/CLAUDE.md @@ -18,6 +18,7 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al - **The index is an immutable snapshot**, swapped in through an `atomic.Pointer`. Handlers read `s.Index()` once per request. - **Visibility is decided server-side.** Non-admins see only `solved/`, and an unsolved problem is a 404, not a 403. `auth.Forward` returns false for a request with no cookies without a network call. `problem.md` (the judge's statement) is admin-only even on solved problems. - **Explanations run in the background.** `POST /explain` starts a job in `explain.Jobs` and returns 202; the job calls Claude (`internal/claude`, streamed, JSON schema) and commits `explain.md` through `Mutate`. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network. +- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job in its own `explain.Jobs`: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`) and commit `reviews/.md`. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`. ## Conventions diff --git a/site/README.md b/site/README.md index 830797b..376983c 100644 --- a/site/README.md +++ b/site/README.md @@ -21,6 +21,7 @@ There is no database. The CLI's layout is the data model (see the root README.md - `notes.md` for notes - `problem.md` for the statement (shown only to the admin, and sent to Claude) - `explain.md` for a Claude-written explanation +- `reviews/.md` for feedback on a recording of the admin explaining their solution (admin only) The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into memory. @@ -31,7 +32,7 @@ The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into 3. commit as `GIT_AUTHOR_NAME` 4. push - The commit subjects match the CLI's: "Solve ", "Skip ", "Reopen " and "Update ". An explanation commits as "Explain ". If someone pushed in between and the push is rejected, the edit is replayed once on the new tip. A second rejection returns 409. + The commit subjects match the CLI's: "Solve ", "Skip ", "Reopen " and "Update ". An explanation commits as "Explain ", a review as "Review " and its deletion as "Remove review ". If someone pushed in between and the push is rejected, the edit is replayed once on the new tip. A second rejection returns 409. - **Dates come from git, not mtimes.** A problem's solve date is the commit that moved it into `solved/`. Its first and last dates are its first and last commits. The site commits, so the laptop must pull before pushing. `usaco sync` does `pull --rebase --autostash` and then `push`. @@ -46,6 +47,9 @@ internal/index/ reads the clone into memory: problems, files, tests, git dat internal/handlers/ REST API, Gitea webhook, SPA file server internal/claude/ the Claude client: streamed call, JSON-schema reply, fixed error messages internal/explain/ the explanation prompt and schema, explain.md rendering, the job tracker +internal/transcribe/ OpenAI-compatible speech-to-text client, and pace/pause/filler metrics +internal/review/ the review prompt and schema, reviews/.md rendering +internal/audiostore/ optional S3 bucket (Garage) that keeps review recordings for playback internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page) web/ Vue 3 + Vite SPA, built for base /usaco/ ``` @@ -64,6 +68,10 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro | `GET /usaco/api/problems//statement/fetch?url=` | admin | the statement behind `url` (default: the saved link) as markdown, for review; saves nothing. 422 for a judge it can't read | | `POST /usaco/api/problems//explain` | admin | `{note?, includeCode?}`: starts an explanation and answers 202; 409 if one is running, 503 without `CLAUDE_API_KEY` | | `GET /usaco/api/problems//explain` | admin | the latest job: `{state: idle\|running\|done\|error, error?}` | +| `POST /usaco/api/problems//review` | admin | multipart `audio` (mp3, m4a, wav, webm, ogg, flac; at most 25 MB), `note?`, `includeCode?`: starts a review and answers 202; 409 if one is running, 413 if too big, 503 without `CLAUDE_API_KEY` or `TRANSCRIBE_API_KEY` | +| `GET /usaco/api/problems//review` | admin | the latest review job, shaped like the explain one | +| `GET /usaco/api/problems//reviews//audio` | admin | the review's recording, with range support; 404 if it was not kept | +| `DELETE /usaco/api/problems//reviews/` | admin | removes the review and its recording | | `POST /usaco/api/problems//status` | admin | `{to: solving\|solved\|skipped}`: moves the directory | | `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull | | `GET /usaco/api/health` | open | 200 once the clone is indexed | @@ -145,10 +153,21 @@ The Explain panel on a problem page (admin only) asks Claude for an intuitive ex - **The call.** `CLAUDE_MODEL` (default `claude-opus-5-5`) at high effort, streamed, with the server-side refusal fallback on. It takes a minute or two and costs roughly $0.10 to $0.60. The request only starts a background job, because nginx gives up after 120 seconds; the page polls. Token usage is logged as `[claude]` lines. - **Statements.** LeetCode and USACO can be fetched. Codeforces sits behind a Cloudflare challenge, and other judges are unknown, so paste those. +## Recording reviews + +The "Review my explanation" panel (admin only) takes a recording of the admin explaining a solution out loud, as to an interviewer, and commits feedback on it as `reviews/.md`. The id is the UTC time it started (`2026-10-20-153000`), so each attempt is its own file and the page lists them newest first. + +- **Transcription.** Claude cannot take audio, so the recording goes first to an OpenAI-compatible `/v1/audio/transcriptions` endpoint: `TRANSCRIBE_URL` (default the OpenAI API) with `TRANSCRIBE_MODEL` (default `whisper-1`, about $0.006 a minute). It asks for word and segment timestamps, and for a verbatim transcript, because Whisper otherwise drops the fillers. A self-hosted faster-whisper server works by changing the URL. +- **Metrics.** Pace (words per minute), pauses of 2 seconds or more, filler-word counts and when complexity was first mentioned are measured from the timestamps (`transcribe.Metrics`), since Claude never hears the recording. It is told so, and judges delivery from the words and these numbers only, not tone. +- **Review.** The statement, examples, optionally the main solution file, the admin's note, the metrics and the timestamped transcript go to Claude with a JSON schema (`internal/review` `Schema`): a verdict (correct, partly correct, incorrect, incomplete), a restatement, an assessment of the approach and complexities, missed edge cases, delivery feedback quoting `[mm:ss]`, 1 to 5 scores in five areas, strengths and things to work on. The markdown ends with the metrics and the full transcript. Its first line is a `` comment the index reads. +- **The recording.** It is too big for git. With all five `S3_*` variables set it is kept in that bucket as `/.` and the page gets a player; otherwise it is thrown away once transcribed. In web_server that is a private Garage bucket, never the public `uploads` one. A recording whose review fails is deleted again. +- **Privacy.** A review is a transcript of the admin talking, so reviews and their count are blanked for everyone else, even on solved problems. + ## Things that are easy to get wrong - **`BASE_PATH` and Vite's `base` must agree.** The SPA's asset URLs and router base are fixed at build time. - **Edits must decide from disk, not the index.** `repo.Mutate` may run an edit twice, the second time on a newer tip. The handlers re-locate the problem in the clone each time with `findOnDisk`. - **`problem.md` is the judge's text.** `GET /problems/` blanks it for non-admins, so the public site links to the judge instead of republishing it. -- **An explanation job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again. +- **An explanation or review job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again). +- **Uploads are capped at 25 MB**, the OpenAI API's limit. nginx's server-wide `client_max_body_size 50M` is above it; lowering that below 25M would turn big recordings into nginx 413s. - **`tests/*.out` used to be gitignored** by the root `*.out` rule. The root `.gitignore` now re-includes `**/tests/*.out`. A test whose expected output is shown as "Not saved." predates that change or never had one. diff --git a/site/cmd/usacosite/main.go b/site/cmd/usacosite/main.go index 0f4c4ce..07f7821 100644 --- a/site/cmd/usacosite/main.go +++ b/site/cmd/usacosite/main.go @@ -1,7 +1,8 @@ // Command usacosite serves the USACO practice log at /usaco/: the problems // from adamf/usaco on the site's Gitea, their solutions and tests, and a few -// admin edits (problem link, notes, statement, status) and Claude-written -// explanations that it commits back to git. +// admin edits (problem link, notes, statement, status), Claude-written +// explanations and reviews of recorded explanations that it commits back to +// git. // // It is built to sit behind adam-french.co.uk's nginx and borrow its login // (internal/auth), like the job tracker. There is no database: the server @@ -21,10 +22,12 @@ import ( "github.com/gin-gonic/gin" + "adam-french.co.uk/usaco-site/internal/audiostore" "adam-french.co.uk/usaco-site/internal/auth" "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/handlers" "adam-french.co.uk/usaco-site/internal/repo" + "adam-french.co.uk/usaco-site/internal/transcribe" ) func main() { @@ -78,6 +81,38 @@ func main() { log.Printf("[claude] %v: explanations are off", err) } + // REVIEWS + // A recording needs a transcriber as well as Claude. OPENAI_API_KEY is + // accepted too, as the key most people already have under that name. + tkey := os.Getenv("TRANSCRIBE_API_KEY") + if tkey == "" { + tkey = os.Getenv("OPENAI_API_KEY") + } + if t, err := transcribe.New(os.Getenv("TRANSCRIBE_URL"), tkey, os.Getenv("TRANSCRIBE_MODEL")); err == nil { + srv.Transcriber = t + log.Printf("[review] recordings are transcribed with %s", t.Model()) + } else { + log.Printf("[review] %v: recording reviews are off", err) + } + // Optional on top: without it, recordings are thrown away once + // transcribed. A half-filled config is a mistake worth stopping for. + store, err := audiostore.New(audiostore.Config{ + Endpoint: os.Getenv("S3_ENDPOINT"), + Region: os.Getenv("S3_REGION"), + Bucket: os.Getenv("S3_BUCKET"), + AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), + SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY"), + }) + switch { + case err != nil: + log.Fatal(err) + case store != nil: + srv.Audio = store + log.Printf("[review] recordings are kept in the %s bucket", store.Bucket()) + default: + log.Println("[review] S3_ENDPOINT is not set: recordings are not kept") + } + rp, err := repo.New(repo.Config{ Dir: filepath.Join(dataDir, "repo"), Remote: remote, diff --git a/site/docker-compose.yml b/site/docker-compose.yml index 4e3aefe..eea8592 100644 --- a/site/docker-compose.yml +++ b/site/docker-compose.yml @@ -31,6 +31,11 @@ services: # Explain button off. CLAUDE_API_KEY: ${CLAUDE_API_KEY:-} CLAUDE_MODEL: ${CLAUDE_MODEL:-} + # Recording reviews also need a transcriber. No S3 here, so + # recordings are not kept. + TRANSCRIBE_API_KEY: ${TRANSCRIBE_API_KEY:-${OPENAI_API_KEY:-}} + TRANSCRIBE_URL: ${TRANSCRIBE_URL:-} + TRANSCRIBE_MODEL: ${TRANSCRIBE_MODEL:-} volumes: - ..:/seed:ro - usaco-data:/data diff --git a/site/go.mod b/site/go.mod index 5625c44..4853fb5 100644 --- a/site/go.mod +++ b/site/go.mod @@ -11,6 +11,18 @@ require ( require ( github.com/JohannesKaufmann/dom v0.3.1 // indirect + github.com/aws/aws-sdk-go-v2 v1.47.3 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.20.9 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect + github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 // indirect + github.com/aws/smithy-go v1.28.5 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.1.2 // indirect github.com/bytedance/sonic v1.14.0 // indirect diff --git a/site/go.sum b/site/go.sum index 2459840..7a2f0da 100644 --- a/site/go.sum +++ b/site/go.sum @@ -12,32 +12,60 @@ github.com/anthropics/anthropic-sdk-go v1.82.0 h1:A82J+yHEMbQ3+7ObCagOX4tVm1uyBh github.com/anthropics/anthropic-sdk-go v1.82.0/go.mod h1:GThfYqPJoaQ/6pmibCI98Cr4y5su2FXMUHn3NrSSnIc= github.com/aws/aws-sdk-go-v2 v1.38.0 h1:UCRQ5mlqcFk9HJDIqENSLR3wiG1VTWlyUfLDEvY7RxU= github.com/aws/aws-sdk-go-v2 v1.38.0/go.mod h1:9Q0OoGQoboYIAJyslFyF1f5K1Ryddop8gqMhWx/n4Wg= +github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk= +github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ= github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90= github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg= github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI= github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4= +github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0= +github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 h1:gr3b87OLB29jymWPzp/CAyXwQRJVE+sC4Wm0qBIKHsk= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys= github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM= github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU= +github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 h1:ChCtagixSFOxltv0o6E3NT8F7ksvZtZGPwUBynO5Nmk= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEBrucJEryfrQU0TffmACk= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 h1:OKEfbf2tcfsF2pBk/S9QqNpo6alaAtiBs4hysCsBjPw= github.com/aws/smithy-go v1.22.5 h1:P9ATCXPMb2mPjYBgueqJNCA5S9UfktsW0tTxi+a7eqw= github.com/aws/smithy-go v1.22.5/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI= +github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k= +github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= diff --git a/site/internal/audiostore/audiostore.go b/site/internal/audiostore/audiostore.go new file mode 100644 index 0000000..483d821 --- /dev/null +++ b/site/internal/audiostore/audiostore.go @@ -0,0 +1,127 @@ +// Package audiostore keeps the review recordings in an S3 bucket, so they +// can be played back next to their feedback. In production that is a +// private bucket on web_server's Garage. +// +// It is optional. Git is the site's store and a recording is about a +// megabyte a minute, too big to commit, so without the S3_* settings the +// audio is transcribed and thrown away and only the review is kept. +package audiostore + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" +) + +// ErrNotFound is a key with no object. +var ErrNotFound = errors.New("no such recording") + +// Config is the S3_* block of the environment. +type Config struct { + Endpoint string // e.g. http://garage:3900 + Region string // must match garage.toml's s3_region + Bucket string + AccessKeyID string + SecretAccessKey string +} + +// Store is one bucket. +type Store struct { + client *s3.Client + bucket string +} + +// New returns nil, and the audio is thrown away, unless every setting is +// given: half a config is more likely a typo than a wish to store nothing. +func New(cfg Config) (*Store, error) { + set := 0 + for _, v := range []string{cfg.Endpoint, cfg.Region, cfg.Bucket, cfg.AccessKeyID, cfg.SecretAccessKey} { + if v != "" { + set++ + } + } + switch set { + case 0: + return nil, nil + case 5: + default: + return nil, errors.New("S3_ENDPOINT, S3_REGION, S3_BUCKET, S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY must be set together") + } + // The same options as web_server's backend uses for Garage. + client := s3.New(s3.Options{ + BaseEndpoint: aws.String(cfg.Endpoint), + Region: cfg.Region, + Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""), + // Garage addresses buckets by path (/bucket/key); virtual-host style + // would need a DNS name per bucket. + UsePathStyle: true, + // Recent SDKs add CRC32 checksums to every PUT by default. Only send + // them where S3 requires them, which is what third-party servers + // handle reliably. + RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, + ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, + }) + return &Store{client: client, bucket: cfg.Bucket}, nil +} + +// Bucket is where everything goes. +func (s *Store) Bucket() string { return s.bucket } + +// Garage is on the same Docker network, so anything near this is a hang. +const timeout = 2 * time.Minute + +// Put stores one recording. +func (s *Store) Put(ctx context.Context, key, contentType string, b []byte) error { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + _, err := s.client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + Body: bytes.NewReader(b), + ContentLength: aws.Int64(int64(len(b))), + ContentType: aws.String(contentType), + }) + if err != nil { + return fmt.Errorf("s3 put %s/%s: %w", s.bucket, key, err) + } + return nil +} + +// Object is a recording being read; the caller closes Body. +type Object struct { + Body io.ReadCloser + ContentType string + Size int64 +} + +// Get opens one recording. +func (s *Store) Get(ctx context.Context, key string) (*Object, error) { + out, err := s.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)}) + if err != nil { + var nk *types.NoSuchKey + if errors.As(err, &nk) { + return nil, ErrNotFound + } + return nil, fmt.Errorf("s3 get %s/%s: %w", s.bucket, key, err) + } + return &Object{Body: out.Body, ContentType: aws.ToString(out.ContentType), Size: aws.ToInt64(out.ContentLength)}, nil +} + +// Delete removes one recording. A missing one is not an error: S3 does not +// report it either. +func (s *Store) Delete(ctx context.Context, key string) error { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + if _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)}); err != nil { + return fmt.Errorf("s3 delete %s/%s: %w", s.bucket, key, err) + } + return nil +} diff --git a/site/internal/audiostore/audiostore_test.go b/site/internal/audiostore/audiostore_test.go new file mode 100644 index 0000000..d8e368e --- /dev/null +++ b/site/internal/audiostore/audiostore_test.go @@ -0,0 +1,73 @@ +package audiostore + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +func TestNewNeedsAllOrNothing(t *testing.T) { + if s, err := New(Config{}); s != nil || err != nil { + t.Errorf("empty config = %v, %v; want nil, nil", s, err) + } + if _, err := New(Config{Endpoint: "http://garage:3900"}); err == nil { + t.Error("half a config should be an error") + } +} + +// A fake S3 that holds objects in a map, addressed by path as Garage is. +func TestPutGetDelete(t *testing.T) { + objs := map[string][]byte{} + types := map[string]string{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPut: + b, _ := io.ReadAll(r.Body) + objs[r.URL.Path], types[r.URL.Path] = b, r.Header.Get("Content-Type") + case http.MethodGet: + b, ok := objs[r.URL.Path] + if !ok { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(404) + io.WriteString(w, `NoSuchKeygone`) + return + } + w.Header().Set("Content-Type", types[r.URL.Path]) + w.Write(b) + case http.MethodDelete: + delete(objs, r.URL.Path) + w.WriteHeader(204) + } + })) + defer srv.Close() + + s, err := New(Config{Endpoint: srv.URL, Region: "garage", Bucket: "usaco-audio", AccessKeyID: "GK1", SecretAccessKey: "s"}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := s.Put(ctx, "moocast/2026-10-20-153000.mp3", "audio/mpeg", []byte("ID3")); err != nil { + t.Fatal(err) + } + if string(objs["/usaco-audio/moocast/2026-10-20-153000.mp3"]) != "ID3" { + t.Fatalf("objects = %v", objs) + } + o, err := s.Get(ctx, "moocast/2026-10-20-153000.mp3") + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(o.Body) + o.Body.Close() + if string(b) != "ID3" || o.ContentType != "audio/mpeg" { + t.Errorf("get = %q %q", b, o.ContentType) + } + if err := s.Delete(ctx, "moocast/2026-10-20-153000.mp3"); err != nil { + t.Fatal(err) + } + if _, err := s.Get(ctx, "moocast/2026-10-20-153000.mp3"); !errors.Is(err, ErrNotFound) { + t.Errorf("get after delete: %v, want ErrNotFound", err) + } +} diff --git a/site/internal/handlers/explain.go b/site/internal/handlers/explain.go index a1c4b6c..e5fef3d 100644 --- a/site/internal/handlers/explain.go +++ b/site/internal/handlers/explain.go @@ -124,16 +124,9 @@ func (s *Server) explain(in explain.Input, link string) error { ctx, cancel := context.WithTimeout(context.Background(), explainTimeout) defer cancel() - // No statement saved: fetch it, and save it alongside the explanation - // so the next one does not need the judge. - fetched := "" - if strings.TrimSpace(in.Statement) == "" { - md, err := s.fetcher().Fetch(ctx, link) - if err != nil { - log.Printf("[explain] %s: fetching %s: %v", in.Name, link, err) - return fmt.Errorf("could not fetch the statement (%v); paste it into the editor", err) - } - in.Statement, fetched = md, md + fetched, err := s.ensureStatement(ctx, "explain", in.Name, &in.Statement, link) + if err != nil { + return err } md, err := explain.Generate(ctx, s.Claude, in, time.Now()) @@ -154,17 +147,45 @@ func (s *Server) explain(in explain.Input, link string) error { return err } pdir := filepath.Join(dir, status, name) - if fetched != "" { - // Only if it is still missing: the admin may have pasted one - // while Claude was working. - if _, err := os.Stat(filepath.Join(pdir, "problem.md")); os.IsNotExist(err) { - if err := writeOrRemove(filepath.Join(pdir, "problem.md"), fetched); err != nil { - return err - } - } + if err := saveFetched(pdir, fetched); err != nil { + return err } return writeOrRemove(filepath.Join(pdir, "explain.md"), md) }) + return jobSaveError("explain", name, "the explanation was written but could not be saved to git", err) +} + +// ensureStatement fetches the statement when none is saved, so a job can +// run on a problem that only has a link. It returns what it fetched, for +// saveFetched to keep alongside the job's result so the next job does not +// need the judge. tag is the log prefix. +func (s *Server) ensureStatement(ctx context.Context, tag, name string, statement *string, link string) (string, error) { + if strings.TrimSpace(*statement) != "" { + return "", nil + } + md, err := s.fetcher().Fetch(ctx, link) + if err != nil { + log.Printf("[%s] %s: fetching %s: %v", tag, name, link, err) + return "", fmt.Errorf("could not fetch the statement (%v); paste it into the editor", err) + } + *statement = md + return md, nil +} + +// saveFetched writes a statement ensureStatement fetched, but only if it is +// still missing: the admin may have pasted one while Claude was working. +func saveFetched(pdir, fetched string) error { + if fetched == "" { + return nil + } + if _, err := os.Stat(filepath.Join(pdir, "problem.md")); os.IsNotExist(err) { + return writeOrRemove(filepath.Join(pdir, "problem.md"), fetched) + } + return nil +} + +// jobSaveError turns a job's Mutate error into a message for the admin. +func jobSaveError(tag, name, unsaved string, err error) error { var re *requestError switch { case err == nil: @@ -174,8 +195,8 @@ func (s *Server) explain(in explain.Input, link string) error { case errors.Is(err, repo.ErrRejected): return errors.New("the repository changed while saving; try again") default: - log.Printf("[explain] %s: saving: %v", name, err) - return errors.New("the explanation was written but could not be saved to git") + log.Printf("[%s] %s: saving: %v", tag, name, err) + return errors.New(unsaved) } } diff --git a/site/internal/handlers/handlers.go b/site/internal/handlers/handlers.go index 2a8fa3f..949ac34 100644 --- a/site/internal/handlers/handlers.go +++ b/site/internal/handlers/handlers.go @@ -1,7 +1,7 @@ // Package handlers is the site's REST API: the problem list and pages (public // for solved problems, everything for the admin), the admin's edits, the -// Claude explanations (explain.go), and the Gitea webhook that tells the -// server to pull. +// Claude explanations (explain.go) and recording reviews (review.go), and +// the Gitea webhook that tells the server to pull. package handlers import ( @@ -49,9 +49,17 @@ type Server struct { // Statements reads a statement from the problem's judge; nil means the // real judges. Statements Fetcher + // Transcriber turns review recordings into text; nil when + // TRANSCRIBE_API_KEY is not set, which turns reviews off. + Transcriber Transcriber + // Audio keeps review recordings for playback; nil when the S3_* + // settings are not given, and the recordings are then thrown away. + Audio AudioStore - idx atomic.Pointer[index.Index] - jobs explain.Jobs + idx atomic.Pointer[index.Index] + // Separate, so a review and an explanation of one problem can run at + // the same time. + jobs, reviewJobs explain.Jobs } // SetIndex swaps in a freshly built index. repo.Repo calls it (through @@ -85,6 +93,10 @@ func (s *Server) Routes(api *gin.RouterGroup) { admin.GET("/problems/:name/statement/fetch", s.fetchStatement) admin.POST("/problems/:name/explain", s.startExplain) admin.GET("/problems/:name/explain", s.explainStatus) + admin.POST("/problems/:name/review", s.startReview) + admin.GET("/problems/:name/review", s.reviewStatus) + admin.GET("/problems/:name/reviews/:id/audio", s.reviewAudio) + admin.DELETE("/problems/:name/reviews/:id", s.deleteReview) api.POST("/hooks/gitea", s.webhook) } @@ -123,7 +135,11 @@ func (s *Server) list(ctx *gin.Context) { out := []index.Summary{} for _, p := range idx.Problems { if visible(p, admin) { - out = append(out, p.Summary) + sum := p.Summary + if !admin { + sum.ReviewCount = 0 + } + out = append(out, sum) } } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) @@ -162,11 +178,12 @@ func (s *Server) get(ctx *gin.Context) { return } // The statement is the judge's text, kept for the admin and for Claude; - // the public page links to the judge instead. The index is shared, so - // this blanks a copy. - if !admin && p.Statement != "" { + // the public page links to the judge instead. Reviews are a transcript + // of the admin talking. The index is shared, so this blanks a copy. + if !admin && (p.Statement != "" || len(p.Reviews) > 0) { c := *p c.Statement = "" + c.Reviews, c.ReviewCount = []index.Review{}, 0 p = &c } ctx.JSON(http.StatusOK, p) diff --git a/site/internal/handlers/review.go b/site/internal/handlers/review.go new file mode 100644 index 0000000..e841961 --- /dev/null +++ b/site/internal/handlers/review.go @@ -0,0 +1,309 @@ +package handlers + +import ( + "bytes" + "context" + "errors" + "io" + "log" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/audiostore" + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/index" + "adam-french.co.uk/usaco-site/internal/review" + "adam-french.co.uk/usaco-site/internal/transcribe" +) + +// Transcriber is the part of transcribe.Client the handlers use, so tests +// can fake it. +type Transcriber interface { + Transcribe(ctx context.Context, filename string, audio []byte) (*transcribe.Transcript, error) + Model() string +} + +// AudioStore is the part of audiostore.Store the handlers use. +type AudioStore interface { + Put(ctx context.Context, key, contentType string, b []byte) error + Get(ctx context.Context, key string) (*audiostore.Object, error) + Delete(ctx context.Context, key string) error +} + +// The formats OpenAI's transcription endpoint takes, by extension, with the +// type the recording is stored and played back as. +var audioTypes = map[string]string{ + ".mp3": "audio/mpeg", ".mpga": "audio/mpeg", ".mpeg": "audio/mpeg", + ".m4a": "audio/mp4", ".mp4": "audio/mp4", + ".wav": "audio/wav", ".webm": "audio/webm", + ".ogg": "audio/ogg", ".oga": "audio/ogg", ".flac": "audio/flac", +} + +// A review's id is the UTC time it was started. Checking the shape keeps +// anything path-like out of the filesystem and the bucket. +const reviewIDLayout = "2006-01-02-150405" + +var validReviewID = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}-\d{6}$`) + +// Transcription and a long recording's review both take minutes. +const reviewTimeout = 10 * time.Minute + +// startReview takes the recording and starts the review; the page polls +// reviewStatus. Like startExplain, everything Claude sees about the problem +// is taken from the index now. +func (s *Server) startReview(ctx *gin.Context) { + p, ok := s.lookup(ctx, true) + if !ok { + return + } + if s.Claude == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + return + } + if s.Transcriber == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "transcription is not configured on this server (TRANSCRIBE_API_KEY)"}) + return + } + + // The form's other fields are tiny; the slack is for them and the + // multipart framing. + ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, transcribe.MaxBytes+64<<10) + fh, err := ctx.FormFile("audio") + if err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the recording is over 25 MB; export it at a lower bitrate"}) + return + } + ctx.JSON(http.StatusBadRequest, gin.H{"error": "attach the recording as audio"}) + return + } + ext := strings.ToLower(filepath.Ext(fh.Filename)) + contentType, ok := audioTypes[ext] + if !ok { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the recording must be mp3, m4a, wav, webm, ogg or flac"}) + return + } + if fh.Size > transcribe.MaxBytes { + ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the recording is over 25 MB; export it at a lower bitrate"}) + return + } + f, err := fh.Open() + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the recording could not be read"}) + return + } + audio, err := io.ReadAll(f) + f.Close() + if err != nil || len(audio) == 0 { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the recording is empty"}) + return + } + + note := ctx.PostForm("note") + if len(note) > maxNote { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"}) + return + } + if strings.TrimSpace(p.Statement) == "" && p.URL == "" { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"}) + return + } + + in := review.Input{Name: p.Name, Statement: p.Statement, Note: note, Examples: examples(p)} + if ctx.PostForm("includeCode") == "true" { + in.Code = mainFile(p) + } + // Chosen now rather than in the job's edit, which Mutate may replay: + // a replay must write the same file. + id := time.Now().UTC().Format(reviewIDLayout) + rec := recording{name: id + ext, contentType: contentType, data: audio} + link := p.URL + if !s.reviewJobs.Start(p.Name, func() error { return s.review(in, link, id, rec) }) { + ctx.JSON(http.StatusConflict, gin.H{"error": "a recording is already being reviewed"}) + return + } + ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name)) +} + +func (s *Server) reviewStatus(ctx *gin.Context) { + if p, ok := s.lookup(ctx, true); ok { + ctx.JSON(http.StatusOK, s.reviewJobs.Get(p.Name)) + } +} + +type recording struct { + name, contentType string + data []byte +} + +// review is one job. Its error is shown to the admin, so every path returns +// a message meant for them and logs the detail. +func (s *Server) review(in review.Input, link, id string, rec recording) (err error) { + ctx, cancel := context.WithTimeout(context.Background(), reviewTimeout) + defer cancel() + name := in.Name + + fetched, err := s.ensureStatement(ctx, "review", name, &in.Statement, link) + if err != nil { + return err + } + + tr, err := s.Transcriber.Transcribe(ctx, rec.name, rec.data) + if err != nil { + var f *transcribe.Failure + if errors.As(err, &f) { + log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err) + return f + } + log.Printf("[review] %s: transcribing: %v", name, err) + return errors.New("the recording could not be transcribed") + } + in.Transcript, in.Metrics = tr, tr.Metrics() + + // The recording is kept only if there is somewhere to keep it, and a + // failure to keep it costs the playback, not the review. It is stored + // before Claude runs so the review can point at it, and removed again + // if the review never gets saved. + key := "" + if s.Audio != nil { + k := name + "/" + rec.name + if perr := s.Audio.Put(ctx, k, rec.contentType, rec.data); perr != nil { + log.Printf("[review] %s: storing the recording: %v", name, perr) + } else { + key = k + // err is the job's result: set by the return statements below. + defer func() { + if err != nil { + if derr := s.Audio.Delete(context.Background(), key); derr != nil { + log.Printf("[review] %s: removing the unused recording: %v", name, derr) + } + } + }() + } + } + + md, err := review.Generate(ctx, s.Claude, in, review.Meta{Now: time.Now(), Transcriber: s.Transcriber.Model(), Audio: key}) + if err != nil { + var f *claude.Failure + if errors.As(err, &f) { + log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err) + return f + } + log.Printf("[review] %s: %v", name, err) + return errors.New("the review could not be written") + } + + err = s.Repo.Mutate(ctx, "Review "+name, func(dir string) error { + status, err := findOnDisk(dir, name) + if err != nil { + return err + } + pdir := filepath.Join(dir, status, name) + if err := saveFetched(pdir, fetched); err != nil { + return err + } + if err := os.MkdirAll(filepath.Join(pdir, "reviews"), 0o755); err != nil { + return err + } + return writeOrRemove(filepath.Join(pdir, "reviews", id+".md"), md) + }) + return jobSaveError("review", name, "the review was written but could not be saved to git", err) +} + +// findReview is the problem's review with the URL's id. +func findReview(ctx *gin.Context, p *index.Problem) (*index.Review, bool) { + id := ctx.Param("id") + if validReviewID.MatchString(id) { + for i := range p.Reviews { + if p.Reviews[i].ID == id { + return &p.Reviews[i], true + } + } + } + ctx.JSON(http.StatusNotFound, gin.H{"error": "no such review"}) + return nil, false +} + +// reviewAudio plays a review's recording back. It is read whole and served +// with ServeContent so the player can seek (range requests); recordings are +// at most 25 MB. +func (s *Server) reviewAudio(ctx *gin.Context) { + p, ok := s.lookup(ctx, true) + if !ok { + return + } + r, ok := findReview(ctx, p) + if !ok { + return + } + if s.Audio == nil || r.Audio == "" { + ctx.JSON(http.StatusNotFound, gin.H{"error": "this review's recording was not kept"}) + return + } + c, cancel := context.WithTimeout(ctx.Request.Context(), time.Minute) + defer cancel() + obj, err := s.Audio.Get(c, r.Audio) + if errors.Is(err, audiostore.ErrNotFound) { + ctx.JSON(http.StatusNotFound, gin.H{"error": "the recording is gone from storage"}) + return + } + if err != nil { + log.Printf("[review] %s: reading %s: %v", p.Name, r.Audio, err) + ctx.JSON(http.StatusBadGateway, gin.H{"error": "the recording could not be read"}) + return + } + defer obj.Body.Close() + b, err := io.ReadAll(io.LimitReader(obj.Body, transcribe.MaxBytes+1)) + if err != nil { + log.Printf("[review] %s: reading %s: %v", p.Name, r.Audio, err) + ctx.JSON(http.StatusBadGateway, gin.H{"error": "the recording could not be read"}) + return + } + if obj.ContentType != "" { + ctx.Header("Content-Type", obj.ContentType) + } + ctx.Header("Cache-Control", "private, max-age=3600") + http.ServeContent(ctx.Writer, ctx.Request, filepath.Base(r.Audio), time.Time{}, bytes.NewReader(b)) +} + +// deleteReview removes a review and, once that is committed, its recording. +func (s *Server) deleteReview(ctx *gin.Context) { + p, ok := s.lookup(ctx, true) + if !ok { + return + } + r, ok := findReview(ctx, p) + if !ok { + return + } + name, id, audio := p.Name, r.ID, r.Audio + s.mutate(ctx, name, "Remove review "+name, func(dir string) error { + status, err := findOnDisk(dir, name) + if err != nil { + return err + } + rdir := filepath.Join(dir, status, name, "reviews") + if err := os.Remove(filepath.Join(rdir, id+".md")); err != nil { + if os.IsNotExist(err) { + return &requestError{http.StatusNotFound, "no such review"} + } + return err + } + // Only succeeds when it was the last review; git does not keep + // empty directories anyway. + os.Remove(rdir) + return nil + }) + if ctx.Writer.Status() == http.StatusOK && audio != "" && s.Audio != nil { + if err := s.Audio.Delete(context.Background(), audio); err != nil { + log.Printf("[review] %s: removing %s: %v", name, audio, err) + } + } +} diff --git a/site/internal/handlers/review_test.go b/site/internal/handlers/review_test.go new file mode 100644 index 0000000..f1b47e7 --- /dev/null +++ b/site/internal/handlers/review_test.go @@ -0,0 +1,305 @@ +package handlers + +import ( + "bytes" + "context" + "encoding/json" + "io" + "mime/multipart" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/audiostore" + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/index" + "adam-french.co.uk/usaco-site/internal/review" + "adam-french.co.uk/usaco-site/internal/transcribe" +) + +// fakeReviewer answers every review with one verdict, or fails. +type fakeReviewer struct { + user string + fail bool +} + +func (f *fakeReviewer) Model() string { return "fake-model" } +func (f *fakeReviewer) JSON(_ context.Context, req claude.Request, out any) error { + f.user = req.User + if f.fail { + return &claude.Failure{Msg: "Claude declined to answer"} + } + *out.(*review.Result) = review.Result{Verdict: "correct", Summary: "Union-find over the edges."} + return nil +} + +type fakeTranscriber struct { + file string + audio []byte + err error +} + +func (f *fakeTranscriber) Model() string { return "fake-whisper" } +func (f *fakeTranscriber) Transcribe(_ context.Context, filename string, audio []byte) (*transcribe.Transcript, error) { + f.file, f.audio = filename, audio + if f.err != nil { + return nil, f.err + } + return &transcribe.Transcript{ + Text: "Um, I'd union the cows.", Duration: 60, + Segments: []transcribe.Segment{{Start: 0, End: 4, Text: " Um, I'd union the cows."}}, + }, nil +} + +// fakeStore is a bucket in a map. +type fakeStore struct { + mu sync.Mutex + objs map[string]string + typ map[string]string +} + +func newFakeStore() *fakeStore { + return &fakeStore{objs: map[string]string{}, typ: map[string]string{}} +} + +func (f *fakeStore) Put(_ context.Context, key, contentType string, b []byte) error { + f.mu.Lock() + defer f.mu.Unlock() + f.objs[key], f.typ[key] = string(b), contentType + return nil +} + +func (f *fakeStore) Get(_ context.Context, key string) (*audiostore.Object, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.objs[key] + if !ok { + return nil, audiostore.ErrNotFound + } + return &audiostore.Object{Body: io.NopCloser(strings.NewReader(b)), ContentType: f.typ[key], Size: int64(len(b))}, nil +} + +func (f *fakeStore) Delete(_ context.Context, key string) error { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.objs, key) + return nil +} + +func (f *fakeStore) keys() []string { + f.mu.Lock() + defer f.mu.Unlock() + var ks []string + for k := range f.objs { + ks = append(ks, k) + } + return ks +} + +// upload posts a recording form; size pads the audio to that many bytes. +func upload(r *gin.Engine, name, filename string, size int, fields ...string) *httptest.ResponseRecorder { + var body bytes.Buffer + w := multipart.NewWriter(&body) + for i := 0; i+1 < len(fields); i += 2 { + w.WriteField(fields[i], fields[i+1]) + } + if filename != "" { + part, _ := w.CreateFormFile("audio", filename) + part.Write([]byte("ID3")) + if size > 3 { + part.Write(make([]byte, size-3)) + } + } + w.Close() + return do(r, "POST", "/usaco/api/problems/"+name+"/review", body.String(), true, "Content-Type", w.FormDataContentType()) +} + +func waitReview(t *testing.T, r *gin.Engine, name string) explain.Status { + t.Helper() + for range 400 { + var s explain.Status + json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/review", "", true).Body.Bytes(), &s) + if s.State != explain.Running { + return s + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("review still running") + return explain.Status{} +} + +func withStatement(t *testing.T, r *gin.Engine) { + t.Helper() + if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast\nwalkie-talkies"}`, true); rec.Code != 200 { + t.Fatalf("saving a statement = %d: %s", rec.Code, rec.Body) + } +} + +func TestReviewNeedsConfigAndAValidRecording(t *testing.T) { + r, repo, _ := setup(t) + if rec := upload(r, "moocast", "a.mp3", 10); rec.Code != 503 { + t.Fatalf("no Claude = %d, want 503", rec.Code) + } + repo.srv.Claude = &fakeReviewer{} + if rec := upload(r, "moocast", "a.mp3", 10); rec.Code != 503 || !strings.Contains(rec.Body.String(), "TRANSCRIBE_API_KEY") { + t.Fatalf("no transcriber = %d %s, want 503", rec.Code, rec.Body) + } + repo.srv.Transcriber = &fakeTranscriber{} + if rec := do(r, "POST", "/usaco/api/problems/moocast/review", "", false); rec.Code != 401 { + t.Fatalf("public upload = %d, want 401", rec.Code) + } + for _, c := range []struct { + file string + size int + want int + }{ + {"", 0, 400}, + {"notes.txt", 10, 400}, + {"a.mp3", transcribe.MaxBytes + 1, 413}, + {"a.mp3", 10, 400}, // no statement or link yet + } { + if rec := upload(r, "moocast", c.file, c.size); rec.Code != c.want { + t.Errorf("%q (%d bytes) = %d %s, want %d", c.file, c.size, rec.Code, rec.Body, c.want) + } + } + if rec := upload(r, "moocast", "a.mp3", 10, "note", strings.Repeat("x", maxNote+1)); rec.Code != 400 { + t.Errorf("long note = %d, want 400", rec.Code) + } +} + +func TestReviewWritesAndCommits(t *testing.T) { + r, repo, _ := setup(t) + fr, ft := &fakeReviewer{}, &fakeTranscriber{} + repo.srv.Claude, repo.srv.Transcriber = fr, ft + withStatement(t, r) + + if rec := upload(r, "moocast", "Take 1.M4A", 10, "note", "mock interview", "includeCode", "true"); rec.Code != 202 { + t.Fatalf("start = %d: %s", rec.Code, rec.Body) + } + if s := waitReview(t, r, "moocast"); s.State != explain.Done { + t.Fatalf("job = %+v, want done", s) + } + if !strings.HasSuffix(ft.file, ".m4a") || string(ft.audio[:3]) != "ID3" { + t.Errorf("transcriber got %q, %q", ft.file, ft.audio) + } + for _, want := range []string{"walkie-talkies", "\nmock interview", "", "[00:00] Um, I'd union the cows."} { + if !strings.Contains(fr.user, want) { + t.Errorf("prompt is missing %q:\n%s", want, fr.user) + } + } + if last := repo.msg[len(repo.msg)-1]; last != "Review moocast" { + t.Errorf("commit subject = %q", last) + } + + files, _ := filepath.Glob(filepath.Join(repo.dir, "solved/moocast/reviews/*.md")) + if len(files) != 1 { + t.Fatalf("reviews = %v", files) + } + b, _ := os.ReadFile(files[0]) + if md := string(b); !strings.HasPrefix(md, "\n_Reviewed by fake-model") || !strings.Contains(md, "transcribed by fake-whisper") { + t.Errorf("review = %s", md) + } + + var adm index.Problem + json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", true).Body.Bytes(), &adm) + if len(adm.Reviews) != 1 || adm.Reviews[0].Verdict != "correct" || adm.Reviews[0].HasAudio || adm.ReviewCount != 1 { + t.Fatalf("admin reviews = %+v", adm.Reviews) + } + id := adm.Reviews[0].ID + if rec := do(r, "GET", "/usaco/api/problems/moocast/reviews/"+id+"/audio", "", true); rec.Code != 404 { + t.Errorf("audio with no store = %d, want 404", rec.Code) + } + + // Reviews are the admin's alone, even on a solved problem. + var pub struct { + Reviews []index.Review + ReviewCount int + } + json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", false).Body.Bytes(), &pub) + if len(pub.Reviews) != 0 || pub.ReviewCount != 0 { + t.Errorf("public view = %+v", pub) + } + if body := do(r, "GET", "/usaco/api/problems", "", false).Body.String(); strings.Contains(body, `"reviewCount":1`) { + t.Errorf("public list shows the review count: %s", body) + } + if rec := do(r, "DELETE", "/usaco/api/problems/moocast/reviews/"+id, "", false); rec.Code != 401 { + t.Errorf("public delete = %d, want 401", rec.Code) + } +} + +func TestReviewKeepsAndRemovesTheRecording(t *testing.T) { + r, repo, _ := setup(t) + store := newFakeStore() + repo.srv.Claude, repo.srv.Transcriber, repo.srv.Audio = &fakeReviewer{}, &fakeTranscriber{}, store + withStatement(t, r) + + upload(r, "moocast", "take.mp3", 100) + if s := waitReview(t, r, "moocast"); s.State != explain.Done { + t.Fatalf("job = %+v, want done", s) + } + var p index.Problem + json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", true).Body.Bytes(), &p) + if len(p.Reviews) != 1 || !p.Reviews[0].HasAudio { + t.Fatalf("reviews = %+v", p.Reviews) + } + id := p.Reviews[0].ID + if keys := store.keys(); len(keys) != 1 || keys[0] != "moocast/"+id+".mp3" { + t.Fatalf("stored = %v", keys) + } + + rec := do(r, "GET", "/usaco/api/problems/moocast/reviews/"+id+"/audio", "", true, "Range", "bytes=0-2") + if rec.Code != 206 || rec.Body.String() != "ID3" || rec.Header().Get("Content-Type") != "audio/mpeg" { + t.Errorf("ranged audio = %d %q %q", rec.Code, rec.Body, rec.Header().Get("Content-Type")) + } + for _, bad := range []string{"..", "2026-01-01-000000", "notes"} { + if rec := do(r, "GET", "/usaco/api/problems/moocast/reviews/"+bad+"/audio", "", true); rec.Code != 404 { + t.Errorf("audio for %q = %d, want 404", bad, rec.Code) + } + } + + if rec := do(r, "DELETE", "/usaco/api/problems/moocast/reviews/"+id, "", true); rec.Code != 200 { + t.Fatalf("delete = %d: %s", rec.Code, rec.Body) + } + if last := repo.msg[len(repo.msg)-1]; last != "Remove review moocast" { + t.Errorf("commit subject = %q", last) + } + if _, err := os.Stat(filepath.Join(repo.dir, "solved/moocast/reviews")); !os.IsNotExist(err) { + t.Error("the empty reviews dir should be gone") + } + if keys := store.keys(); len(keys) != 0 { + t.Errorf("recording not removed: %v", keys) + } +} + +func TestReviewFailures(t *testing.T) { + r, repo, _ := setup(t) + store := newFakeStore() + ft := &fakeTranscriber{err: &transcribe.Failure{Msg: "no speech was found in the recording"}} + fr := &fakeReviewer{} + repo.srv.Claude, repo.srv.Transcriber, repo.srv.Audio = fr, ft, store + withStatement(t, r) + commits := len(repo.msg) + + upload(r, "moocast", "a.mp3", 10) + if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "no speech was found in the recording" { + t.Fatalf("transcription failure: job = %+v", s) + } + + // The recording is stored before Claude runs, and must not be left + // behind when the review fails. + ft.err, fr.fail = nil, true + upload(r, "moocast", "a.mp3", 10) + if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" { + t.Fatalf("Claude failure: job = %+v", s) + } + if len(repo.msg) != commits || len(store.keys()) != 0 { + t.Errorf("a failed review left commits %v or recordings %v", repo.msg[commits:], store.keys()) + } +} diff --git a/site/internal/index/index.go b/site/internal/index/index.go index 72bc4a5..1cbfd0f 100644 --- a/site/internal/index/index.go +++ b/site/internal/index/index.go @@ -4,8 +4,9 @@ // The layout is the CLI's (README.md at the repo root): solving/, solved/ // and skipped//, each with a solution (main.cpp, sol.py...), an .in // the CLI wires up, tests/N.in + N.out, and optionally a .url, notes.md, -// problem.md (the statement, pasted or fetched from the judge by the site) -// and explain.md (an explanation the site had Claude write). The repo is +// problem.md (the statement, pasted or fetched from the judge by the site), +// explain.md (an explanation the site had Claude write) and reviews/.md +// (feedback on a recording of the admin explaining it). The repo is // small, so everything, file contents included, is read on each rebuild, // and a rebuild only happens when the clone changes. package index @@ -19,6 +20,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "sort" "strconv" "strings" @@ -71,6 +73,7 @@ type Summary struct { Tests int `json:"tests"` HasNotes bool `json:"hasNotes"` HasExplanation bool `json:"hasExplanation"` + ReviewCount int `json:"reviewCount"` FirstSeen *time.Time `json:"firstSeen,omitempty"` SolvedAt *time.Time `json:"solvedAt,omitempty"` LastTouched *time.Time `json:"lastTouched,omitempty"` @@ -83,12 +86,28 @@ type Problem struct { Notes string `json:"notes"` // Statement is the judge's text, so the handlers send it to the admin // only: the site should not republish it. - Statement string `json:"statement,omitempty"` - Explanation string `json:"explanation"` - Files []File `json:"files"` - Sample *File `json:"sample,omitempty"` - TestSet []Test `json:"testCases"` - History []Commit `json:"history"` + Statement string `json:"statement,omitempty"` + Explanation string `json:"explanation"` + // Reviews are newest first, and admin-only like Statement: they are a + // transcript of the admin talking. + Reviews []Review `json:"reviews"` + Files []File `json:"files"` + Sample *File `json:"sample,omitempty"` + TestSet []Test `json:"testCases"` + History []Commit `json:"history"` +} + +// Review is one reviews/.md. The site writes the id as the UTC time of +// the recording, so ids sort by age. +type Review struct { + ID string `json:"id"` + Verdict string `json:"verdict,omitempty"` + // Audio is the recording's key in the audio store; the page only needs + // to know there is one. + Audio string `json:"-"` + HasAudio bool `json:"hasAudio"` + // Content is the markdown without its header comment. + Content string `json:"content"` } // Index is one snapshot of the clone. @@ -145,7 +164,7 @@ var langs = map[string]string{ } func readProblem(pdir, status string) (*Problem, error) { - p := &Problem{Summary: Summary{Name: filepath.Base(pdir), Status: status, Langs: []string{}}, Files: []File{}, TestSet: []Test{}, History: []Commit{}} + p := &Problem{Summary: Summary{Name: filepath.Base(pdir), Status: status, Langs: []string{}}, Reviews: []Review{}, Files: []File{}, TestSet: []Test{}, History: []Commit{}} entries, err := os.ReadDir(pdir) if err != nil { @@ -208,6 +227,10 @@ func readProblem(pdir, status string) (*Problem, error) { } p.TestSet = tests p.Tests = len(tests) + if p.Reviews, err = readReviews(filepath.Join(pdir, "reviews")); err != nil { + return nil, err + } + p.ReviewCount = len(p.Reviews) p.HasNotes = strings.TrimSpace(p.Notes) != "" p.HasExplanation = strings.TrimSpace(p.Explanation) != "" p.Source = Source(p.URL) @@ -251,6 +274,38 @@ func readTests(tdir string) ([]Test, error) { return tests, nil } +// reviewHead is the comment internal/review writes as a review's first line. +var reviewHead = regexp.MustCompile(`^\r?\n`) + +func readReviews(rdir string) ([]Review, error) { + entries, err := os.ReadDir(rdir) + if os.IsNotExist(err) { + return []Review{}, nil + } + if err != nil { + return nil, err + } + out := []Review{} + for _, e := range entries { + id, ok := strings.CutSuffix(e.Name(), ".md") + if !ok || e.IsDir() { + continue + } + f, err := readFile(filepath.Join(rdir, e.Name()), "") + if err != nil { + return nil, err + } + r := Review{ID: id, Content: f.Content} + if m := reviewHead.FindStringSubmatch(f.Content); m != nil { + r.Verdict, r.Audio, r.HasAudio = m[1], m[2], m[2] != "" + r.Content = f.Content[len(m[0]):] + } + out = append(out, r) + } + sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID }) + return out, nil +} + func readFile(path, lang string) (File, error) { f, err := os.Open(path) if err != nil { diff --git a/site/internal/index/index_test.go b/site/internal/index/index_test.go index dfe9c3e..0da8ef1 100644 --- a/site/internal/index/index_test.go +++ b/site/internal/index/index_test.go @@ -72,6 +72,9 @@ func fixture(t *testing.T) string { write("solved/moocast/notes.md", "union find\n") write("solved/moocast/problem.md", "# Moocast\n") write("solved/moocast/explain.md", "## Key observation\n") + write("solved/moocast/reviews/2026-09-04-090000.md", "\n_Reviewed by m._\n") + write("solved/moocast/reviews/2026-09-04-100000.md", "\n_Reviewed by m._\n") + write("solved/moocast/reviews/notes.md", "hand-written\n") commit(4, "Add a test") return dir } @@ -92,7 +95,20 @@ func TestBuild(t *testing.T) { if m.Statement != "# Moocast\n" || m.Explanation != "## Key observation\n" || !m.HasExplanation { t.Fatalf("moocast statement/explanation = %q / %q", m.Statement, m.Explanation) } - if w := idx.Problems["watermelon"]; w.HasExplanation || w.Statement != "" { + wantReviews := []Review{ + {ID: "notes", Content: "hand-written\n"}, + {ID: "2026-09-04-100000", Verdict: "correct", Audio: "moocast/2026-09-04-100000.mp3", HasAudio: true, Content: "_Reviewed by m._\n"}, + {ID: "2026-09-04-090000", Verdict: "incorrect", Content: "_Reviewed by m._\n"}, + } + if m.ReviewCount != 3 || len(m.Reviews) != 3 { + t.Fatalf("moocast reviews = %+v", m.Reviews) + } + for i, r := range wantReviews { + if m.Reviews[i] != r { + t.Errorf("review %d = %+v, want %+v", i, m.Reviews[i], r) + } + } + if w := idx.Problems["watermelon"]; w.HasExplanation || w.Statement != "" || w.Reviews == nil || w.ReviewCount != 0 { t.Fatal("watermelon has no problem.md or explain.md") } if len(m.Files) != 2 || m.Files[0].Name != "main.cpp" || m.Files[1].Lang != "python" { diff --git a/site/internal/review/review.go b/site/internal/review/review.go new file mode 100644 index 0000000..ac585e6 --- /dev/null +++ b/site/internal/review/review.go @@ -0,0 +1,336 @@ +// Package review turns a recording of the admin explaining their solution, +// already transcribed, into reviews/.md: interview-style feedback on the +// approach (is it right, are the complexities right, what was missed) and on +// the delivery (structure, clarity, pace, fillers), written by Claude. +// +// Claude only reads the transcript. Pace, silences and fillers come from the +// transcriber's timestamps (transcribe.Metrics) and are given to it as +// numbers, and it is told it cannot hear tone, so it does not guess at it. +// +// Like explain.md, the reply is a fixed JSON shape stored as markdown, so it +// reads fine on Gitea and can be edited by hand. +package review + +import ( + "context" + "fmt" + "math" + "sort" + "strings" + "time" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/index" + "adam-french.co.uk/usaco-site/internal/transcribe" +) + +// Input is what Claude is told. +type Input struct { + Name string + Statement string + Examples []explain.Example + Code *index.File // their solution, when they chose to send it + Note string // context from the admin: "mock interview, 20 minutes" + Transcript *transcribe.Transcript + Metrics transcribe.Metrics +} + +// Score is one area of the rubric. +type Score struct { + Score int `json:"score"` + Reason string `json:"reason"` +} + +// Scores are the rubric's areas, in the order they are shown. +type Scores struct { + Understanding Score `json:"understanding"` + Approach Score `json:"approach"` + Correctness Score `json:"correctness"` + Complexity Score `json:"complexity"` + Communication Score `json:"communication"` +} + +// Result is the reply's shape; Schema is the same thing for the API. +type Result struct { + Verdict string `json:"verdict"` + Summary string `json:"summary"` + Approach string `json:"approach"` + Gaps []string `json:"gaps"` + Delivery string `json:"delivery"` + Scores Scores `json:"scores"` + Strengths []string `json:"strengths"` + Improvements []string `json:"improvements"` +} + +// Verdicts, and how they read on the page. +var Verdicts = map[string]string{ + "correct": "Correct", + "partially_correct": "Partly correct", + "incorrect": "Incorrect", + "incomplete": "Incomplete", +} + +func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} } + +func strs(desc string) map[string]any { + return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": desc} +} + +func score(desc string) map[string]any { + return map[string]any{ + "type": "object", + "description": desc, + "properties": map[string]any{ + "score": map[string]any{"type": "integer", "enum": []int{1, 2, 3, 4, 5}}, + "reason": str("One sentence: why this score, specific to what they said."), + }, + "required": []string{"score", "reason"}, + "additionalProperties": false, + } +} + +// Schema constrains the reply to Result. Structured outputs need every +// object closed and every property required. +var Schema = map[string]any{ + "type": "object", + "properties": map[string]any{ + "verdict": map[string]any{"type": "string", "enum": []string{"correct", "partially_correct", "incorrect", "incomplete"}, "description": "Whether the approach they described solves the problem within its constraints. incomplete: they never reached a full approach."}, + "summary": str("Markdown, two or three sentences: the approach they described, restated plainly, so they can check it was understood."), + "approach": str("Markdown. An interviewer's assessment of the approach: whether it is correct and why, whether it fits the constraints, the time and memory complexity they stated against the real ones, and how well they justified it. If it is wrong, say where it breaks, with a small counterexample if there is one, and point toward the right idea without giving a full solution."), + "gaps": strs("Markdown. Edge cases, constraints or errors they missed or got wrong, one per item. Empty if there are none."), + "delivery": str("Markdown. How the explanation came across: its structure (restating the problem, brute force, optimisation, complexity, edge cases, checking an example), clarity and signposting, pace, pauses and filler words. Quote them with [mm:ss] timestamps and refer to the measured metrics."), + "scores": map[string]any{ + "type": "object", + "properties": map[string]any{ + "understanding": score("Did they restate the problem and its constraints correctly, and ask or settle what was ambiguous?"), + "approach": score("How good is the algorithm, and how well did they arrive at it?"), + "correctness": score("Is it right, and did they justify it and check it on an example?"), + "complexity": score("Did they state time and memory complexity, and were they right?"), + "communication": score("Was it structured, clear and easy to follow aloud?"), + }, + "required": []string{"understanding", "approach", "correctness", "complexity", "communication"}, + "additionalProperties": false, + }, + "strengths": strs("Markdown. What they did well, one per item, specific to this recording. Two to four."), + "improvements": strs("Markdown. The most useful things to do differently next time, each concrete enough to act on in the next recording, most important first. Two to five."), + }, + "required": []string{"verdict", "summary", "approach", "gaps", "delivery", "scores", "strengths", "improvements"}, + "additionalProperties": false, +} + +// The reply is a page of prose; the rest is room for adaptive thinking. +const maxTokens = 24000 + +// System is the same on every call, so it is cached. +const System = `You are an experienced technical interviewer coaching someone for coding interviews and competitive programming. They solved a problem on their own, then recorded themselves explaining their solution out loud as they would to an interviewer. You get the problem, an automatic transcript of the recording with timestamps, delivery metrics measured from the audio, and sometimes their code. Give them the feedback a good interviewer would give after a mock interview. + +Reading the transcript: +- It is machine transcription of speech. Technical terms, variable names, numbers and notation are often misheard ("oh of n" for O(n), "a ray" for array). Read charitably and judge what they evidently meant; never criticise spelling, punctuation or grammar. +- You cannot hear the recording. Judge delivery only from the words, the timestamps and the metrics given. Do not guess at tone of voice, confidence or energy. +- Timestamps are [mm:ss]. Cite them when you quote or point at a moment. + +Judging the approach: +- Decide for yourself whether the approach they describe is correct and fast enough for the constraints in the statement. Do not trust their claims, and do not assume that because they solved it their explanation is right: a correct submission can be explained wrongly, and the explanation is what is being assessed. +- Check the complexities they state against the real ones. Notice if they never state them. +- Look for edge cases they did not address: empty or minimal input, duplicates, overflow, disconnected graphs, ties, off-by-ones at the boundaries. +- If code is included, compare what they said with what they wrote, and point out where the two differ. +- If the approach is wrong, say where it breaks and nudge toward the right idea. Never write out a full solution in a real programming language. + +Judging delivery: +- A strong explanation restates the problem, mentions the obvious approach and why it is too slow, builds to the real one with the key insight made explicit, states time and memory complexity, covers edge cases, and checks the idea on an example. Say which of these were missing or came late. +- Comfortable spoken pace is roughly 120 to 160 words per minute. A few pauses to think are normal; long or frequent ones, and long runs of filler words, are worth naming. The filler counts are raw word counts, so "like" may include real uses: look at the transcript before calling it a habit. + +Scores, each 1 to 5: 1 missing or wrong, 2 weak, 3 adequate, 4 good, 5 what a strong candidate would do. Most decent attempts land at 3 or 4; give 5 only when nothing meaningful could be better. + +Be direct and specific. Praise only what earned it, and make every improvement something they could act on in the next recording. Write in plain, direct prose, using markdown for emphasis, lists and inline code.` + +// Prompt is the user message. +func Prompt(in Input) string { + var b strings.Builder + fmt.Fprintf(&b, "\n%s\n\n", in.Name, strings.TrimSpace(in.Statement)) + for i, ex := range in.Examples { + fmt.Fprintf(&b, "\n\n\n%s\n\n", i+1, strings.TrimRight(ex.In, "\n")) + if ex.Out != "" { + fmt.Fprintf(&b, "\n%s\n\n", strings.TrimRight(ex.Out, "\n")) + } + b.WriteString("\n") + } + if in.Code != nil { + fmt.Fprintf(&b, "\n\n%s\n\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n")) + } + if note := strings.TrimSpace(in.Note); note != "" { + fmt.Fprintf(&b, "\n\n%s\n\n", note) + } + b.WriteString("\n\n" + metricsText(in.Metrics) + "\n") + b.WriteString("\n\n" + transcriptText(in.Transcript, "") + "\n") + b.WriteString("\nReview my explanation of this problem.") + return b.String() +} + +// Clock formats seconds as mm:ss, or h:mm:ss past an hour. +func Clock(sec float64) string { + s := int(math.Round(sec)) + if s >= 3600 { + return fmt.Sprintf("%d:%02d:%02d", s/3600, s/60%60, s%60) + } + return fmt.Sprintf("%02d:%02d", s/60, s%60) +} + +// At most this many pauses are listed; the longest are kept. +const maxPauses = 10 + +func metricsText(m transcribe.Metrics) string { + var b strings.Builder + fmt.Fprintf(&b, "- Length %s, %d words, %.0f words per minute\n", Clock(m.Duration), m.Words, m.WPM) + if len(m.Pauses) == 0 { + fmt.Fprintf(&b, "- No pauses of %.0fs or more\n", transcribe.PauseThreshold) + } else { + longest := m.Longest() + fmt.Fprintf(&b, "- %d pauses of %.0fs or more; longest %.1fs at [%s]\n", len(m.Pauses), transcribe.PauseThreshold, longest.Length, Clock(longest.At)) + ps := m.Pauses + if len(ps) > maxPauses { + ps = longestPauses(ps, maxPauses) + } + var at []string + for _, p := range ps { + at = append(at, fmt.Sprintf("[%s] %.1fs", Clock(p.At), p.Length)) + } + b.WriteString("- Pauses: " + strings.Join(at, ", ") + "\n") + } + if m.FillerCount == 0 { + b.WriteString("- No filler words\n") + } else { + var fs []string + for _, f := range m.Fillers { + fs = append(fs, fmt.Sprintf("%q × %d", f.Word, f.Count)) + } + perMin := 0.0 + if m.Duration > 0 { + perMin = float64(m.FillerCount) / (m.Duration / 60) + } + fmt.Fprintf(&b, "- Filler words: %d (%.1f per minute): %s\n", m.FillerCount, perMin, strings.Join(fs, ", ")) + } + if m.ComplexityAt < 0 { + b.WriteString("- Complexity never mentioned by name\n") + } else { + fmt.Fprintf(&b, "- Complexity first mentioned at [%s]\n", Clock(m.ComplexityAt)) + } + return b.String() +} + +// longestPauses keeps the n longest, still in order. +func longestPauses(ps []transcribe.Pause, n int) []transcribe.Pause { + lengths := make([]float64, len(ps)) + for i, p := range ps { + lengths[i] = p.Length + } + sort.Sort(sort.Reverse(sort.Float64Slice(lengths))) + // Ties at the cut keep the earlier ones. + cut := lengths[n-1] + var out []transcribe.Pause + for _, p := range ps { + if len(out) < n && p.Length >= cut { + out = append(out, p) + } + } + return out +} + +// transcriptText is one line per segment, each line starting with prefix +// and its timestamp. +func transcriptText(t *transcribe.Transcript, sep string) string { + var b strings.Builder + if len(t.Segments) == 0 { + return strings.TrimSpace(t.Text) + "\n" + } + for _, s := range t.Segments { + if text := strings.TrimSpace(s.Text); text != "" { + fmt.Fprintf(&b, "[%s] %s\n%s", Clock(s.Start), text, sep) + } + } + return b.String() +} + +// Meta is what the markdown records about how the review was made. +type Meta struct { + Now time.Time + Transcriber string + // Audio is the recording's key in the audio store, or "" if it was not + // kept. + Audio string +} + +// Generate asks Claude and returns the review's markdown. +func Generate(ctx context.Context, a explain.Asker, in Input, meta Meta) (string, error) { + var r Result + err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + if err != nil { + return "", err + } + return Render(r, in, a.Model(), meta), nil +} + +// Render lays a Result out as markdown. The first line is a comment that +// index reads (and strips) for the verdict and the recording; the page folds +// each "## " section away and keeps the line after it visible. +func Render(r Result, in Input, model string, meta Meta) string { + var b strings.Builder + head := "\n") + fmt.Fprintf(&b, "_Reviewed by %s on %s: a %s recording, transcribed by %s._\n", + model, meta.Now.Format("2 January 2006 at 15:04"), Clock(in.Metrics.Duration), meta.Transcriber) + + section := func(title, body string) { + if body = strings.TrimSpace(body); body != "" { + fmt.Fprintf(&b, "\n## %s\n\n%s\n", title, body) + } + } + verdict := Verdicts[r.Verdict] + if verdict == "" { + verdict = r.Verdict + } + section("Verdict", "**"+verdict+".** "+strings.TrimSpace(r.Summary)) + + var sc strings.Builder + sc.WriteString("| Area | Score | Why |\n| --- | --- | --- |\n") + for _, row := range []struct { + name string + s Score + }{ + {"Understanding", r.Scores.Understanding}, + {"Approach", r.Scores.Approach}, + {"Correctness", r.Scores.Correctness}, + {"Complexity", r.Scores.Complexity}, + {"Communication", r.Scores.Communication}, + } { + fmt.Fprintf(&sc, "| %s | %d/5 | %s |\n", row.name, row.s.Score, cell(row.s.Reason)) + } + section("Scores", sc.String()) + section("Approach", r.Approach) + section("Gaps", bullets(r.Gaps)) + section("Delivery", r.Delivery) + section("Strengths", bullets(r.Strengths)) + section("To work on", bullets(r.Improvements)) + section("Metrics", metricsText(in.Metrics)) + section("Transcript", transcriptText(in.Transcript, "\n")) + return b.String() +} + +// cell keeps a table cell on one line and its pipes from splitting it. +func cell(s string) string { + return strings.ReplaceAll(strings.Join(strings.Fields(s), " "), "|", `\|`) +} + +func bullets(items []string) string { + var b strings.Builder + for _, it := range items { + if it = strings.TrimSpace(it); it != "" { + b.WriteString("- " + strings.ReplaceAll(it, "\n", "\n ") + "\n") + } + } + return b.String() +} diff --git a/site/internal/review/review_test.go b/site/internal/review/review_test.go new file mode 100644 index 0000000..5f71aa0 --- /dev/null +++ b/site/internal/review/review_test.go @@ -0,0 +1,179 @@ +package review + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/index" + "adam-french.co.uk/usaco-site/internal/transcribe" +) + +var transcript = &transcribe.Transcript{ + Text: "Um, sort it. Then two pointers.", + Duration: 75, + Segments: []transcribe.Segment{ + {Start: 0, End: 3, Text: " Um, sort it."}, + {Start: 6, End: 9, Text: " Then two pointers. "}, + {Start: 9, End: 9, Text: " "}, + }, +} + +var metrics = transcribe.Metrics{ + Duration: 75, Words: 6, WPM: 4.8, + Pauses: []transcribe.Pause{{At: 3, Length: 3}}, + Fillers: []transcribe.Filler{{Word: "um", Count: 1}}, + FillerCount: 1, ComplexityAt: -1, +} + +func TestPrompt(t *testing.T) { + p := Prompt(Input{ + Name: "two-sum", + Statement: "# Two Sum\n\nFind a pair.", + Examples: []explain.Example{{In: "1 2\n", Out: "3\n"}}, + Code: &index.File{Name: "main.cpp", Content: "int main() {}\n"}, + Note: " mock interview ", + Transcript: transcript, + Metrics: metrics, + }) + for _, want := range []string{ + "\n# Two Sum", + "\n\n1 2\n\n\n3\n", + "\nint main() {}\n", + "\nmock interview\n", + "- Length 01:15, 6 words, 5 words per minute\n", + "- 1 pauses of 2s or more; longest 3.0s at [00:03]\n- Pauses: [00:03] 3.0s\n", + "- Filler words: 1 (0.8 per minute): \"um\" × 1\n", + "- Complexity never mentioned by name\n", + "\n[00:00] Um, sort it.\n[00:06] Then two pointers.\n", + } { + if !strings.Contains(p, want) { + t.Errorf("prompt is missing %q:\n%s", want, p) + } + } + if q := Prompt(Input{Name: "x", Statement: "s", Transcript: &transcribe.Transcript{Text: "hi"}, Metrics: transcribe.Metrics{ComplexityAt: 4}}); strings.Contains(q, "my_code") || strings.Contains(q, "") || + !strings.Contains(q, "\nhi\n") || !strings.Contains(q, "first mentioned at [00:04]") || !strings.Contains(q, "No pauses") { + t.Errorf("minimal prompt:\n%s", q) + } +} + +func TestLongestPausesKeepsOrder(t *testing.T) { + var ps []transcribe.Pause + for i := range 12 { + ps = append(ps, transcribe.Pause{At: float64(i * 10), Length: float64(2 + i%4)}) + } + got := longestPauses(ps, 3) + if len(got) != 3 || got[0].At != 30 || got[1].At != 70 || got[2].At != 110 { + t.Errorf("longest = %+v", got) + } +} + +func TestClock(t *testing.T) { + for sec, want := range map[float64]string{0: "00:00", 59.6: "01:00", 754: "12:34", 3725: "1:02:05"} { + if got := Clock(sec); got != want { + t.Errorf("Clock(%v) = %q, want %q", sec, got, want) + } + } +} + +func TestRender(t *testing.T) { + r := Result{ + Verdict: "partially_correct", + Summary: "Sort, then two pointers.", + Approach: "Right idea; sorting loses the indices.", + Gaps: []string{"Returns values, not indices.", " "}, + Delivery: "Clear, but complexity came late.", + Scores: Scores{ + Understanding: Score{4, "Restated it."}, + Approach: Score{3, "Sorting | hashing\nboth work."}, + Correctness: Score{2, "Indices lost."}, + Complexity: Score{1, "Never stated."}, + Communication: Score{4, "Easy to follow."}, + }, + Strengths: []string{"Named the brute force."}, + Improvements: []string{"State complexity early."}, + } + in := Input{Transcript: transcript, Metrics: metrics} + got := Render(r, in, "claude-opus-5-5", Meta{Now: time.Date(2026, 10, 20, 15, 30, 0, 0, time.UTC), Transcriber: "whisper-1", Audio: "two-sum/2026-10-20-153000.mp3"}) + want := "\n" + + "_Reviewed by claude-opus-5-5 on 20 October 2026 at 15:30: a 01:15 recording, transcribed by whisper-1._\n" + + "\n## Verdict\n\n**Partly correct.** Sort, then two pointers.\n" + + "\n## Scores\n\n| Area | Score | Why |\n| --- | --- | --- |\n" + + "| Understanding | 4/5 | Restated it. |\n" + + "| Approach | 3/5 | Sorting \\| hashing both work. |\n" + + "| Correctness | 2/5 | Indices lost. |\n" + + "| Complexity | 1/5 | Never stated. |\n" + + "| Communication | 4/5 | Easy to follow. |\n" + + "\n## Approach\n\nRight idea; sorting loses the indices.\n" + + "\n## Gaps\n\n- Returns values, not indices.\n" + + "\n## Delivery\n\nClear, but complexity came late.\n" + + "\n## Strengths\n\n- Named the brute force.\n" + + "\n## To work on\n\n- State complexity early.\n" + + "\n## Metrics\n\n- Length 01:15, 6 words, 5 words per minute\n" + + "- 1 pauses of 2s or more; longest 3.0s at [00:03]\n- Pauses: [00:03] 3.0s\n" + + "- Filler words: 1 (0.8 per minute): \"um\" × 1\n- Complexity never mentioned by name\n" + + "\n## Transcript\n\n[00:00] Um, sort it.\n\n[00:06] Then two pointers.\n" + if got != want { + t.Errorf("Render =\n%s\nwant\n%s", got, want) + } + + r.Gaps = nil + if md := Render(r, in, "m", Meta{Now: time.Now(), Transcriber: "w"}); strings.Contains(md, "audio=") || strings.Contains(md, "## Gaps") { + t.Errorf("no audio and no gaps should leave both out:\n%s", md) + } +} + +// The schema must describe exactly Result, or the reply would not decode. +func TestSchemaMatchesResult(t *testing.T) { + props := Schema["properties"].(map[string]any) + b, _ := json.Marshal(Result{}) + var fields map[string]any + json.Unmarshal(b, &fields) + for f := range fields { + if _, ok := props[f]; !ok { + t.Errorf("Result field %q is not in the schema", f) + } + } + if len(props) != len(fields) || len(Schema["required"].([]string)) != len(fields) { + t.Errorf("schema has %d properties (%d required), Result has %d fields", len(props), len(Schema["required"].([]string)), len(fields)) + } + scores := props["scores"].(map[string]any)["properties"].(map[string]any) + b, _ = json.Marshal(Scores{}) + var areas map[string]any + json.Unmarshal(b, &areas) + if len(scores) != len(areas) { + t.Errorf("schema has %d scores, Scores has %d", len(scores), len(areas)) + } + for _, v := range props["verdict"].(map[string]any)["enum"].([]string) { + if Verdicts[v] == "" { + t.Errorf("verdict %q has no label", v) + } + } +} + +type fakeAsker struct{ req claude.Request } + +func (f *fakeAsker) Model() string { return "fake" } +func (f *fakeAsker) JSON(_ context.Context, req claude.Request, out any) error { + f.req = req + *out.(*Result) = Result{Verdict: "correct", Summary: "Hash map."} + return nil +} + +func TestGenerate(t *testing.T) { + a := &fakeAsker{} + md, err := Generate(context.Background(), a, Input{Name: "x", Statement: "s", Transcript: transcript}, Meta{Now: time.Now(), Transcriber: "whisper-1"}) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(md, "\n_Reviewed by fake on") || !strings.Contains(md, "## Verdict\n\n**Correct.** Hash map.") { + t.Errorf("unexpected markdown:\n%s", md) + } + if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil || !strings.Contains(a.req.User, "[00:06] Then two pointers.") { + t.Errorf("request not filled in: %+v", a.req) + } +} diff --git a/site/internal/transcribe/metrics.go b/site/internal/transcribe/metrics.go new file mode 100644 index 0000000..29c00ba --- /dev/null +++ b/site/internal/transcribe/metrics.go @@ -0,0 +1,153 @@ +package transcribe + +import ( + "regexp" + "sort" + "strings" +) + +// PauseThreshold is the silence, in seconds, that counts as a pause: long +// enough to be noticed by an interviewer, short enough to catch hesitation. +const PauseThreshold = 2.0 + +// Pause is a silence starting At seconds in. +type Pause struct { + At, Length float64 +} + +// Filler is one filler word or phrase and how often it was said. +type Filler struct { + Word string + Count int +} + +// Metrics are the delivery numbers Claude cannot get from reading the +// transcript: it never hears the recording, so pace and silence are +// measured here from the timestamps. +type Metrics struct { + Duration float64 + Words int + WPM float64 + Pauses []Pause // chronological + Fillers []Filler + // FillerCount is the sum of Fillers. + FillerCount int + // ComplexityAt is when time or memory complexity was first mentioned, + // or -1 if it never was. + ComplexityAt float64 +} + +// Longest is the longest pause, or the zero Pause. +func (m Metrics) Longest() Pause { + var p Pause + for _, q := range m.Pauses { + if q.Length > p.Length { + p = q + } + } + return p +} + +type token struct { + text string + start, end float64 +} + +var notWord = regexp.MustCompile(`[^a-z0-9'()]+`) + +// tokens are the transcript's words, lowercased and stripped of punctuation. +// A server that gives no word timings gets each word its segment's times, +// which is still enough to place things to within a sentence. +func (t *Transcript) tokens() []token { + var out []token + add := func(raw string, start, end float64) { + for _, f := range strings.Fields(notWord.ReplaceAllString(strings.ToLower(raw), " ")) { + out = append(out, token{f, start, end}) + } + } + if len(t.Words) > 0 { + for _, w := range t.Words { + add(w.Word, w.Start, w.End) + } + return out + } + for _, s := range t.Segments { + add(s.Text, s.Start, s.End) + } + if len(out) == 0 { + add(t.Text, 0, t.Duration) + } + return out +} + +// Whisper spells drawn-out fillers with repeated letters ("ummm", "uhh"). +var fillerShapes = []struct { + re *regexp.Regexp + word string +}{ + {regexp.MustCompile(`^u+h*m+$`), "um"}, + {regexp.MustCompile(`^u+h+$`), "uh"}, + {regexp.MustCompile(`^e+r+m*$`), "er"}, + {regexp.MustCompile(`^h+m+$`), "hmm"}, +} + +// Single words that are usually filler in spoken explanation. "So" and +// "right" are left out: they start too many real sentences to count. +var fillerWords = map[string]bool{"like": true, "basically": true, "actually": true, "literally": true} + +var fillerPhrases = map[string]bool{"you know": true, "kind of": true, "sort of": true, "i mean": true} + +// Metrics measures t. +func (t *Transcript) Metrics() Metrics { + toks := t.tokens() + m := Metrics{Duration: t.Duration, Words: len(toks), ComplexityAt: -1} + if m.Duration > 0 { + m.WPM = float64(m.Words) / (m.Duration / 60) + } + + if len(t.Words) > 0 { + for i := 1; i < len(t.Words); i++ { + if gap := t.Words[i].Start - t.Words[i-1].End; gap >= PauseThreshold { + m.Pauses = append(m.Pauses, Pause{t.Words[i-1].End, gap}) + } + } + } else { + for i := 1; i < len(t.Segments); i++ { + if gap := t.Segments[i].Start - t.Segments[i-1].End; gap >= PauseThreshold { + m.Pauses = append(m.Pauses, Pause{t.Segments[i-1].End, gap}) + } + } + } + + counts := map[string]int{} + for i, tk := range toks { + next := "" + if i+1 < len(toks) { + next = toks[i+1].text + } + for _, f := range fillerShapes { + if f.re.MatchString(tk.text) { + counts[f.word]++ + } + } + if fillerWords[tk.text] { + counts[tk.text]++ + } + if pair := tk.text + " " + next; fillerPhrases[pair] { + counts[pair]++ + } + if m.ComplexityAt < 0 && (tk.text == "complexity" || strings.HasPrefix(tk.text, "o(") || + ((tk.text == "big" || tk.text == "o") && (next == "o" || next == "of"))) { + m.ComplexityAt = tk.start + } + } + for w, n := range counts { + m.Fillers = append(m.Fillers, Filler{w, n}) + m.FillerCount += n + } + sort.Slice(m.Fillers, func(i, j int) bool { + a, b := m.Fillers[i], m.Fillers[j] + return a.Count > b.Count || (a.Count == b.Count && a.Word < b.Word) + }) + return m +} diff --git a/site/internal/transcribe/transcribe.go b/site/internal/transcribe/transcribe.go new file mode 100644 index 0000000..938f6f7 --- /dev/null +++ b/site/internal/transcribe/transcribe.go @@ -0,0 +1,198 @@ +// Package transcribe turns a recording of the admin talking through a +// solution into timed text, for internal/review. +// +// Claude cannot take audio, so this is a second provider: anything that +// speaks OpenAI's /v1/audio/transcriptions, which is the OpenAI API itself +// (whisper-1) and the self-hosted faster-whisper servers. Swapping between +// them is TRANSCRIBE_URL and TRANSCRIBE_MODEL. It is raw HTTP rather than an +// SDK: one multipart POST does not justify a second vendor's client. +// +// Like internal/claude, a missing key switches the feature off, and the +// errors shown to the admin are fixed strings while the detail is logged. +package transcribe + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "strings" + "time" +) + +// Defaults for a blank TRANSCRIBE_URL and TRANSCRIBE_MODEL. +const ( + DefaultURL = "https://api.openai.com" + DefaultModel = "whisper-1" +) + +// MaxBytes is the OpenAI API's upload limit. The handlers refuse anything +// bigger before it is read. +const MaxBytes = 25 << 20 + +// ErrNotConfigured is a server with no transcription key. +var ErrNotConfigured = errors.New("TRANSCRIBE_API_KEY is not set") + +// Failure is a transcription that did not happen. Msg is safe to show the +// admin; Err (logged, never sent) says why. +type Failure struct { + Msg string + Err error +} + +func (f *Failure) Error() string { return f.Msg } +func (f *Failure) Unwrap() error { return f.Err } + +// Word and Segment are timed in seconds from the start of the recording. +type Word struct { + Word string `json:"word"` + Start float64 `json:"start"` + End float64 `json:"end"` +} + +type Segment struct { + Start float64 `json:"start"` + End float64 `json:"end"` + Text string `json:"text"` +} + +// Transcript is the verbose_json reply, less what nothing here uses. +type Transcript struct { + Text string `json:"text"` + Duration float64 `json:"duration"` + Segments []Segment `json:"segments"` + Words []Word `json:"words"` +} + +// Client calls one server with one model. +type Client struct { + url, key, model string + http *http.Client +} + +// New builds a client, or returns ErrNotConfigured for a blank key. +func New(url, key, model string) (*Client, error) { + if key == "" { + return nil, ErrNotConfigured + } + if url == "" { + url = DefaultURL + } + if model == "" { + model = DefaultModel + } + // Transcription runs at a few times real time; a 25 MB recording is + // about half an hour of speech. + return &Client{url: strings.TrimRight(url, "/"), key: key, model: model, http: &http.Client{Timeout: 5 * time.Minute}}, nil +} + +// Model is the model every call uses. +func (c *Client) Model() string { return c.model } + +// Whisper tidies speech into prose unless the prompt shows it the style to +// keep, and the fillers it would drop are half of what the delivery review +// is about. +const verbatimPrompt = "Umm, so, uh, I think, like, we could, you know, sort the array first... hmm, and then, uh, use two pointers." + +// Transcribe sends one recording. filename's extension is how the server +// tells the format. +func (c *Client) Transcribe(ctx context.Context, filename string, audio []byte) (*Transcript, error) { + var body bytes.Buffer + w := multipart.NewWriter(&body) + fields := [][2]string{ + {"model", c.model}, + {"response_format", "verbose_json"}, + {"timestamp_granularities[]", "word"}, + {"timestamp_granularities[]", "segment"}, + {"language", "en"}, + {"prompt", verbatimPrompt}, + } + for _, f := range fields { + if err := w.WriteField(f[0], f[1]); err != nil { + return nil, &Failure{"the recording could not be sent", err} + } + } + part, err := w.CreateFormFile("file", filename) + if err == nil { + _, err = part.Write(audio) + } + if err == nil { + err = w.Close() + } + if err != nil { + return nil, &Failure{"the recording could not be sent", err} + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url+"/v1/audio/transcriptions", &body) + if err != nil { + return nil, &Failure{"the transcription server is misconfigured", err} + } + req.Header.Set("Authorization", "Bearer "+c.key) + req.Header.Set("Content-Type", w.FormDataContentType()) + + resp, err := c.http.Do(req) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + return nil, &Failure{"transcription took too long", err} + } + return nil, &Failure{"could not reach the transcription server", err} + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) + if err != nil { + return nil, &Failure{"the transcript could not be read", err} + } + if resp.StatusCode != http.StatusOK { + return nil, statusFailure(resp.StatusCode, raw) + } + + var t Transcript + if err := json.Unmarshal(raw, &t); err != nil { + return nil, &Failure{"the transcript could not be read", err} + } + if strings.TrimSpace(t.Text) == "" { + return nil, &Failure{"no speech was found in the recording", errors.New("empty transcript")} + } + if t.Duration == 0 { + t.Duration = t.end() + } + return &t, nil +} + +// end is the last timestamp, for servers that leave duration out. +func (t *Transcript) end() float64 { + var end float64 + for _, s := range t.Segments { + end = max(end, s.End) + } + for _, w := range t.Words { + end = max(end, w.End) + } + return end +} + +func statusFailure(status int, raw []byte) error { + var e struct { + Error struct{ Message string } `json:"error"` + } + json.Unmarshal(raw, &e) + err := fmt.Errorf("HTTP %d: %s", status, strings.TrimSpace(e.Error.Message)) + switch { + case status == 401 || status == 403: + return &Failure{"the transcription API key was refused", err} + case status == 413: + return &Failure{"the recording is too big to transcribe", err} + case status == 429: + return &Failure{"transcription is rate limited; try again in a minute", err} + case status >= 500: + return &Failure{"the transcription server is unavailable; try again later", err} + case status == 400: + // Usually a format the server cannot decode. + return &Failure{"the transcription server rejected the recording (is it an audio file?)", err} + } + return &Failure{"the transcription request was rejected", err} +} diff --git a/site/internal/transcribe/transcribe_test.go b/site/internal/transcribe/transcribe_test.go new file mode 100644 index 0000000..25e9b9f --- /dev/null +++ b/site/internal/transcribe/transcribe_test.go @@ -0,0 +1,149 @@ +package transcribe + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const fixture = `{ + "task": "transcribe", "language": "english", "duration": 30.0, + "text": "Um, so I'd sort it. The complexity is O(n log n).", + "segments": [ + {"id": 0, "start": 0.0, "end": 2.0, "text": " Um, so I'd sort it."}, + {"id": 1, "start": 5.0, "end": 8.0, "text": " The complexity is O(n log n)."} + ], + "words": [ + {"word": "Um", "start": 0.0, "end": 0.3}, + {"word": "so", "start": 0.4, "end": 0.6}, + {"word": "I'd", "start": 0.7, "end": 0.9}, + {"word": "sort", "start": 1.0, "end": 1.4}, + {"word": "it", "start": 1.5, "end": 2.0}, + {"word": "The", "start": 5.0, "end": 5.2}, + {"word": "complexity", "start": 5.3, "end": 6.0}, + {"word": "is", "start": 6.1, "end": 6.3}, + {"word": "O(n", "start": 6.4, "end": 7.0}, + {"word": "log", "start": 7.1, "end": 7.5}, + {"word": "n)", "start": 7.6, "end": 8.0} + ] +}` + +func TestTranscribeSendsVerboseJSONRequest(t *testing.T) { + var got struct { + auth, model, format, file, filename string + grains []string + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/audio/transcriptions" { + http.NotFound(w, r) + return + } + got.auth = r.Header.Get("Authorization") + if err := r.ParseMultipartForm(1 << 20); err != nil { + t.Error(err) + } + got.model = r.FormValue("model") + got.format = r.FormValue("response_format") + got.grains = r.MultipartForm.Value["timestamp_granularities[]"] + f, h, err := r.FormFile("file") + if err == nil { + b, _ := io.ReadAll(f) + got.file, got.filename = string(b), h.Filename + } + io.WriteString(w, fixture) + })) + defer srv.Close() + + c, err := New(srv.URL+"/", "k3y", "") + if err != nil { + t.Fatal(err) + } + tr, err := c.Transcribe(context.Background(), "take1.mp3", []byte("ID3fake")) + if err != nil { + t.Fatal(err) + } + if got.auth != "Bearer k3y" || got.model != DefaultModel || got.format != "verbose_json" || + strings.Join(got.grains, ",") != "word,segment" || got.file != "ID3fake" || got.filename != "take1.mp3" { + t.Errorf("request = %+v", got) + } + if tr.Duration != 30 || len(tr.Words) != 11 || len(tr.Segments) != 2 { + t.Errorf("transcript = %+v", tr) + } +} + +func TestTranscribeFailures(t *testing.T) { + if _, err := New("", "", ""); !errors.Is(err, ErrNotConfigured) { + t.Fatalf("blank key: %v", err) + } + for status, want := range map[int]string{401: "key was refused", 429: "rate limited", 400: "rejected the recording", 503: "unavailable"} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + io.WriteString(w, `{"error":{"message":"nope"}}`) + })) + c, _ := New(srv.URL, "k", "") + _, err := c.Transcribe(context.Background(), "a.mp3", []byte("x")) + var f *Failure + if !errors.As(err, &f) || !strings.Contains(f.Msg, want) || !strings.Contains(f.Err.Error(), "nope") { + t.Errorf("HTTP %d: %v, want %q", status, err, want) + } + srv.Close() + } +} + +func TestMetrics(t *testing.T) { + var tr Transcript + if err := json.Unmarshal([]byte(fixture), &tr); err != nil { + t.Fatal(err) + } + m := tr.Metrics() + if m.Words != 11 || m.WPM != 22 { + t.Errorf("words = %d, wpm = %v", m.Words, m.WPM) + } + if len(m.Pauses) != 1 || m.Pauses[0] != (Pause{2, 3}) || m.Longest() != (Pause{2, 3}) { + t.Errorf("pauses = %+v", m.Pauses) + } + if m.FillerCount != 1 || m.Fillers[0] != (Filler{"um", 1}) { + t.Errorf("fillers = %+v", m.Fillers) + } + if m.ComplexityAt != 5.3 { + t.Errorf("complexity at %v, want 5.3", m.ComplexityAt) + } +} + +func TestMetricsWithoutWordTimings(t *testing.T) { + tr := Transcript{ + Duration: 60, + Segments: []Segment{ + {0, 10, "Ummm, you know, it's like a heap, kind of."}, + {10.5, 20, "Uhh, big O of n."}, + {25, 30, "Basically done."}, + }, + } + m := tr.Metrics() + if m.Words != 16 || m.WPM != 16 { + t.Errorf("words = %d, wpm = %v", m.Words, m.WPM) + } + if len(m.Pauses) != 1 || m.Pauses[0] != (Pause{20, 5}) { + t.Errorf("pauses = %+v", m.Pauses) + } + want := map[string]int{"um": 1, "you know": 1, "like": 1, "kind of": 1, "uh": 1, "basically": 1} + if m.FillerCount != 6 || len(m.Fillers) != len(want) { + t.Errorf("fillers = %+v", m.Fillers) + } + for _, f := range m.Fillers { + if want[f.Word] != f.Count { + t.Errorf("filler %q = %d", f.Word, f.Count) + } + } + if m.ComplexityAt != 10.5 { + t.Errorf("complexity at %v, want 10.5", m.ComplexityAt) + } + if quiet := (&Transcript{Text: "hi"}); quiet.Metrics().ComplexityAt != -1 { + t.Error("no mention should be -1") + } +} diff --git a/site/web/src/api.js b/site/web/src/api.js index 619aeca..cb5a087 100644 --- a/site/web/src/api.js +++ b/site/web/src/api.js @@ -1,5 +1,6 @@ /** - * The server's REST API (internal/handlers). Every call goes through + * The server's REST API (internal/handlers). Every call but the audio + * player's goes through * request(), which turns an error response into a thrown Error carrying the * server's message, and sends a refused admin action to the site's login. */ @@ -15,12 +16,14 @@ export class ApiError extends Error { } } +// A FormData body is sent as multipart, with the boundary the browser picks. async function request(method, path, body) { + const form = body instanceof FormData; const res = await fetch(BASE + path, { method, credentials: "same-origin", - headers: body === undefined ? {} : { "Content-Type": "application/json" }, - body: body === undefined ? undefined : JSON.stringify(body), + headers: body === undefined || form ? {} : { "Content-Type": "application/json" }, + body: body === undefined || form ? body : JSON.stringify(body), }); const data = await res.json().catch(() => ({})); if (!res.ok) { @@ -39,3 +42,12 @@ export const fetchStatement = (name, url) => request("GET", `/problems/${encodeURIComponent(name)}/statement/fetch?url=${encodeURIComponent(url || "")}`); export const startExplain = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/explain`, body); export const explainStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/explain`); + +// form: FormData with audio (the file), note and includeCode ("true"). +export const startReview = (name, form) => request("POST", `/problems/${encodeURIComponent(name)}/review`, form); +export const reviewStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/review`); +export const deleteReview = (name, id) => + request("DELETE", `/problems/${encodeURIComponent(name)}/reviews/${encodeURIComponent(id)}`); +// For an