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:
@@ -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
|
||||
}
|
||||
@@ -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, `<?xml version="1.0"?><Error><Code>NoSuchKey</Code><Message>gone</Message></Error>`)
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,9 @@
|
||||
// The layout is the CLI's (README.md at the repo root): solving/, solved/
|
||||
// and skipped/<name>/, each with a solution (main.cpp, sol.py...), an <io>.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/<id>.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/<id>.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(`^<!-- review verdict=(\S+)(?: audio=(\S+))? -->\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 {
|
||||
|
||||
@@ -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", "<!-- review verdict=incorrect -->\n_Reviewed by m._\n")
|
||||
write("solved/moocast/reviews/2026-09-04-100000.md", "<!-- review verdict=correct audio=moocast/2026-09-04-100000.mp3 -->\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" {
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
// Package review turns a recording of the admin explaining their solution,
|
||||
// already transcribed, into reviews/<id>.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, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
|
||||
for i, ex := range in.Examples {
|
||||
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
|
||||
if ex.Out != "" {
|
||||
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
|
||||
}
|
||||
b.WriteString("</example>\n")
|
||||
}
|
||||
if in.Code != nil {
|
||||
fmt.Fprintf(&b, "\n<my_code file=%q>\n%s\n</my_code>\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n"))
|
||||
}
|
||||
if note := strings.TrimSpace(in.Note); note != "" {
|
||||
fmt.Fprintf(&b, "\n<context>\n%s\n</context>\n", note)
|
||||
}
|
||||
b.WriteString("\n<delivery_metrics>\n" + metricsText(in.Metrics) + "</delivery_metrics>\n")
|
||||
b.WriteString("\n<transcript>\n" + transcriptText(in.Transcript, "") + "</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 := "<!-- review verdict=" + r.Verdict
|
||||
if meta.Audio != "" {
|
||||
head += " audio=" + meta.Audio
|
||||
}
|
||||
b.WriteString(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()
|
||||
}
|
||||
@@ -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{
|
||||
"<problem name=\"two-sum\">\n# Two Sum",
|
||||
"<example n=\"1\">\n<input>\n1 2\n</input>\n<output>\n3\n</output>",
|
||||
"<my_code file=\"main.cpp\">\nint main() {}\n</my_code>",
|
||||
"<context>\nmock interview\n</context>",
|
||||
"- 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",
|
||||
"<transcript>\n[00:00] Um, sort it.\n[00:06] Then two pointers.\n</transcript>",
|
||||
} {
|
||||
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, "<context>") ||
|
||||
!strings.Contains(q, "<transcript>\nhi\n</transcript>") || !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 := "<!-- review verdict=partially_correct audio=two-sum/2026-10-20-153000.mp3 -->\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, "<!-- review verdict=correct -->\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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user