-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamazon_transcribe_handler.go
295 lines (243 loc) · 7.43 KB
/
amazon_transcribe_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package suzu
import (
"context"
"encoding/json"
"errors"
"io"
"strings"
"sync"
"github.com/aws/aws-sdk-go/service/transcribestreamingservice"
zlog "github.com/rs/zerolog/log"
)
func init() {
NewServiceHandlerFuncs.register("aws", NewAmazonTranscribeHandler)
}
type AmazonTranscribeHandler struct {
Config Config
ChannelID string
ConnectionID string
SampleRate uint32
ChannelCount uint16
LanguageCode string
RetryCount int
mu sync.Mutex
OnResultFunc func(context.Context, io.WriteCloser, string, string, string, any) error
}
func NewAmazonTranscribeHandler(config Config, channelID, connectionID string, sampleRate uint32, channelCount uint16, languageCode string, onResultFunc any) serviceHandlerInterface {
return &AmazonTranscribeHandler{
Config: config,
ChannelID: channelID,
ConnectionID: connectionID,
SampleRate: sampleRate,
ChannelCount: channelCount,
LanguageCode: languageCode,
RetryCount: 0,
OnResultFunc: onResultFunc.(func(context.Context, io.WriteCloser, string, string, string, any) error),
}
}
type AwsResult struct {
ChannelID *string `json:"channel_id,omitempty"`
IsPartial *bool `json:"is_partial,omitempty"`
ResultID *string `json:"result_id,omitempty"`
TranscriptionResult
}
func NewAwsResult() AwsResult {
return AwsResult{
TranscriptionResult: TranscriptionResult{
Type: "aws",
},
}
}
func (ar *AwsResult) WithChannelID(channelID string) *AwsResult {
ar.ChannelID = &channelID
return ar
}
func (ar *AwsResult) WithIsPartial(isPartial bool) *AwsResult {
ar.IsPartial = &isPartial
return ar
}
func (ar *AwsResult) WithResultID(resultID string) *AwsResult {
ar.ResultID = &resultID
return ar
}
func (ar *AwsResult) SetMessage(message string) *AwsResult {
ar.Message = message
return ar
}
func (h *AmazonTranscribeHandler) UpdateRetryCount() int {
defer h.mu.Unlock()
h.mu.Lock()
h.RetryCount++
return h.RetryCount
}
func (h *AmazonTranscribeHandler) GetRetryCount() int {
return h.RetryCount
}
func (h *AmazonTranscribeHandler) ResetRetryCount() int {
defer h.mu.Unlock()
h.mu.Lock()
h.RetryCount = 0
return h.RetryCount
}
func (h *AmazonTranscribeHandler) Handle(ctx context.Context, opusCh chan opusChannel, header soraHeader) (*io.PipeReader, error) {
at := NewAmazonTranscribe(h.Config, h.LanguageCode, int64(h.SampleRate), int64(h.ChannelCount))
packetReader, err := opus2ogg(ctx, opusCh, h.SampleRate, h.ChannelCount, h.Config, header)
if err != nil {
return nil, err
}
stream, err := at.Start(ctx, packetReader)
if err != nil {
return nil, err
}
// リクエストが成功した時点でリトライカウントをリセットする
h.ResetRetryCount()
r, w := io.Pipe()
go func() {
encoder := json.NewEncoder(w)
L:
for {
select {
case <-ctx.Done():
break L
case event := <-stream.Events():
switch e := event.(type) {
case *transcribestreamingservice.TranscriptEvent:
if h.OnResultFunc != nil {
if err := h.OnResultFunc(ctx, w, h.ChannelID, h.ConnectionID, h.LanguageCode, e.Transcript.Results); err != nil {
if err := encoder.Encode(NewSuzuErrorResponse(err)); err != nil {
zlog.Error().
Err(err).
Str("channel_id", h.ChannelID).
Str("connection_id", h.ConnectionID).
Send()
}
w.CloseWithError(err)
return
}
} else {
for _, res := range e.Transcript.Results {
if at.Config.FinalResultOnly {
// IsPartial: true の場合は結果を返さない
if *res.IsPartial {
continue
}
}
result := NewAwsResult()
if at.Config.AwsResultIsPartial {
result.WithIsPartial(*res.IsPartial)
}
if at.Config.AwsResultChannelID {
result.WithChannelID(*res.ChannelId)
}
if at.Config.AwsResultID {
result.WithResultID(*res.ResultId)
}
for _, alt := range res.Alternatives {
message, ok := buildMessage(at.Config, *alt, *res.IsPartial)
if !ok {
continue
}
result.SetMessage(message)
if err := encoder.Encode(result); err != nil {
w.CloseWithError(err)
return
}
}
}
}
default:
break L
}
}
}
if err := stream.Err(); err != nil {
zlog.Error().
Err(err).
Str("channel_id", h.ChannelID).
Str("connection_id", h.ConnectionID).
Int("retry_count", h.GetRetryCount()).
Send()
// 復帰が不可能なエラー以外は再接続を試みる
switch err.(type) {
case *transcribestreamingservice.LimitExceededException,
*transcribestreamingservice.InternalFailureException:
err = errors.Join(err, ErrServerDisconnected)
default:
// サーバから切断された場合は再接続を試みる
if strings.Contains(err.Error(), "http2: server sent GOAWAY and closed the connection;") {
err = errors.Join(err, ErrServerDisconnected)
}
}
w.CloseWithError(err)
return
}
w.Close()
}()
return r, nil
}
func contentFilterByTranscribedTime(config Config, item transcribestreamingservice.Item) bool {
minimumTranscribedTime := config.MinimumTranscribedTime
// minimumTranscribedTime が設定されていない場合はフィルタリングしない
if minimumTranscribedTime <= 0 {
return true
}
// 句読点の場合はフィルタリングしない
if *item.Type == transcribestreamingservice.ItemTypePunctuation {
return true
}
// StartTime または EndTime が nil の場合はフィルタリングしない
if (item.StartTime == nil) || (item.EndTime == nil) {
return true
}
// 発話時間が minimumTranscribedTime 未満の場合はフィルタリングする
return (*item.EndTime - *item.StartTime) >= minimumTranscribedTime
}
func contentFilterByConfidenceScore(config Config, item transcribestreamingservice.Item, isPartial bool) bool {
minimumConfidenceScore := config.MinimumConfidenceScore
// minimumConfidenceScore が設定されていない場合はフィルタリングしない
if minimumConfidenceScore <= 0 {
return true
}
// isPartial が true の場合はフィルタリングしない
if isPartial {
return true
}
// 句読点の場合はフィルタリングしない
if *item.Type == transcribestreamingservice.ItemTypePunctuation {
return true
}
// Confidence が nil の場合はフィルタリングしない
if item.Confidence == nil {
return true
}
// 信頼スコアが minimumConfidenceScore 未満の場合はフィルタリングする
return *item.Confidence >= minimumConfidenceScore
}
func buildMessage(config Config, alt transcribestreamingservice.Alternative, isPartial bool) (string, bool) {
var message string
minimumTranscribedTime := config.MinimumTranscribedTime
minimumConfidenceScore := config.MinimumConfidenceScore
// 両方無効の場合には全てのメッセージを返す
if (minimumTranscribedTime <= 0) && (minimumConfidenceScore <= 0) {
return *alt.Transcript, true
}
items := alt.Items
includePronunciation := false
for _, item := range items {
if !contentFilterByTranscribedTime(config, *item) {
continue
}
if !contentFilterByConfidenceScore(config, *item, isPartial) {
continue
}
if *item.Type == transcribestreamingservice.ItemTypePronunciation {
includePronunciation = true
}
message += *item.Content
}
// 各評価の結果、句読点のみかメッセージが空の場合は次へ
if !includePronunciation || (message == "") {
return "", false
}
return message, true
}