feat(asr): integrate Automatic Speech Recognition (ASR) support

- Added ASR configuration options to the knowledge base and model settings.
- Implemented ASR model selection and transcription capabilities in the knowledge processing pipeline.
- Enhanced file upload support to include audio formats for ASR processing.
- Updated localization files to include ASR-related labels and descriptions.
- Refactored model handling to accommodate ASR as a new model type.
This commit is contained in:
wizardchen
2026-04-02 16:43:37 +08:00
committed by lyingbug
parent d68c94a11a
commit 624e24ba49
30 changed files with 652 additions and 35 deletions
+8
View File
@@ -209,6 +209,14 @@ func getContentTypeByExt(ext string) string {
return "image/svg+xml"
case ".mp3":
return "audio/mpeg"
case ".wav":
return "audio/wav"
case ".m4a":
return "audio/mp4"
case ".flac":
return "audio/flac"
case ".ogg":
return "audio/ogg"
case ".mp4":
return "video/mp4"
default:
+85 -1
View File
@@ -259,6 +259,15 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
logger.Info(ctx, "Image multimodal configuration validation passed")
}
// 检查音频ASR配置完整性 - 只在音频文件时校验
if IsAudioType(getFileType(fileName)) {
if !kb.ASRConfig.IsASREnabled() {
logger.Error(ctx, "ASR model is not configured")
return nil, werrors.NewBadRequestError("上传音频文件需要设置ASR语音识别模型")
}
logger.Info(ctx, "Audio ASR configuration validation passed")
}
// Validate file type
logger.Infof(ctx, "Checking file type: %s", fileName)
if !isValidFileType(fileName) {
@@ -596,6 +605,11 @@ var allowedFileURLExtensions = map[string]bool{
"pdf": true,
"docx": true,
"doc": true,
"mp3": true,
"wav": true,
"m4a": true,
"flac": true,
"ogg": true,
}
// maxFileURLSize is the maximum allowed file size for file URL import (10MB)
@@ -2987,7 +3001,8 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
// isValidFileType checks if a file type is supported
func isValidFileType(filename string) bool {
switch strings.ToLower(getFileType(filename)) {
case "pdf", "txt", "docx", "doc", "md", "markdown", "png", "jpg", "jpeg", "gif", "csv", "xlsx", "xls", "pptx", "ppt", "json":
case "pdf", "txt", "docx", "doc", "md", "markdown", "png", "jpg", "jpeg", "gif", "csv", "xlsx", "xls", "pptx", "ppt", "json",
"mp3", "wav", "m4a", "flac", "ogg":
return true
default:
return false
@@ -7399,6 +7414,16 @@ func IsImageType(fileType string) bool {
}
}
// IsAudioType checks if a file type is an audio format
func IsAudioType(fileType string) bool {
switch strings.ToLower(fileType) {
case "mp3", "wav", "m4a", "flac", "ogg":
return true
default:
return false
}
}
// downloadFileFromURL downloads a remote file to a temp file and returns its binary content.
// payloadFileName and payloadFileType are in/out pointers: if they point to an empty string,
// the function resolves the value from Content-Disposition / URL path and writes it back.
@@ -7641,6 +7666,17 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
return nil
}
// 检查音频ASR配置(仅对文件导入)
if payload.FilePath != "" && IsAudioType(payload.FileType) && !kb.ASRConfig.IsASREnabled() {
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
Errorf("processDocument audio without ASR model configured")
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "上传音频文件需要设置ASR语音识别模型"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
// New pipeline: convert -> store images -> chunk -> vectorize -> multimodal tasks
var convertResult *types.ReadResult
var chunks []types.ParsedChunk
@@ -7764,6 +7800,54 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
}
}
// Step 1.5: ASR transcription for audio files
if convertResult != nil && convertResult.IsAudio && len(convertResult.AudioData) > 0 {
if !kb.ASRConfig.IsASREnabled() {
logger.Error(ctx, "Audio file detected but ASR is not configured")
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "ASR model is not configured for audio transcription"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
logger.Infof(ctx, "[ASR] Starting audio transcription for knowledge %s, audio size=%d bytes",
knowledge.ID, len(convertResult.AudioData))
asrModel, err := s.modelService.GetASRModel(ctx, kb.ASRConfig.ModelID)
if err != nil {
logger.Errorf(ctx, "[ASR] Failed to get ASR model: %v", err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("failed to get ASR model: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
transcribedText, err := asrModel.Transcribe(ctx, convertResult.AudioData, knowledge.FileName)
if err != nil {
logger.Errorf(ctx, "[ASR] Transcription failed: %v", err)
if isLastRetry {
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("audio transcription failed: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
}
return fmt.Errorf("audio transcription failed: %w", err)
}
if transcribedText == "" {
logger.Warn(ctx, "[ASR] Transcription returned empty text")
transcribedText = "[No speech detected in audio file]"
}
logger.Infof(ctx, "[ASR] Transcription completed, text length=%d", len(transcribedText))
// Replace the audio placeholder with the transcribed text
convertResult.MarkdownContent = transcribedText
convertResult.IsAudio = false
convertResult.AudioData = nil
}
// Step 2: Store images and update markdown references
var storedImages []docparser.StoredImage
+48
View File
@@ -8,6 +8,7 @@ import (
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/models/asr"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/models/vlm"
"github.com/Tencent/WeKnora/internal/types"
@@ -458,3 +459,50 @@ func (s *modelService) GetVLMModel(ctx context.Context, modelId string) (vlm.VLM
// Note: default model selection logic has been removed; models no longer
// maintain a per-type default flag at the service layer.
// GetASRModel retrieves and initializes an automatic speech recognition model instance.
func (s *modelService) GetASRModel(ctx context.Context, modelId string) (asr.ASR, error) {
if modelId == "" {
return nil, errors.New("model ID cannot be empty")
}
tenantID := types.MustTenantIDFromContext(ctx)
model, err := s.repo.GetByID(ctx, tenantID, modelId)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": modelId,
"tenant_id": tenantID,
})
return nil, err
}
if model == nil {
return nil, ErrModelNotFound
}
logger.Infof(ctx, "Getting ASR model: %s, source: %s", model.Name, model.Source)
ifType := model.Parameters.InterfaceType
if ifType == "" {
ifType = "openai"
}
sttModel, err := asr.NewASR(&asr.Config{
ModelID: model.ID,
APIKey: model.Parameters.APIKey,
BaseURL: model.Parameters.BaseURL,
ModelName: model.Name,
Source: model.Source,
InterfaceType: ifType,
})
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": model.ID,
"model_name": model.Name,
})
return nil, err
}
return sttModel, nil
}
@@ -24,10 +24,17 @@ var imageFormats = map[string]bool{
"bmp": true, "tiff": true, "webp": true,
}
var audioFormats = map[string]bool{
"mp3": true, "wav": true, "m4a": true, "flac": true, "ogg": true,
}
func init() {
for k := range imageFormats {
simpleFormats[k] = true
}
for k := range audioFormats {
simpleFormats[k] = true
}
}
// IsSimpleFormat returns true if the file type can be handled by the Go SimpleFormatReader.
@@ -65,6 +72,8 @@ func (b *SimpleFormatReader) Read(_ context.Context, req *types.ReadRequest) (*t
return &types.ReadResult{MarkdownContent: md}, nil
case imageFormats[ft]:
return imageToResult(req.FileName, req.FileContent), nil
case audioFormats[ft]:
return audioToResult(req.FileName, req.FileContent), nil
default:
return nil, fmt.Errorf("unsupported simple format: %s", ft)
}
@@ -99,6 +108,28 @@ func IsImageFormat(fileType string) bool {
return imageFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// IsAudioFormat returns true if the file type is a recognized audio format.
func IsAudioFormat(fileType string) bool {
return audioFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// audioToResult wraps a standalone audio file. The actual transcription is
// handled by the ASR model in the knowledge service pipeline. Here we just
// return a placeholder markdown with the raw bytes preserved for upstream
// processing.
func audioToResult(fileName string, data []byte) *types.ReadResult {
if fileName == "" {
fileName = "audio.mp3"
}
// Return a placeholder; the knowledge service will replace this with
// the ASR transcription result.
return &types.ReadResult{
MarkdownContent: fmt.Sprintf("[Audio file: %s]", fileName),
IsAudio: true,
AudioData: data,
}
}
// ensureOriginalImageRef checks whether the input file is an image and, if the
// returned markdown does not already contain a markdown image reference for it,
// prepends one and appends the raw bytes to imageRefs. This guarantees that
@@ -67,7 +67,7 @@ func (e *simpleEngine) Description() string {
return "Simple format & image parsing (no external service required)"
}
func (e *simpleEngine) FileTypes(_ bool) []string {
return []string{"md", "markdown", "txt", "csv", "json", "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp"}
return []string{"md", "markdown", "txt", "csv", "json", "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp", "mp3", "wav", "m4a", "flac", "ogg"}
}
func (e *simpleEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string) {
return true, ""
+44
View File
@@ -0,0 +1,44 @@
package asr
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types"
)
// ASR defines the interface for Automatic Speech Recognition model operations.
type ASR interface {
// Transcribe sends audio bytes to the ASR model and returns the transcribed text.
Transcribe(ctx context.Context, audioBytes []byte, fileName string) (string, error)
GetModelName() string
GetModelID() string
}
// Config holds the configuration needed to create an ASR instance.
type Config struct {
Source types.ModelSource
BaseURL string
ModelName string
APIKey string
ModelID string
InterfaceType string // "openai" (default)
Language string // optional: specify language for transcription
}
// NewASR creates an ASR instance based on the provided configuration.
func NewASR(config *Config) (ASR, error) {
ifType := strings.ToLower(config.InterfaceType)
if ifType == "" {
ifType = "openai"
}
switch ifType {
case "openai":
return NewOpenAIASR(config)
default:
return nil, fmt.Errorf("unsupported ASR interface type: %s", ifType)
}
}
+119
View File
@@ -0,0 +1,119 @@
package asr
import (
"bytes"
"context"
"fmt"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
openai "github.com/sashabaranov/go-openai"
)
const (
asrDefaultTimeout = 300 * time.Second // audio transcription can be slow
)
// OpenAIASR implements ASR via an OpenAI-compatible audio transcriptions API.
type OpenAIASR struct {
modelName string
modelID string
client *openai.Client
baseURL string
language string
}
// NewOpenAIASR creates an OpenAI-compatible ASR instance.
func NewOpenAIASR(config *Config) (*OpenAIASR, error) {
apiCfg := openai.DefaultConfig(config.APIKey)
if config.BaseURL != "" {
apiCfg.BaseURL = config.BaseURL
}
apiCfg.HTTPClient = &http.Client{Timeout: asrDefaultTimeout}
return &OpenAIASR{
modelName: config.ModelName,
modelID: config.ModelID,
client: openai.NewClientWithConfig(apiCfg),
baseURL: config.BaseURL,
language: config.Language,
}, nil
}
// Transcribe sends audio bytes to the OpenAI-compatible audio transcriptions API.
func (s *OpenAIASR) Transcribe(ctx context.Context, audioBytes []byte, fileName string) (string, error) {
if len(audioBytes) == 0 {
return "", fmt.Errorf("audio bytes are empty")
}
// Ensure fileName has an extension for proper MIME type detection
if fileName == "" {
fileName = "audio.mp3"
}
logger.Infof(ctx, "[ASR] Calling OpenAI-compatible transcription API, model=%s, baseURL=%s, audioSize=%d, file=%s",
s.modelName, s.baseURL, len(audioBytes), fileName)
req := openai.AudioRequest{
Model: s.modelName,
FilePath: fileName,
Reader: bytes.NewReader(audioBytes),
Format: openai.AudioResponseFormatJSON,
}
if s.language != "" {
req.Language = s.language
}
resp, err := s.client.CreateTranscription(ctx, req)
if err != nil {
return "", fmt.Errorf("ASR transcription request failed: %w", err)
}
text := strings.TrimSpace(resp.Text)
logger.Infof(ctx, "[ASR] Transcription completed, text length=%d", len(text))
return text, nil
}
func (s *OpenAIASR) GetModelName() string { return s.modelName }
func (s *OpenAIASR) GetModelID() string { return s.modelID }
// DetectAudioFormat returns a file extension hint for the given audio bytes.
func DetectAudioFormat(data []byte, fileName string) string {
if fileName != "" {
ext := strings.ToLower(filepath.Ext(fileName))
if ext != "" {
return ext
}
}
// Try to detect from magic bytes
if len(data) >= 4 {
// MP3: starts with ID3 or 0xFF 0xFB
if data[0] == 'I' && data[1] == 'D' && data[2] == '3' {
return ".mp3"
}
if data[0] == 0xFF && (data[1]&0xE0) == 0xE0 {
return ".mp3"
}
// FLAC: starts with "fLaC"
if data[0] == 'f' && data[1] == 'L' && data[2] == 'a' && data[3] == 'C' {
return ".flac"
}
// OGG: starts with "OggS"
if data[0] == 'O' && data[1] == 'g' && data[2] == 'g' && data[3] == 'S' {
return ".ogg"
}
// WAV: starts with "RIFF"
if data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F' {
return ".wav"
}
}
// M4A: check for ftyp box
if len(data) >= 8 && data[4] == 'f' && data[5] == 't' && data[6] == 'y' && data[7] == 'p' {
return ".m4a"
}
return ".mp3" // default
}
+2
View File
@@ -32,12 +32,14 @@ func (p *AliyunProvider) Info() ProviderInfo {
types.ModelTypeEmbedding: AliyunChatBaseURL,
types.ModelTypeRerank: AliyunRerankBaseURL,
types.ModelTypeVLLM: AliyunChatBaseURL,
types.ModelTypeASR: AliyunChatBaseURL,
},
ModelTypes: []types.ModelType{
types.ModelTypeKnowledgeQA,
types.ModelTypeEmbedding,
types.ModelTypeRerank,
types.ModelTypeVLLM,
types.ModelTypeASR,
},
RequiresAuth: true,
}
+1
View File
@@ -25,6 +25,7 @@ func (p *GenericProvider) Info() ProviderInfo {
types.ModelTypeEmbedding,
types.ModelTypeRerank,
types.ModelTypeVLLM,
types.ModelTypeASR,
},
RequiresAuth: false, // 可能需要也可能不需要
}
+2
View File
@@ -31,12 +31,14 @@ func (p *GPUStackProvider) Info() ProviderInfo {
types.ModelTypeEmbedding: GPUStackBaseURL,
types.ModelTypeRerank: GPUStackRerankBaseURL,
types.ModelTypeVLLM: GPUStackBaseURL,
types.ModelTypeASR: GPUStackBaseURL,
},
ModelTypes: []types.ModelType{
types.ModelTypeKnowledgeQA,
types.ModelTypeEmbedding,
types.ModelTypeRerank,
types.ModelTypeVLLM,
types.ModelTypeASR,
},
RequiresAuth: true, // GPUStack 需要 API Key
}
+2
View File
@@ -28,12 +28,14 @@ func (p *OpenAIProvider) Info() ProviderInfo {
types.ModelTypeEmbedding: OpenAIBaseURL,
types.ModelTypeRerank: OpenAIBaseURL,
types.ModelTypeVLLM: OpenAIBaseURL,
types.ModelTypeASR: OpenAIBaseURL,
},
ModelTypes: []types.ModelType{
types.ModelTypeKnowledgeQA,
types.ModelTypeEmbedding,
types.ModelTypeRerank,
types.ModelTypeVLLM,
types.ModelTypeASR,
},
RequiresAuth: true,
}
+2
View File
@@ -28,12 +28,14 @@ func (p *SiliconFlowProvider) Info() ProviderInfo {
types.ModelTypeEmbedding: SiliconFlowBaseURL,
types.ModelTypeRerank: SiliconFlowBaseURL,
types.ModelTypeVLLM: SiliconFlowBaseURL,
types.ModelTypeASR: SiliconFlowBaseURL,
},
ModelTypes: []types.ModelType{
types.ModelTypeKnowledgeQA,
types.ModelTypeEmbedding,
types.ModelTypeRerank,
types.ModelTypeVLLM,
types.ModelTypeASR,
},
RequiresAuth: true,
}
+2
View File
@@ -20,6 +20,8 @@ type ReadResult struct {
ImageDirPath string
Metadata map[string]string
Error string
IsAudio bool // true when the result contains raw audio data needing ASR transcription
AudioData []byte // raw audio bytes for ASR processing
}
// ImageRef represents an image reference extracted from the document.
+3
View File
@@ -6,6 +6,7 @@ import (
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/models/asr"
"github.com/Tencent/WeKnora/internal/models/vlm"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -32,6 +33,8 @@ type ModelService interface {
GetChatModel(ctx context.Context, modelId string) (chat.Chat, error)
// GetVLMModel gets a vision language model
GetVLMModel(ctx context.Context, modelId string) (vlm.VLM, error)
// GetASRModel gets an automatic speech recognition model
GetASRModel(ctx context.Context, modelId string) (asr.ASR, error)
}
// ModelRepository defines the model repository interface
+31
View File
@@ -60,6 +60,8 @@ type KnowledgeBase struct {
SummaryModelID string `yaml:"summary_model_id" json:"summary_model_id"`
// VLM config
VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json"`
// ASR config (Automatic Speech Recognition)
ASRConfig ASRConfig `yaml:"asr_config" json:"asr_config" gorm:"type:json"`
// Storage provider config (new): only stores provider selection; credentials from tenant StorageEngineConfig
StorageProviderConfig *StorageProviderConfig `yaml:"storage_provider_config" json:"storage_provider_config" gorm:"column:storage_provider_config;type:jsonb"`
// Deprecated: legacy COS config column. Kept for backward compatibility with old data.
@@ -386,6 +388,35 @@ func (c *VLMConfig) Scan(value interface{}) error {
return json.Unmarshal(b, c)
}
// ASRConfig represents the ASR (Automatic Speech Recognition) configuration
type ASRConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
ModelID string `yaml:"model_id" json:"model_id"`
Language string `yaml:"language" json:"language"` // optional: language hint for transcription
}
// IsASREnabled checks if ASR is enabled with a valid model
func (c ASRConfig) IsASREnabled() bool {
return c.Enabled && c.ModelID != ""
}
// Value implements the driver.Valuer interface, used to convert ASRConfig to database value
func (c ASRConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to ASRConfig
func (c *ASRConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// ExtractConfig represents the extract configuration for a knowledge base
type ExtractConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
+1
View File
@@ -18,6 +18,7 @@ const (
ModelTypeRerank ModelType = "Rerank" // Rerank model
ModelTypeKnowledgeQA ModelType = "KnowledgeQA" // KnowledgeQA model
ModelTypeVLLM ModelType = "VLLM" // VLLM model
ModelTypeASR ModelType = "ASR" // ASR (Automatic Speech Recognition) model
)
// ModelStatus represents the status of the model