feat: add realtime ASR voice chat with Cobra subcommand
This commit is contained in:
1 parent
dab8cbb55d
commit
74367f39e0
17 files changed
+977
-82
No files matched your search
@@ -0,0 +1,36 @@
|
||||
package model
|
||||
|
||||
// ASREvent 只包含实时转写接口使用的事件字段。
|
||||
type ASREvent struct {
|
||||
Type string `json:"type"`
|
||||
ItemID string `json:"item_id,omitempty"`
|
||||
Delta string `json:"delta,omitempty"`
|
||||
Transcript string `json:"transcript,omitempty"`
|
||||
Audio string `json:"audio,omitempty"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ASRSessionUpdate 配置中文、单声道 PCM 输入和手动提交。
|
||||
type ASRSessionUpdate struct {
|
||||
Type string `json:"type"`
|
||||
Session ASRSession `json:"session"`
|
||||
}
|
||||
|
||||
type ASRSession struct {
|
||||
Type string `json:"type"`
|
||||
Audio struct {
|
||||
Input struct {
|
||||
Format struct {
|
||||
Type string `json:"type"`
|
||||
Rate int `json:"rate"`
|
||||
} `json:"format"`
|
||||
Transcription struct {
|
||||
Model string `json:"model"`
|
||||
Language string `json:"language"`
|
||||
} `json:"transcription"`
|
||||
TurnDetection any `json:"turn_detection"`
|
||||
} `json:"input"`
|
||||
} `json:"audio"`
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
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"})
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func asrServer(t *testing.T, handle func(*websocket.Conn)) *ASR {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/realtime" || r.URL.Query().Get("model") != "local-asr" {
|
||||
t.Errorf("连接地址不正确: %s", r.URL)
|
||||
}
|
||||
protocols := websocket.Subprotocols(r)
|
||||
if len(protocols) != 2 || protocols[0] != "realtime" || protocols[1] != "openai-insecure-api-key.test-key" {
|
||||
t.Error("未使用预期的认证子协议")
|
||||
}
|
||||
upgrader := websocket.Upgrader{Subprotocols: []string{"realtime"}}
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
handle(conn)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return &ASR{BaseURL: "ws" + strings.TrimPrefix(server.URL, "http"), Model: "local-asr", APIKey: "test-key"}
|
||||
}
|
||||
|
||||
func initASR(t *testing.T, conn *websocket.Conn) bool {
|
||||
t.Helper()
|
||||
if err := conn.WriteJSON(model.ASREvent{Type: "session.created"}); err != nil {
|
||||
return false
|
||||
}
|
||||
var update model.ASRSessionUpdate
|
||||
if err := conn.ReadJSON(&update); err != nil {
|
||||
t.Error(err)
|
||||
return false
|
||||
}
|
||||
input := update.Session.Audio.Input
|
||||
if update.Type != "session.update" || update.Session.Type != "transcription" || input.Format.Rate != 24000 || input.Format.Type != "audio/pcm" || input.Transcription.Model != "local-asr" || input.Transcription.Language != "zh" || input.TurnDetection != nil {
|
||||
t.Errorf("会话配置错误: %+v", update)
|
||||
}
|
||||
return conn.WriteJSON(model.ASREvent{Type: "session.updated"}) == nil
|
||||
}
|
||||
|
||||
func TestASRTranscribe(t *testing.T) {
|
||||
pcm := bytes.Repeat([]byte{1, 2}, 4801)
|
||||
asr := asrServer(t, func(conn *websocket.Conn) {
|
||||
if !initASR(t, conn) {
|
||||
return
|
||||
}
|
||||
var received []byte
|
||||
for {
|
||||
kind, data, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if kind != websocket.TextMessage {
|
||||
t.Error("音频必须使用 JSON 文本帧")
|
||||
}
|
||||
var event model.ASREvent
|
||||
if err := json.Unmarshal(data, &event); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if event.Type == "input_audio_buffer.commit" {
|
||||
break
|
||||
}
|
||||
chunk, err := base64.StdEncoding.DecodeString(event.Audio)
|
||||
if err != nil || event.Type != "input_audio_buffer.append" || len(chunk) > 4800 || len(chunk)%2 != 0 {
|
||||
t.Errorf("音频包错误: %s,%v", event.Type, err)
|
||||
}
|
||||
received = append(received, chunk...)
|
||||
}
|
||||
if !bytes.Equal(received, pcm) {
|
||||
t.Error("收到的 PCM 与输入不一致")
|
||||
}
|
||||
conn.WriteJSON(model.ASREvent{Type: "conversation.item.input_audio_transcription.delta", ItemID: "one", Delta: "查天气"})
|
||||
conn.WriteJSON(model.ASREvent{Type: "conversation.item.input_audio_transcription.completed", ItemID: "one", Transcript: " 画一只猫。 "})
|
||||
})
|
||||
var delta string
|
||||
text, err := asr.Transcribe(context.Background(), bytes.NewReader(pcm), func(s string) { delta += s })
|
||||
if err != nil || delta != "查天气" || text != "画一只猫。" {
|
||||
t.Fatalf("结果 = %q,临时文字 = %q,错误 = %v", text, delta, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASRFailures(t *testing.T) {
|
||||
for _, mode := range []string{"空结果", "服务端错误", "转写失败", "断连", "等待最终结果超时", "初始化超时", "录音过短", "读取音频失败", "取消"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
asr := asrServer(t, func(conn *websocket.Conn) {
|
||||
if mode == "初始化超时" {
|
||||
conn.ReadMessage()
|
||||
return
|
||||
}
|
||||
if !initASR(t, conn) {
|
||||
return
|
||||
}
|
||||
for {
|
||||
var event model.ASREvent
|
||||
if conn.ReadJSON(&event) != nil {
|
||||
return
|
||||
}
|
||||
if mode == "取消" {
|
||||
cancel()
|
||||
conn.ReadMessage()
|
||||
return
|
||||
}
|
||||
if event.Type == "input_audio_buffer.commit" {
|
||||
break
|
||||
}
|
||||
}
|
||||
switch mode {
|
||||
case "空结果":
|
||||
conn.WriteJSON(model.ASREvent{Type: "conversation.item.input_audio_transcription.completed"})
|
||||
case "服务端错误", "转写失败":
|
||||
kind := "error"
|
||||
if mode == "转写失败" {
|
||||
kind = "conversation.item.input_audio_transcription.failed"
|
||||
}
|
||||
conn.WriteJSON(map[string]any{"type": kind, "error": map[string]string{"message": "测试失败"}})
|
||||
case "等待最终结果超时":
|
||||
conn.ReadMessage()
|
||||
}
|
||||
})
|
||||
var audio io.Reader = bytes.NewReader(make([]byte, 4800))
|
||||
if mode == "录音过短" {
|
||||
audio = bytes.NewReader(make([]byte, 4798))
|
||||
}
|
||||
if mode == "读取音频失败" {
|
||||
audio = failedAudio{}
|
||||
}
|
||||
text, err := asr.transcribe(ctx, audio, nil, 100*time.Millisecond)
|
||||
if mode == "空结果" {
|
||||
if err != nil || text != "" {
|
||||
t.Fatalf("空结果 = %q,错误 = %v", text, err)
|
||||
}
|
||||
} else if err == nil {
|
||||
t.Fatal("预期失败")
|
||||
}
|
||||
if mode == "取消" && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("预期取消,得到 %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type failedAudio struct{}
|
||||
|
||||
func (failedAudio) Read([]byte) (int, error) {
|
||||
return 0, errors.New("录音设备断开")
|
||||
}
|
||||
|
||||
func TestASRCancelBlockedAudio(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
reader, writer := io.Pipe()
|
||||
defer writer.Close()
|
||||
asr := asrServer(t, func(conn *websocket.Conn) {
|
||||
if initASR(t, conn) {
|
||||
cancel()
|
||||
conn.ReadMessage()
|
||||
}
|
||||
})
|
||||
if _, err := asr.Transcribe(ctx, reader, nil); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("预期取消,得到 %v", err)
|
||||
}
|
||||
if _, err := reader.Read(make([]byte, 2)); err == nil {
|
||||
t.Fatal("取消后应该关闭阻塞的音频读取")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user