Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions internal/api/handler/paid_ai.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ var unmeteredFeatureNames = map[string]string{
"/api/v1/me/profile/ats-report": "ats_review",
"/api/v1/me/tracking/:slug/mail-recall": "mail_recall",
"/api/v1/me/autofill/run": "autofill",
"/api/v1/me/interviews/transcriptions": "interview_transcription",
}

// unknownPaywallFeature labels a refusal on an unmetered route missing from the table above.
Expand Down
1 change: 1 addition & 0 deletions internal/api/handler/paid_ai_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ var gatedRoutes = []gatedRoute{
{fiber.MethodPost, "/api/v1/me/cvs/00000000-0000-0000-0000-000000000001/cover-letter", plan.FeatureCoverLetter},
{fiber.MethodPost, "/api/v1/me/cvs/00000000-0000-0000-0000-000000000001/cover-letter/stream", plan.FeatureCoverLetter},
{fiber.MethodPost, "/api/v1/speech/transcriptions", plan.FeatureDictation},
{fiber.MethodPost, "/api/v1/me/interviews/transcriptions", unmeteredAI},
{fiber.MethodPost, "/api/v1/me/profile/ats-report", unmeteredAI},
{fiber.MethodPost, "/api/v1/me/tracking/some-job/mail-recall", unmeteredAI},
{fiber.MethodPost, "/api/v1/me/emails/4821/reply-draft", plan.FeatureMailReply},
Expand Down
2 changes: 2 additions & 0 deletions internal/api/handler/paywall_hit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ func paywallHitFor(r gatedRoute) wantPaywallHit {
feature, job = "mail_recall", plan.PaywallJob{Slug: "some-job"}
case r.path == "/api/v1/me/autofill/run":
feature = "autofill"
case r.path == "/api/v1/me/interviews/transcriptions":
feature = "interview_transcription"
case strings.Contains(r.path, "/assistant/sessions/"):
job = plan.PaywallJob{SessionID: cvUUID}
case strings.Contains(r.path, "/me/cvs/"+testUUID):
Expand Down
3 changes: 2 additions & 1 deletion internal/api/handler/speech.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type transcriber interface {
Transcribe(ctx context.Context, audio []byte, filename string) (string, error)
}

// speechHandlers serve dictation: one recording in, its text out. There is no
// speechHandlers serve dictation and interview transcription. There is no
// storage and no state — the audio is read, forwarded, and dropped.
type speechHandlers struct {
// stt is nil where no speech gateway is configured, and every request then
Expand All @@ -40,6 +40,7 @@ func (h *speechHandlers) register(api fiber.Router, mw middleware) {
// composer that posts messages, so a client allowed to send one may transcribe for it (a
// narrower rule would leave the control dead in the extension's side panel).
api.Post("/speech/transcriptions", mw.key, mw.paidAI(plan.FeatureDictation), h.PostTranscription)
api.Post("/me/interviews/transcriptions", mw.key, mw.paidAI(unmeteredAI), interviewTranscriptionLimit(), h.postInterviewTranscription)
}

// maxAudioUpload bounds one recording: around eight minutes at the ~32 kbit/s the
Expand Down
82 changes: 82 additions & 0 deletions internal/api/handler/speech_interview.go
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 {
Comment thread
strelov1 marked this conversation as resolved.
Resolved
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) &&

Check failure on line 71 in internal/api/handler/speech_interview.go

View workflow job for this annotation

GitHub Actions / backend-checks

G115: integer overflow conversion int -> uint32 (gosec)
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)
}
92 changes: 92 additions & 0 deletions internal/api/handler/speech_interview_test.go
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"

Check failure on line 17 in internal/api/handler/speech_interview_test.go

View workflow job for this annotation

GitHub Actions / backend-checks

G101: Potential hardcoded credentials (gosec)
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},
Comment thread
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)

Check failure on line 39 in internal/api/handler/speech_interview_test.go

View workflow job for this annotation

GitHub Actions / backend-checks

net/http/httptest.NewRequest must not be called. use net/http/httptest.NewRequestWithContext (noctx)
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))

Check failure on line 80 in internal/api/handler/speech_interview_test.go

View workflow job for this annotation

GitHub Actions / backend-checks

G115: integer overflow conversion int -> uint32 (gosec)
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))

Check failure on line 90 in internal/api/handler/speech_interview_test.go

View workflow job for this annotation

GitHub Actions / backend-checks

G115: integer overflow conversion int -> uint32 (gosec)
return audio
}
25 changes: 13 additions & 12 deletions internal/engage/cvlifecycle/paywall.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,22 @@ type attempt struct {
}

// attempts is keyed by the label the paid-AI gate records: a plan feature for a metered
// route, a fixed name for the three that draw on no allowance (see handler.paid_ai.go). A
// route, a fixed name for routes that draw on no allowance (see handler.paid_ai.go). A
// label missing here still gets a letter, with fallbackAttempt, so a route added to the gate
// before its words are written here is never a silent hole.
var attempts = map[string]attempt{
"tailor": {"tailor your CV", "tailor your CV for %s"},
"match": {"see how well you fit a posting", "see how well you fit %s"},
"assistant": {"talk to the AI assistant", "talk through %s with the AI assistant"},
"dictation": {"dictate to the AI assistant", ""},
"cover-letter": {"draft a cover letter", "draft a cover letter for %s"},
"auto-apply": {"apply with auto-apply", "apply to %s with auto-apply"},
"mail-reply": {"draft a reply to a recruiter's email", ""},
"recruiter-contact": {"see who recruits at a company", "see who recruits for %s"},
"ats_review": {"get the AI review of your CV", ""},
"mail_recall": {"pull the emails about an application into your tracker", "pull the emails about %s into your tracker"},
"autofill": {"have the agent fill in an application form", "have the agent fill in the application for %s"},
"tailor": {"tailor your CV", "tailor your CV for %s"},
"match": {"see how well you fit a posting", "see how well you fit %s"},
"assistant": {"talk to the AI assistant", "talk through %s with the AI assistant"},
"dictation": {"dictate to the AI assistant", ""},
"cover-letter": {"draft a cover letter", "draft a cover letter for %s"},
"auto-apply": {"apply with auto-apply", "apply to %s with auto-apply"},
"mail-reply": {"draft a reply to a recruiter's email", ""},
"recruiter-contact": {"see who recruits at a company", "see who recruits for %s"},
"ats_review": {"get the AI review of your CV", ""},
"mail_recall": {"pull the emails about an application into your tracker", "pull the emails about %s into your tracker"},
"autofill": {"have the agent fill in an application form", "have the agent fill in the application for %s"},
"interview_transcription": {"transcribe an interview recording", ""},
}

var fallbackAttempt = attempt{generic: "use one of the AI features"}
Expand Down
2 changes: 1 addition & 1 deletion internal/engage/cvlifecycle/paywall_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestPaywallLetter_WithoutAPostingNamesOnlyTheFeature(t *testing.T) {
}

func TestPaywallLetter_EveryGateLabelHasWordsAndAnUnknownOneStillGetsALetter(t *testing.T) {
labels := []string{"tailor", "match", "assistant", "dictation", "cover-letter", "auto-apply", "ats_review", "mail_recall", "autofill"}
labels := []string{"tailor", "match", "assistant", "dictation", "cover-letter", "auto-apply", "ats_review", "mail_recall", "autofill", "interview_transcription"}
seen := map[string]bool{}
for _, label := range labels {
if _, ok := attempts[label]; !ok {
Expand Down
Loading