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]>
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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", "<context>\nmock interview", "<my_code file=\"main.cpp\">", "[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, "<!-- review verdict=correct -->\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())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user