Repository navigation
fix(interviews): enable desktop transcription #5034
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+260
−14
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/binary" | ||
| "strconv" | ||
| "time" | ||
|
|
||
| "github.com/gofiber/fiber/v2" | ||
| "github.com/gofiber/fiber/v2/middleware/limiter" | ||
|
|
||
| "github.com/strelov1/freehire/internal/identity/auth" | ||
| ) | ||
|
|
||
| // The desktop client sends successive WAV segments. Bound their total cost per | ||
| // account independently of the daily allowance for short composer dictations. | ||
| func interviewTranscriptionLimit() fiber.Handler { | ||
| return limiter.New(limiter.Config{ | ||
| Max: 120, | ||
| Expiration: time.Hour, | ||
| KeyGenerator: func(c *fiber.Ctx) string { | ||
| userID, _ := auth.UserID(c) | ||
| return strconv.FormatInt(userID, 10) | ||
| }, | ||
| LimitReached: func(_ *fiber.Ctx) error { | ||
| return fiber.NewError(fiber.StatusTooManyRequests, "interview transcription limit reached") | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| func (h *speechHandlers) postInterviewTranscription(c *fiber.Ctx) error { | ||
| if h.stt == nil { | ||
| return fiber.NewError(fiber.StatusNotImplemented, "transcription is not configured") | ||
| } | ||
| if err := requirePaidCall(c.UserContext()); err != nil { | ||
| return err | ||
| } | ||
| if err := refuseEncodedBody(c); err != nil { | ||
| return err | ||
| } | ||
| audio, filename, err := readAudioUpload(c) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if filename != "dictation.wav" || !validInterviewAudio(audio) { | ||
| return fiber.NewError(fiber.StatusBadRequest, "expected up to 60 seconds of mono 16 kHz PCM WAV") | ||
| } | ||
| text, err := h.stt.Transcribe(c.Context(), audio, filename) | ||
| if err != nil { | ||
| return fiber.NewError(fiber.StatusBadGateway, "transcription failed") | ||
| } | ||
| c.Set(fiber.HeaderCacheControl, "private, no-store") | ||
| return c.JSON(fiber.Map{"data": fiber.Map{"text": text}}) | ||
| } | ||
|
|
||
| // The desktop client writes a canonical PCM WAV header. Checking the actual | ||
| // sample bytes bounds inference time even if the header overstates its length. | ||
| func validInterviewAudio(audio []byte) bool { | ||
| const ( | ||
| headerBytes = 44 | ||
| sampleRate = 16000 | ||
| bytesPerSample = 2 | ||
| bytesPerSecond = sampleRate * bytesPerSample | ||
| segmentSeconds = 60 | ||
| ) | ||
| size := len(audio) - headerBytes | ||
| if size <= 0 || size > segmentSeconds*bytesPerSecond || size%bytesPerSample != 0 { | ||
| return false | ||
| } | ||
| return bytes.Equal(audio[:4], []byte("RIFF")) && | ||
| binary.LittleEndian.Uint32(audio[4:]) == uint32(len(audio)-8) && | ||
| bytes.Equal(audio[8:16], []byte("WAVEfmt ")) && | ||
| binary.LittleEndian.Uint32(audio[16:]) == 16 && | ||
| binary.LittleEndian.Uint16(audio[20:]) == 1 && | ||
| binary.LittleEndian.Uint16(audio[22:]) == 1 && | ||
| binary.LittleEndian.Uint32(audio[24:]) == sampleRate && | ||
| binary.LittleEndian.Uint32(audio[28:]) == bytesPerSecond && | ||
| binary.LittleEndian.Uint16(audio[32:]) == bytesPerSample && | ||
| binary.LittleEndian.Uint16(audio[34:]) == 8*bytesPerSample && | ||
| bytes.Equal(audio[36:40], []byte("data")) && | ||
| binary.LittleEndian.Uint32(audio[40:]) == uint32(size) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/binary" | ||
| "encoding/json" | ||
| "net/http/httptest" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/gofiber/fiber/v2" | ||
|
|
||
| "github.com/strelov1/freehire/internal/identity/auth" | ||
| ) | ||
|
|
||
| func TestInterviewTranscription(t *testing.T) { | ||
| const apiKey = "fhk_test-key" | ||
| issuer := auth.NewIssuer("test-secret", time.Hour) | ||
| gateway := &fakeTranscriber{text: "the interview transcript"} | ||
| app := fiber.New(fiber.Config{ErrorHandler: RenderError}) | ||
| newSpeechHandlers(gateway, nil).register(app.Group("/api/v1"), middleware{ | ||
| key: auth.RequireAuthOrKey(issuer, testVersions, stubValidKey{hash: auth.HashAPIKey(apiKey), userID: 7}), | ||
| paidAI: markPaidAI, | ||
| }) | ||
|
|
||
| for _, tt := range []struct { | ||
| name string | ||
| audio []byte | ||
| key bool | ||
| want int | ||
| }{ | ||
| {"anonymous", interviewTestWAV(32000), false, fiber.StatusUnauthorized}, | ||
| {"malformed", []byte("not a WAV"), true, fiber.StatusBadRequest}, | ||
|
strelov1 marked this conversation as resolved.
Resolved
|
||
| {"over 60 seconds", interviewTestWAV(60*32000 + 2), true, fiber.StatusBadRequest}, | ||
| {"60 seconds", interviewTestWAV(60 * 32000), true, fiber.StatusOK}, | ||
| } { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| body, contentType := audioUpload(t, tt.audio, "interview.wav") | ||
| req := httptest.NewRequest(fiber.MethodPost, "/api/v1/me/interviews/transcriptions", body) | ||
| req.Header.Set(fiber.HeaderContentType, contentType) | ||
| if tt.key { | ||
| req.Header.Set(fiber.HeaderAuthorization, "Bearer "+apiKey) | ||
| } | ||
| before := gateway.calls | ||
| res, err := app.Test(req, 5000) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer res.Body.Close() | ||
| if res.StatusCode != tt.want { | ||
| t.Fatalf("status = %d, want %d", res.StatusCode, tt.want) | ||
| } | ||
| if tt.want != fiber.StatusOK { | ||
| if gateway.calls != before { | ||
| t.Fatal("rejected audio reached the inference gateway") | ||
| } | ||
| return | ||
| } | ||
| var result struct { | ||
| Data struct { | ||
| Text string `json:"text"` | ||
| } `json:"data"` | ||
| } | ||
| if err := json.NewDecoder(res.Body).Decode(&result); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if result.Data.Text != gateway.text || res.Header.Get(fiber.HeaderCacheControl) != "private, no-store" { | ||
| t.Fatalf("text = %q, cache control = %q", result.Data.Text, res.Header.Get(fiber.HeaderCacheControl)) | ||
| } | ||
| if gateway.calls != before+1 || gateway.filename != "dictation.wav" || !bytes.Equal(gateway.audio, tt.audio) { | ||
| t.Fatal("gateway did not receive the WAV with its sanitized filename") | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func interviewTestWAV(sampleBytes int) []byte { | ||
| audio := make([]byte, 44+sampleBytes) | ||
| copy(audio, "RIFF") | ||
| binary.LittleEndian.PutUint32(audio[4:], uint32(len(audio)-8)) | ||
| copy(audio[8:], "WAVEfmt ") | ||
| binary.LittleEndian.PutUint32(audio[16:], 16) | ||
| binary.LittleEndian.PutUint16(audio[20:], 1) | ||
| binary.LittleEndian.PutUint16(audio[22:], 1) | ||
| binary.LittleEndian.PutUint32(audio[24:], 16000) | ||
| binary.LittleEndian.PutUint32(audio[28:], 32000) | ||
| binary.LittleEndian.PutUint16(audio[32:], 2) | ||
| binary.LittleEndian.PutUint16(audio[34:], 16) | ||
| copy(audio[36:], "data") | ||
| binary.LittleEndian.PutUint32(audio[40:], uint32(sampleBytes)) | ||
| return audio | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.