|
| 1 | +package transcription |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "strings" |
| 12 | + |
| 13 | + sdk "github.com/memohai/twilight-ai/sdk" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + defaultModelID = "nova-3" |
| 18 | + defaultBaseURL = "https://api.deepgram.com" |
| 19 | +) |
| 20 | + |
| 21 | +type Option func(*Provider) |
| 22 | + |
| 23 | +func WithAPIKey(key string) Option { return func(p *Provider) { p.apiKey = key } } |
| 24 | +func WithBaseURL(baseURL string) Option { |
| 25 | + return func(p *Provider) { p.baseURL = strings.TrimRight(baseURL, "/") } |
| 26 | +} |
| 27 | +func WithHTTPClient(hc *http.Client) Option { return func(p *Provider) { p.httpClient = hc } } |
| 28 | + |
| 29 | +type Provider struct { |
| 30 | + apiKey string |
| 31 | + baseURL string |
| 32 | + httpClient *http.Client |
| 33 | +} |
| 34 | + |
| 35 | +func New(opts ...Option) *Provider { |
| 36 | + p := &Provider{baseURL: defaultBaseURL, httpClient: &http.Client{}} |
| 37 | + for _, opt := range opts { |
| 38 | + opt(p) |
| 39 | + } |
| 40 | + return p |
| 41 | +} |
| 42 | + |
| 43 | +func (p *Provider) TranscriptionModel(id string) *sdk.TranscriptionModel { |
| 44 | + if id == "" { |
| 45 | + id = defaultModelID |
| 46 | + } |
| 47 | + return &sdk.TranscriptionModel{ID: id, Provider: p} |
| 48 | +} |
| 49 | + |
| 50 | +func (p *Provider) ListModels(context.Context) ([]*sdk.TranscriptionModel, error) { |
| 51 | + return nil, fmt.Errorf("deepgram transcription: provider does not expose a remote models discovery API in this SDK") |
| 52 | +} |
| 53 | + |
| 54 | +type audioConfig struct { |
| 55 | + Language string |
| 56 | + SmartFormat bool |
| 57 | + DetectLang bool |
| 58 | + Diarize bool |
| 59 | + Punctuate bool |
| 60 | +} |
| 61 | + |
| 62 | +func parseConfig(cfg map[string]any) audioConfig { |
| 63 | + ac := audioConfig{SmartFormat: true, Punctuate: true} |
| 64 | + if cfg == nil { |
| 65 | + return ac |
| 66 | + } |
| 67 | + if v, ok := cfg["language"].(string); ok && v != "" { |
| 68 | + ac.Language = v |
| 69 | + } |
| 70 | + if v, ok := cfg["smart_format"].(bool); ok { |
| 71 | + ac.SmartFormat = v |
| 72 | + } |
| 73 | + if v, ok := cfg["detect_language"].(bool); ok { |
| 74 | + ac.DetectLang = v |
| 75 | + } |
| 76 | + if v, ok := cfg["diarize"].(bool); ok { |
| 77 | + ac.Diarize = v |
| 78 | + } |
| 79 | + if v, ok := cfg["punctuate"].(bool); ok { |
| 80 | + ac.Punctuate = v |
| 81 | + } |
| 82 | + return ac |
| 83 | +} |
| 84 | + |
| 85 | +func (p *Provider) DoTranscribe(ctx context.Context, params sdk.TranscriptionParams) (*sdk.TranscriptionResult, error) { |
| 86 | + cfg := parseConfig(params.Config) |
| 87 | + modelID := defaultModelID |
| 88 | + if params.Model != nil && params.Model.ID != "" { |
| 89 | + modelID = params.Model.ID |
| 90 | + } |
| 91 | + |
| 92 | + u, err := url.Parse(p.baseURL + "/v1/listen") |
| 93 | + if err != nil { |
| 94 | + return nil, fmt.Errorf("deepgram transcription: parse URL: %w", err) |
| 95 | + } |
| 96 | + q := u.Query() |
| 97 | + q.Set("model", modelID) |
| 98 | + if cfg.Language != "" { |
| 99 | + q.Set("language", cfg.Language) |
| 100 | + } |
| 101 | + if cfg.SmartFormat { |
| 102 | + q.Set("smart_format", "true") |
| 103 | + } |
| 104 | + if cfg.DetectLang { |
| 105 | + q.Set("detect_language", "true") |
| 106 | + } |
| 107 | + if cfg.Diarize { |
| 108 | + q.Set("diarize", "true") |
| 109 | + } |
| 110 | + if cfg.Punctuate { |
| 111 | + q.Set("punctuate", "true") |
| 112 | + } |
| 113 | + u.RawQuery = q.Encode() |
| 114 | + |
| 115 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(params.Audio)) |
| 116 | + if err != nil { |
| 117 | + return nil, fmt.Errorf("deepgram transcription: build request: %w", err) |
| 118 | + } |
| 119 | + if params.ContentType != "" { |
| 120 | + req.Header.Set("Content-Type", params.ContentType) |
| 121 | + } else { |
| 122 | + req.Header.Set("Content-Type", "audio/wav") |
| 123 | + } |
| 124 | + req.Header.Set("Authorization", "Token "+p.apiKey) |
| 125 | + |
| 126 | + resp, err := p.httpClient.Do(req) |
| 127 | + if err != nil { |
| 128 | + return nil, fmt.Errorf("deepgram transcription: request failed: %w", err) |
| 129 | + } |
| 130 | + defer resp.Body.Close() |
| 131 | + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 132 | + body, _ := io.ReadAll(resp.Body) |
| 133 | + return nil, fmt.Errorf("deepgram transcription: unexpected status %d: %s", resp.StatusCode, string(body)) |
| 134 | + } |
| 135 | + |
| 136 | + var payload struct { |
| 137 | + Results struct { |
| 138 | + Channels []struct { |
| 139 | + DetectedLanguage string `json:"detected_language"` |
| 140 | + Alternatives []struct { |
| 141 | + Transcript string `json:"transcript"` |
| 142 | + Words []struct { |
| 143 | + Word string `json:"word"` |
| 144 | + Start float64 `json:"start"` |
| 145 | + End float64 `json:"end"` |
| 146 | + Speaker int `json:"speaker"` |
| 147 | + } `json:"words"` |
| 148 | + } `json:"alternatives"` |
| 149 | + } `json:"channels"` |
| 150 | + } `json:"results"` |
| 151 | + Metadata struct { |
| 152 | + Duration float64 `json:"duration"` |
| 153 | + } `json:"metadata"` |
| 154 | + } |
| 155 | + if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { |
| 156 | + return nil, fmt.Errorf("deepgram transcription: decode response: %w", err) |
| 157 | + } |
| 158 | + if len(payload.Results.Channels) == 0 || len(payload.Results.Channels[0].Alternatives) == 0 { |
| 159 | + return nil, fmt.Errorf("deepgram transcription: empty transcript in response") |
| 160 | + } |
| 161 | + alt := payload.Results.Channels[0].Alternatives[0] |
| 162 | + out := &sdk.TranscriptionResult{ |
| 163 | + Text: alt.Transcript, |
| 164 | + Language: payload.Results.Channels[0].DetectedLanguage, |
| 165 | + DurationSeconds: payload.Metadata.Duration, |
| 166 | + } |
| 167 | + if len(alt.Words) > 0 { |
| 168 | + out.Words = make([]sdk.TranscriptionWord, 0, len(alt.Words)) |
| 169 | + for _, w := range alt.Words { |
| 170 | + out.Words = append(out.Words, sdk.TranscriptionWord{ |
| 171 | + Text: w.Word, |
| 172 | + Start: w.Start, |
| 173 | + End: w.End, |
| 174 | + SpeakerID: fmt.Sprintf("speaker_%d", w.Speaker), |
| 175 | + }) |
| 176 | + } |
| 177 | + } |
| 178 | + return out, nil |
| 179 | +} |
0 commit comments