feat(video): update ASR terminology and file type labels for improved clarity

- Changed 'Audio Processing' to 'Audio & Video' in English, Korean, Russian, and Chinese translations to reflect expanded functionality.
- Updated ASR configuration titles and descriptions to include video processing capabilities, enhancing user understanding of the feature.
- Renamed file type labels from 'Audio Files' to 'Audio & Video' across multiple languages for consistency and clarity.
- Enhanced document upload handling in the KnowledgeBase to filter unsupported file types, providing user feedback for filtered images, videos, and audio files.

This update improves the internationalization of the application and clarifies the capabilities of the ASR feature.
This commit is contained in:
wizardchen
2026-04-14 22:27:31 +08:00
committed by lyingbug
parent cb97489787
commit 0fcab3a413
23 changed files with 635 additions and 291 deletions
+15 -2
View File
@@ -6,10 +6,23 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
// Segment represents a transcribed segment with timestamps.
type Segment struct {
Start float64 `json:"start"`
End float64 `json:"end"`
Text string `json:"text"`
}
// TranscriptionResult holds the full text and its segments.
type TranscriptionResult struct {
Text string `json:"text"`
Segments []Segment `json:"segments,omitempty"`
}
// 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)
// Transcribe sends audio bytes to the ASR model and returns the transcribed text and segments.
Transcribe(ctx context.Context, audioBytes []byte, fileName string) (*TranscriptionResult, error)
GetModelName() string
GetModelID() string
+25 -5
View File
@@ -3,6 +3,7 @@ package asr
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
@@ -44,9 +45,9 @@ func NewOpenAIASR(config *Config) (*OpenAIASR, error) {
}
// Transcribe sends audio bytes to the OpenAI-compatible audio transcriptions API.
func (s *OpenAIASR) Transcribe(ctx context.Context, audioBytes []byte, fileName string) (string, error) {
func (s *OpenAIASR) Transcribe(ctx context.Context, audioBytes []byte, fileName string) (*TranscriptionResult, error) {
if len(audioBytes) == 0 {
return "", fmt.Errorf("audio bytes are empty")
return nil, fmt.Errorf("audio bytes are empty")
}
// Ensure fileName has an extension for proper MIME type detection
@@ -61,7 +62,7 @@ func (s *OpenAIASR) Transcribe(ctx context.Context, audioBytes []byte, fileName
Model: s.modelName,
FilePath: fileName,
Reader: bytes.NewReader(audioBytes),
Format: openai.AudioResponseFormatJSON,
Format: openai.AudioResponseFormatVerboseJSON,
}
if s.language != "" {
@@ -70,12 +71,31 @@ func (s *OpenAIASR) Transcribe(ctx context.Context, audioBytes []byte, fileName
resp, err := s.client.CreateTranscription(ctx, req)
if err != nil {
return "", fmt.Errorf("ASR transcription request failed: %w", err)
return nil, fmt.Errorf("ASR transcription request failed: %w", err)
}
jsonData, err := json.Marshal(resp)
if err != nil {
return nil, fmt.Errorf("marshal transcription response: %w", err)
}
logger.Debugf(ctx, "[ASR] Transcription response: %s", string(jsonData))
text := strings.TrimSpace(resp.Text)
logger.Infof(ctx, "[ASR] Transcription completed, text length=%d", len(text))
return text, nil
var segments []Segment
for _, s := range resp.Segments {
segments = append(segments, Segment{
Start: s.Start,
End: s.End,
Text: strings.TrimSpace(s.Text),
})
}
return &TranscriptionResult{
Text: text,
Segments: segments,
}, nil
}
func (s *OpenAIASR) GetModelName() string { return s.modelName }
+3
View File
@@ -15,6 +15,9 @@ type Extractor interface {
// for each frame's image data. This is useful for streaming processing.
ExtractFramesToReaders(ctx context.Context, videoBytes []byte, options *ExtractOptions) ([]io.Reader, error)
// ExtractAudio extracts the audio track from a video file and returns it as bytes.
ExtractAudio(ctx context.Context, videoBytes []byte) ([]byte, error)
// GetVideoInfo retrieves basic information about a video file.
// It returns a map containing duration, width, height, etc.
GetVideoInfo(ctx context.Context, videoBytes []byte) (map[string]interface{}, error)
+44
View File
@@ -247,6 +247,50 @@ func (e *FFMpegExtractor) readExtractedFrames(ctx context.Context, frameDir stri
return frames, nil
}
// ExtractAudio extracts the audio track from a video using FFmpeg.
func (e *FFMpegExtractor) ExtractAudio(ctx context.Context, videoBytes []byte) ([]byte, error) {
tempVideoPath, err := e.writeTempVideo(videoBytes)
if err != nil {
return nil, err
}
defer os.Remove(tempVideoPath)
tempAudioFile, err := os.CreateTemp(e.tempDir, "audio-output-*.mp3")
if err != nil {
return nil, fmt.Errorf("failed to create temp audio file: %w", err)
}
tempAudioPath := tempAudioFile.Name()
tempAudioFile.Close()
defer os.Remove(tempAudioPath)
cmd := exec.CommandContext(ctx, e.ffmpegPath,
"-i", tempVideoPath,
"-vn",
"-c:a", "libmp3lame",
"-q:a", "2",
"-y",
tempAudioPath,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
if strings.Contains(stderr.String(), "Output file does not contain any stream") {
logger.Infof(ctx, "[VideoFFMpeg] Video does not contain an audio stream")
return nil, nil
}
return nil, fmt.Errorf("ffmpeg audio extraction failed: %w, stderr: %s", err, stderr.String())
}
audioBytes, err := os.ReadFile(tempAudioPath)
if err != nil {
return nil, fmt.Errorf("failed to read extracted audio: %w", err)
}
logger.Infof(ctx, "[VideoFFMpeg] Extracted audio, size: %d bytes", len(audioBytes))
return audioBytes, nil
}
// GetVideoInfo returns basic information about a video.
func (e *FFMpegExtractor) GetVideoInfo(ctx context.Context, videoBytes []byte) (map[string]interface{}, error) {
tempVideoPath, err := e.writeTempVideo(videoBytes)
+14 -3
View File
@@ -29,22 +29,33 @@ func NewOllamaVLM(config *Config, ollamaService *ollama.OllamaService) (*OllamaV
}
// Predict sends an image with a text prompt to the Ollama vision model.
func (v *OllamaVLM) Predict(ctx context.Context, imgBytes []byte, prompt string) (string, error) {
func (v *OllamaVLM) Predict(ctx context.Context, imgBytesList [][]byte, prompt string) (string, error) {
streamFlag := false
var images []ollamaapi.ImageData
for _, imgBytes := range imgBytesList {
if len(imgBytes) > 0 {
images = append(images, imgBytes)
}
}
chatReq := &ollamaapi.ChatRequest{
Model: v.modelName,
Messages: []ollamaapi.Message{
{
Role: "user",
Content: prompt,
Images: []ollamaapi.ImageData{imgBytes},
Images: images,
},
},
Stream: &streamFlag,
Options: map[string]interface{}{"temperature": 0.1},
}
logger.Infof(ctx, "[VLM] Calling Ollama API, model=%s, imageSize=%d", v.modelName, len(imgBytes))
totalImageSize := 0
for _, img := range imgBytesList {
totalImageSize += len(img)
}
logger.Infof(ctx, "[VLM] Calling Ollama API, model=%s, numImages=%d, totalImageSize=%d", v.modelName, len(images), totalImageSize)
var result string
err := v.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
+32 -20
View File
@@ -64,37 +64,49 @@ func NewRemoteAPIVLM(config *Config) (*RemoteAPIVLM, error) {
}
// Predict sends an image with a text prompt to the OpenAI-compatible API.
func (v *RemoteAPIVLM) Predict(ctx context.Context, imgBytes []byte, prompt string) (string, error) {
mimeType := detectImageMIME(imgBytes)
b64 := base64.StdEncoding.EncodeToString(imgBytes)
dataURI := fmt.Sprintf("data:%s;base64,%s", mimeType, b64)
func (v *RemoteAPIVLM) Predict(ctx context.Context, imgBytesList [][]byte, prompt string) (string, error) {
var parts []openai.ChatMessagePart
// Add text prompt first
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: prompt,
})
// Add images
for _, imgBytes := range imgBytesList {
if len(imgBytes) > 0 {
mimeType := detectImageMIME(imgBytes)
b64 := base64.StdEncoding.EncodeToString(imgBytes)
dataURI := fmt.Sprintf("data:%s;base64,%s", mimeType, b64)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
}
req := openai.ChatCompletionRequest{
Model: v.modelName,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
MultiContent: []openai.ChatMessagePart{
{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
},
{
Type: openai.ChatMessagePartTypeText,
Text: prompt,
},
},
Role: openai.ChatMessageRoleUser,
MultiContent: parts,
},
},
MaxTokens: defaultMaxToks,
Temperature: defaultTemp,
}
logger.Infof(ctx, "[VLM] Calling OpenAI-compatible API, model=%s, baseURL=%s, imageSize=%d",
v.modelName, v.baseURL, len(imgBytes))
totalImageSize := 0
for _, img := range imgBytesList {
totalImageSize += len(img)
}
logger.Infof(ctx, "[VLM] Calling OpenAI-compatible API, model=%s, baseURL=%s, numImages=%d, totalImageSize=%d",
v.modelName, v.baseURL, len(imgBytesList), totalImageSize)
resp, err := v.client.CreateChatCompletion(ctx, req)
if err != nil {
+2 -2
View File
@@ -11,8 +11,8 @@ import (
// VLM defines the interface for Vision Language Model operations.
type VLM interface {
// Predict sends an image with a text prompt to the VLM and returns the generated text.
Predict(ctx context.Context, imgBytes []byte, prompt string) (string, error)
// Predict sends one or more images with a text prompt to the VLM and returns the generated text.
Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error)
GetModelName() string
GetModelID() string