// 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} }