Include chat, weather, image, travel, streaming ASR and text examples, shared model initialization, documentation, and existing tests. Co-authored-by: TRAE CLI <traecli@bytedance.com>
153 lines
4.4 KiB
Go
153 lines
4.4 KiB
Go
package provider
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"example.com/ueino/pkg/model"
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
// ASR 调用 OpenAI Realtime 的纯转写接口。
|
|
type ASR struct {
|
|
BaseURL string
|
|
Model string
|
|
APIKey string
|
|
}
|
|
|
|
// Transcribe 读取最长 15 秒的 PCM 流,临时文字回调展示,最终文字单独返回。
|
|
// audio 如果实现 io.Closer,结束或取消时会关闭它,以解除正在等待的音频读取。
|
|
func (a *ASR) Transcribe(ctx context.Context, audio io.Reader, onDelta func(string)) (string, error) {
|
|
return a.transcribe(ctx, audio, onDelta, 30*time.Second)
|
|
}
|
|
|
|
func (a *ASR) transcribe(ctx context.Context, audio io.Reader, onDelta func(string), timeout time.Duration) (string, error) {
|
|
endpoint, err := url.Parse(strings.TrimRight(a.BaseURL, "/") + "/realtime")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
query := endpoint.Query()
|
|
query.Set("model", a.Model)
|
|
endpoint.RawQuery = query.Encode()
|
|
dialer := websocket.Dialer{
|
|
HandshakeTimeout: timeout,
|
|
Subprotocols: []string{"realtime", "openai-insecure-api-key." + a.APIKey},
|
|
}
|
|
conn, resp, err := dialer.DialContext(ctx, endpoint.String(), nil)
|
|
if err != nil {
|
|
if resp != nil {
|
|
resp.Body.Close()
|
|
}
|
|
return "", fmt.Errorf("连接语音识别服务失败: %w", err)
|
|
}
|
|
defer conn.Close()
|
|
runCtx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
stop := context.AfterFunc(runCtx, func() {
|
|
conn.Close()
|
|
if closer, ok := audio.(io.Closer); ok {
|
|
closer.Close()
|
|
}
|
|
})
|
|
defer stop()
|
|
// 返回时也关闭输入,确保发送协程不会留在 Read 中。
|
|
if closer, ok := audio.(io.Closer); ok {
|
|
defer closer.Close()
|
|
}
|
|
conn.SetReadDeadline(time.Now().Add(timeout))
|
|
sendErr := make(chan error, 1)
|
|
started := false
|
|
for {
|
|
var event model.ASREvent
|
|
if err := conn.ReadJSON(&event); err != nil {
|
|
if ctx.Err() != nil {
|
|
return "", ctx.Err()
|
|
}
|
|
select {
|
|
case err := <-sendErr:
|
|
return "", err
|
|
default:
|
|
return "", fmt.Errorf("读取语音识别结果失败: %w", err)
|
|
}
|
|
}
|
|
switch event.Type {
|
|
case "session.created":
|
|
update := model.ASRSessionUpdate{Type: "session.update"}
|
|
update.Session.Type = "transcription"
|
|
input := &update.Session.Audio.Input
|
|
input.Format.Type, input.Format.Rate = "audio/pcm", 24000
|
|
input.Transcription.Model, input.Transcription.Language = a.Model, "zh"
|
|
conn.SetWriteDeadline(time.Now().Add(timeout))
|
|
if err := conn.WriteJSON(update); err != nil {
|
|
return "", err
|
|
}
|
|
case "session.updated":
|
|
if started {
|
|
continue
|
|
}
|
|
started = true
|
|
// 初始化完成后取消读超时,提交时再设置最终结果的等待时间。
|
|
conn.SetReadDeadline(time.Time{})
|
|
go func() {
|
|
if err := sendAudio(runCtx, conn, audio, timeout); err != nil {
|
|
sendErr <- err
|
|
conn.Close()
|
|
}
|
|
}()
|
|
case "conversation.item.input_audio_transcription.delta":
|
|
if onDelta != nil {
|
|
onDelta(event.Delta)
|
|
}
|
|
case "conversation.item.input_audio_transcription.completed":
|
|
return strings.TrimSpace(event.Transcript), nil
|
|
case "error", "conversation.item.input_audio_transcription.failed":
|
|
if event.Error != nil {
|
|
return "", fmt.Errorf("语音识别失败: %s", event.Error.Message)
|
|
}
|
|
return "", fmt.Errorf("语音识别失败: %s", event.Type)
|
|
}
|
|
}
|
|
}
|
|
|
|
func sendAudio(ctx context.Context, conn *websocket.Conn, audio io.Reader, timeout time.Duration) error {
|
|
ticker := time.NewTicker(100 * time.Millisecond)
|
|
defer ticker.Stop()
|
|
buffer := make([]byte, 4800)
|
|
total := 0
|
|
// 即使调用方提供更长音频,也不跨过服务端的 20 秒自动分段边界。
|
|
audio = io.LimitReader(audio, 15*48000)
|
|
for {
|
|
n, err := io.ReadFull(audio, buffer)
|
|
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
|
|
return fmt.Errorf("读取录音失败: %w", err)
|
|
}
|
|
n -= n % 2
|
|
if n > 0 {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-ticker.C:
|
|
}
|
|
conn.SetWriteDeadline(time.Now().Add(timeout))
|
|
if err := conn.WriteJSON(model.ASREvent{Type: "input_audio_buffer.append", Audio: base64.StdEncoding.EncodeToString(buffer[:n])}); err != nil {
|
|
return fmt.Errorf("发送录音失败: %w", err)
|
|
}
|
|
total += n
|
|
}
|
|
if err != nil {
|
|
break
|
|
}
|
|
}
|
|
if total < 4800 {
|
|
return fmt.Errorf("录音不足 100ms,请重新录音")
|
|
}
|
|
conn.UnderlyingConn().SetReadDeadline(time.Now().Add(timeout))
|
|
conn.SetWriteDeadline(time.Now().Add(timeout))
|
|
return conn.WriteJSON(model.ASREvent{Type: "input_audio_buffer.commit"})
|
|
}
|