Files
usaco/site/internal/handlers/explain.go
T
adamfandClaude Opus 5.5 63608f130c
Test and publish the site / test (push) Successful in 2m4s
Test and publish the site / publish (push) Successful in 1m44s
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/<id>.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 <[email protected]>
2026-10-20 01:56:55 +01:00

241 lines
7.2 KiB
Go

package handlers
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
"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/repo"
"adam-french.co.uk/usaco-site/internal/statement"
)
// Fetcher is the part of statement.Fetcher the handlers use, so tests can
// fake the judges.
type Fetcher interface {
Fetch(ctx context.Context, link string) (string, error)
}
func (s *Server) fetcher() Fetcher {
if s.Statements != nil {
return s.Statements
}
return &statement.Fetcher{}
}
// fetchStatement returns the statement behind ?url= (or the saved link) for
// the admin to review in the editor. It saves nothing.
func (s *Server) fetchStatement(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
link := strings.TrimSpace(ctx.Query("url"))
if link == "" {
link = p.URL
}
if u, err := url.Parse(link); link == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "give the problem an http(s) link first"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), 20*time.Second)
defer cancel()
md, err := s.fetcher().Fetch(c, link)
switch {
case errors.Is(err, statement.ErrUnsupported):
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
case err != nil:
log.Printf("[statement] %s: %v", link, err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
default:
ctx.JSON(http.StatusOK, gin.H{"statement": md})
}
}
type explainBody struct {
Note string `json:"note"`
IncludeCode bool `json:"includeCode"`
}
const maxNote = 4 << 10
// Claude can take a few minutes at high effort; this also bounds the
// commit that follows.
const explainTimeout = 10 * time.Minute
// startExplain starts writing explain.md and answers at once; the page polls
// explainStatus. Everything Claude sees is taken from the index now, so a
// sync during the call changes nothing but where the result is committed.
func (s *Server) startExplain(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
}
var body explainBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
if len(body.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 := explain.Input{Name: p.Name, Statement: p.Statement, Note: body.Note, Examples: examples(p)}
if body.IncludeCode {
in.Code = mainFile(p)
}
link := p.URL
if !s.jobs.Start(p.Name, func() error { return s.explain(in, link) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "an explanation is already being written"})
return
}
ctx.JSON(http.StatusAccepted, s.jobs.Get(p.Name))
}
func (s *Server) explainStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.jobs.Get(p.Name))
}
}
// explain 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) explain(in explain.Input, link string) error {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
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())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err)
return f
}
log.Printf("[explain] %s: %v", in.Name, err)
return errors.New("the explanation could not be written")
}
name := in.Name
err = s.Repo.Mutate(ctx, "Explain "+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
}
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:
return nil
case errors.As(err, &re):
return errors.New(re.msg)
case errors.Is(err, repo.ErrRejected):
return errors.New("the repository changed while saving; try again")
default:
log.Printf("[%s] %s: saving: %v", tag, name, err)
return errors.New(unsaved)
}
}
// mainFile is the CLI's solution (main.cpp, main.rs...), else the first
// solution file.
func mainFile(p *index.Problem) *index.File {
for i := range p.Files {
if strings.HasPrefix(p.Files[i].Name, "main.") {
return &p.Files[i]
}
}
if len(p.Files) > 0 {
return &p.Files[0]
}
return nil
}
// A case bigger than this is a stress test, not something to trace by hand,
// and a truncated one would mislead.
const maxExample = 2 << 10
// examples are the saved tests that have an expected output, then the
// sample input if no test has the same input. Three is plenty to trace.
func examples(p *index.Problem) []explain.Example {
var out []explain.Example
seen := map[string]bool{}
for _, t := range p.TestSet {
if len(out) == 3 {
return out
}
if t.Output == nil || t.Input.Truncated || len(t.Input.Content) > maxExample || len(t.Output.Content) > maxExample {
continue
}
out = append(out, explain.Example{In: t.Input.Content, Out: t.Output.Content})
seen[strings.TrimSpace(t.Input.Content)] = true
}
if sm := p.Sample; sm != nil && len(out) < 3 && len(sm.Content) <= maxExample && !seen[strings.TrimSpace(sm.Content)] {
out = append(out, explain.Example{In: sm.Content})
}
return out
}