Files
ai_academy/internal/models/asr/protocol.go
T
runny 9058149576
Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s
refactor: 项目更名 WeKnora → Academy
- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名)
- 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块)
- docreader proto 描述符采用等长替换,保持序列化字节布局有效
- Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像
- 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
2026-11-13 20:52:51 +08:00

164 lines
5.5 KiB
Go

package asr
import (
"context"
"fmt"
"path/filepath"
"slices"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/models/api/openaichataudio"
"academy/internal/models/api/openaitranscriptions"
"academy/internal/models/providers"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
)
// retryPolicy is the transport-error retry budget, which is none. The
// knowledge pipeline retries a failed transcription as a whole task, and a
// client-level retry on top would turn one hung 300-second upload into
// several.
var retryPolicy = func() api.RetryPolicy { return api.RetryPolicy{} }
// newASR resolves the catalog and returns the protocol client for the
// configured model. It mirrors rerank.newReranker and
// embedding.newRemoteEmbedder: the vendor's facts decide the protocol, the
// URL and the credential, and this function knows no vendor names.
func newASR(config *Config) (ASR, error) {
if config == nil {
return nil, fmt.Errorf("asr config is nil")
}
if strings.TrimSpace(config.ModelName) == "" {
return nil, fmt.Errorf("model name is required")
}
resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: config.Provider,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeASR,
Extra: config.ExtraConfig,
Override: config.Spec,
})
if err != nil {
return nil, err
}
// A vendor that does not declare speech recognition has not been checked
// for it, and its Endpoint hook may still compute a path — Azure's does.
// A row that named the vendor is refused; a row that named none and was
// matched by its URL is what the pre-catalog client served: an
// OpenAI-compatible endpoint at that URL.
if !resolved.Vendor.SupportsType(types.ModelTypeASR) {
if strings.TrimSpace(config.Provider) != "" {
return nil, fmt.Errorf("%s does not offer speech recognition in this build", resolved.Vendor.Name)
}
resolved, err = modelruntime.Resolve(modelruntime.Ref{
Provider: providers.GenericID,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeASR,
Extra: config.ExtraConfig,
Override: config.Spec,
})
if err != nil {
return nil, err
}
}
if err := validateASRBaseURL(resolved.BaseURL); err != nil {
return nil, err
}
vendor := resolved.Vendor
endpoint, err := resolved.Endpoint(types.ModelTypeASR, modelruntime.Connection{
ModelID: config.ModelID,
Credentials: api.Credentials{APIKey: config.APIKey},
Headers: config.CustomHeaders,
Extra: config.ExtraConfig,
Client: newASRHTTPClient(time.Duration(resolved.Transcriptions.RequestTimeout) * time.Second),
})
if err != nil {
return nil, err
}
if endpoint.URL != "" {
if err := validateASRBaseURL(endpoint.URL); err != nil {
return nil, err
}
}
settings := resolved.Transcriptions
var client api.Transcriber
switch resolved.TranscriptionAPI {
case api.TranscriptionOpenAI:
client = openaitranscriptions.New(openaitranscriptions.Config{
Endpoint: endpoint, Settings: settings, Retry: retryPolicy(),
})
case api.TranscriptionChatAudio:
client = openaichataudio.New(openaichataudio.Config{
Endpoint: endpoint, Settings: settings, Retry: retryPolicy(),
})
default:
return nil, fmt.Errorf("unsupported transcription api %q for provider %s",
resolved.TranscriptionAPI, vendor.ID)
}
return &protocolASR{
inner: client,
settings: settings,
vendor: vendor.Name,
endpoint: resolved.BaseURL,
modelName: config.ModelName,
modelID: config.ModelID,
}, nil
}
// protocolASR adapts a protocol client to the ASR interface and refuses an
// upload the vendor has documented it will not take, before sending it.
type protocolASR struct {
inner api.Transcriber
settings api.TranscriptionsSettings
vendor string
endpoint string
modelName string
modelID string
}
func (a *protocolASR) GetModelName() string { return a.modelName }
func (a *protocolASR) GetModelID() string { return a.modelID }
func (a *protocolASR) Transcribe(ctx context.Context, audio []byte, fileName string) (*TranscriptionResult, error) {
if len(audio) == 0 {
return nil, fmt.Errorf("audio bytes are empty")
}
if limit := a.settings.MaxFileBytes; limit > 0 && len(audio) > limit {
return nil, fmt.Errorf("%s transcription: the audio is %.1f MB; %s accepts at most %d MB per file",
a.modelName, float64(len(audio))/(1<<20), a.vendor, limit>>20)
}
// The server identifies the format from the extension.
if fileName == "" {
fileName = "audio.mp3"
}
if formats := a.settings.Formats; len(formats) > 0 {
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(fileName)), ".")
if !slices.Contains(formats, ext) {
return nil, fmt.Errorf("%s transcription: %s accepts %s audio, not %q",
a.modelName, a.vendor, strings.Join(formats, "/"), fileName)
}
}
logger.Infof(ctx, "[ASR] transcribing model=%s endpoint=%s size=%d file=%s",
a.modelName, a.endpoint, len(audio), fileName)
out, err := a.inner.Transcribe(ctx, api.TranscriptionRequest{
Audio: audio, FileName: fileName, Language: languageFrom(ctx),
})
if err != nil {
return nil, fmt.Errorf("ASR transcription request failed: %w", err)
}
result := &TranscriptionResult{Text: out.Text, Duration: out.Duration}
for _, s := range out.Segments {
result.Segments = append(result.Segments, Segment{Start: s.Start, End: s.End, Text: s.Text})
}
logger.Infof(ctx, "[ASR] transcription completed, text length=%d", len(result.Text))
return result, nil
}