Appearance
转录模型配置
转录模型是AnythingLLM处理音频和视频内容的重要组件,能够将语音转换为文本,使音频内容可以被搜索和分析。本指南将详细介绍如何配置和优化各种转录模型。
什么是转录模型
转录模型(也称为语音识别模型)将音频信号转换为文本,主要功能包括:
- 语音转文字: 将音频文件转换为可搜索的文本
- 实时转录: 实时处理音频流
- 多语言支持: 识别不同语言的语音
- 音频预处理: 降噪、音频增强等
- 时间戳标记: 为转录文本添加时间信息
支持的转录模型
OpenAI Whisper
Whisper API
OpenAI提供的云端Whisper服务,支持多种语言和音频格式。
bash
# OpenAI Whisper 配置
WHISPER_PROVIDER=openai
OPENAI_API_KEY=your_openai_api_key
WHISPER_MODEL_PREF=whisper-1
# 音频处理设置
WHISPER_LANGUAGE=auto # 自动检测语言
WHISPER_TEMPERATURE=0.0
WHISPER_RESPONSE_FORMAT=json
特性:
- 支持语言: 99种语言
- 音频格式: mp3, mp4, mpeg, mpga, m4a, wav, webm
- 最大文件大小: 25MB
- 准确性: 非常高
配置选项
bash
# 详细配置
WHISPER_LANGUAGE=zh # 指定中文
WHISPER_PROMPT="以下是普通话的录音。" # 提示词
WHISPER_TEMPERATURE=0.2 # 控制随机性
WHISPER_RESPONSE_FORMAT=verbose_json # 详细输出
本地 Whisper 模型
Whisper.cpp
高效的本地Whisper实现:
bash
# Whisper.cpp 配置
WHISPER_PROVIDER=local
WHISPER_MODEL_PATH=/path/to/whisper/models
WHISPER_MODEL_SIZE=base # tiny, base, small, medium, large
# 性能设置
WHISPER_THREADS=4
WHISPER_PROCESSORS=1
模型大小选择:
tiny
: 39MB, 最快但准确性较低base
: 74MB, 平衡选择small
: 244MB, 更好的准确性medium
: 769MB, 高准确性large
: 1550MB, 最高准确性
本地部署配置
bash
# 下载模型
wget https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin
# 配置路径
WHISPER_MODEL_PATH=/opt/whisper/models/ggml-base.bin
WHISPER_LANGUAGE=auto
WHISPER_TRANSLATE=false # 是否翻译为英文
Azure 语音服务
bash
# Azure 语音服务配置
WHISPER_PROVIDER=azure
AZURE_SPEECH_KEY=your_azure_speech_key
AZURE_SPEECH_REGION=eastus
AZURE_SPEECH_LANGUAGE=zh-CN
# 高级设置
AZURE_SPEECH_ENDPOINT=https://eastus.api.cognitive.microsoft.com
AZURE_SPEECH_PROFANITY_OPTION=masked
Google Cloud Speech-to-Text
bash
# Google Cloud 配置
WHISPER_PROVIDER=google
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
GOOGLE_SPEECH_LANGUAGE=zh-CN
GOOGLE_SPEECH_MODEL=latest_long
# 增强功能
GOOGLE_SPEECH_ENABLE_PUNCTUATION=true
GOOGLE_SPEECH_ENABLE_SPEAKER_DIARIZATION=true
AWS Transcribe
bash
# AWS Transcribe 配置
WHISPER_PROVIDER=aws
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_REGION=us-east-1
AWS_TRANSCRIBE_LANGUAGE=zh-CN
# 自定义词汇
AWS_TRANSCRIBE_VOCABULARY_NAME=custom-vocabulary
音频格式支持
支持的格式
常见音频格式
bash
# 支持的音频格式
SUPPORTED_AUDIO_FORMATS=mp3,wav,m4a,aac,ogg,flac,webm
# 最大文件大小 (MB)
MAX_AUDIO_FILE_SIZE=100
# 音频质量设置
AUDIO_SAMPLE_RATE=16000 # 16kHz
AUDIO_CHANNELS=1 # 单声道
AUDIO_BIT_DEPTH=16 # 16位
视频文件音频提取
bash
# 启用视频音频提取
ENABLE_VIDEO_AUDIO_EXTRACTION=true
SUPPORTED_VIDEO_FORMATS=mp4,avi,mov,mkv,webm
# FFmpeg 配置
FFMPEG_PATH=/usr/bin/ffmpeg
FFMPEG_AUDIO_CODEC=pcm_s16le
音频预处理
自动预处理
bash
# 启用音频预处理
ENABLE_AUDIO_PREPROCESSING=true
# 降噪设置
ENABLE_NOISE_REDUCTION=true
NOISE_REDUCTION_LEVEL=moderate # light, moderate, aggressive
# 音量标准化
ENABLE_AUDIO_NORMALIZATION=true
TARGET_AUDIO_LEVEL=-23 # LUFS
高级预处理
javascript
// 音频预处理配置
const audioPreprocessing = {
enabled: true,
noiseReduction: {
enabled: true,
algorithm: 'spectral_subtraction',
level: 'moderate'
},
normalization: {
enabled: true,
targetLevel: -23,
peakLimiting: true
},
filtering: {
highpass: 80, // Hz
lowpass: 8000 // Hz
}
};
语言配置
多语言支持
自动语言检测
bash
# 自动检测语言
WHISPER_LANGUAGE=auto
WHISPER_LANGUAGE_DETECTION_THRESHOLD=0.5
# 支持的语言列表
SUPPORTED_LANGUAGES=zh,en,ja,ko,es,fr,de,ru,ar
特定语言优化
bash
# 中文优化
WHISPER_LANGUAGE=zh
WHISPER_PROMPT="以下是中文普通话的录音,包含技术术语。"
# 英文优化
WHISPER_LANGUAGE=en
WHISPER_PROMPT="The following is a recording in English with technical terms."
# 日文优化
WHISPER_LANGUAGE=ja
WHISPER_PROMPT="以下は日本語の録音です。"
方言和口音
中文方言支持
bash
# 普通话
WHISPER_LANGUAGE=zh
WHISPER_DIALECT=mandarin
# 粤语 (需要特殊模型)
WHISPER_LANGUAGE=yue
WHISPER_MODEL_PREF=whisper-cantonese
# 台湾国语
WHISPER_LANGUAGE=zh-TW
英文口音
bash
# 美式英语
WHISPER_LANGUAGE=en-US
# 英式英语
WHISPER_LANGUAGE=en-GB
# 澳式英语
WHISPER_LANGUAGE=en-AU
高级功能
说话人分离
启用说话人分离
bash
# 说话人分离配置
ENABLE_SPEAKER_DIARIZATION=true
MAX_SPEAKERS=5
MIN_SPEAKERS=1
# 说话人识别
ENABLE_SPEAKER_IDENTIFICATION=true
SPEAKER_PROFILES_PATH=/path/to/speaker/profiles
配置示例
javascript
// 说话人分离配置
const speakerDiarization = {
enabled: true,
maxSpeakers: 5,
minSpeakers: 1,
clustering: 'spectral',
threshold: 0.5,
outputFormat: 'segments' // segments, speakers, both
};
实时转录
流式处理
bash
# 实时转录配置
ENABLE_REAL_TIME_TRANSCRIPTION=true
STREAM_CHUNK_SIZE=1024 # 字节
STREAM_BUFFER_SIZE=4096
STREAM_TIMEOUT=5000 # 5秒
# WebSocket 配置
WEBSOCKET_PORT=3002
WEBSOCKET_PATH=/ws/transcribe
实时配置
javascript
// 实时转录配置
const realtimeConfig = {
enabled: true,
chunkSize: 1024,
bufferSize: 4096,
timeout: 5000,
interimResults: true,
punctuation: true,
profanityFilter: false
};
时间戳和分段
时间戳配置
bash
# 时间戳设置
ENABLE_TIMESTAMPS=true
TIMESTAMP_GRANULARITY=word # word, sentence, segment
TIMESTAMP_FORMAT=seconds # seconds, milliseconds
# 分段设置
ENABLE_SEGMENTATION=true
SEGMENT_MAX_LENGTH=30 # 秒
SEGMENT_MIN_LENGTH=1
输出格式
javascript
// 时间戳输出格式
const timestampFormat = {
enabled: true,
granularity: 'word',
format: {
start: 'seconds',
end: 'seconds',
confidence: true
},
segments: {
enabled: true,
maxLength: 30,
minLength: 1
}
};
性能优化
处理速度优化
并行处理
bash
# 并行转录配置
TRANSCRIPTION_WORKERS=4
MAX_CONCURRENT_TRANSCRIPTIONS=2
TRANSCRIPTION_QUEUE_SIZE=10
# 批量处理
ENABLE_BATCH_TRANSCRIPTION=true
BATCH_SIZE=5
BATCH_TIMEOUT=300000 # 5分钟
GPU 加速
bash
# GPU 配置 (如果支持)
ENABLE_GPU_ACCELERATION=true
CUDA_DEVICE=0
GPU_MEMORY_LIMIT=4096 # MB
# 模型优化
ENABLE_MODEL_QUANTIZATION=true
QUANTIZATION_LEVEL=int8
内存优化
内存管理
bash
# 内存限制
TRANSCRIPTION_MEMORY_LIMIT=2048 # MB
AUDIO_BUFFER_SIZE=1024 # KB
# 临时文件管理
TEMP_AUDIO_DIR=/tmp/anythingllm/audio
CLEANUP_TEMP_FILES=true
TEMP_FILE_TTL=3600 # 1小时
流式处理优化
javascript
// 流式处理配置
const streamConfig = {
bufferSize: 1024,
chunkSize: 512,
overlap: 100,
memoryLimit: 2048,
cleanup: {
enabled: true,
interval: 300000, // 5分钟
maxAge: 3600000 // 1小时
}
};
质量控制
转录质量评估
置信度阈值
bash
# 质量控制
MIN_CONFIDENCE_THRESHOLD=0.7
ENABLE_QUALITY_FILTERING=true
# 后处理
ENABLE_TEXT_POSTPROCESSING=true
REMOVE_FILLER_WORDS=true
CORRECT_COMMON_ERRORS=true
质量指标
javascript
// 质量评估配置
const qualityConfig = {
confidenceThreshold: 0.7,
filtering: {
enabled: true,
removeFillers: true,
correctErrors: true,
validateSpeech: true
},
metrics: {
trackConfidence: true,
trackLatency: true,
trackAccuracy: true
}
};
错误处理和重试
自动重试
bash
# 重试配置
TRANSCRIPTION_RETRY_ATTEMPTS=3
RETRY_DELAY=1000 # 1秒
RETRY_BACKOFF_FACTOR=2
# 错误处理
ENABLE_FALLBACK_MODEL=true
FALLBACK_MODEL=whisper-base
错误恢复
javascript
// 错误恢复策略
async function robustTranscription(audioFile, options = {}) {
const maxRetries = 3;
for (let i = 0; i < maxRetries; i++) {
try {
return await transcribeAudio(audioFile, options);
} catch (error) {
if (i === maxRetries - 1) {
// 使用备用模型
return await transcribeWithFallback(audioFile, options);
}
await sleep(Math.pow(2, i) * 1000);
}
}
}
监控与分析
使用监控
基础监控
bash
# 转录监控
ENABLE_TRANSCRIPTION_METRICS=true
METRICS_COLLECTION_INTERVAL=60000 # 1分钟
# 监控指标
TRACK_TRANSCRIPTION_LATENCY=true
TRACK_TRANSCRIPTION_ACCURACY=true
TRACK_AUDIO_QUALITY=true
详细分析
javascript
// 转录分析配置
const transcriptionAnalytics = {
enabled: true,
metrics: {
latency: true,
accuracy: true,
confidence: true,
audioQuality: true,
languageDetection: true
},
reporting: {
interval: 3600000, // 1小时
format: 'json',
destination: '/var/log/transcription-metrics.log'
}
};
性能基准测试
速度测试
bash
# 转录速度测试
time curl -X POST http://localhost:3001/api/transcribe \
-F "audio=@test-audio.wav" \
-F "language=zh"
准确性测试
javascript
// 准确性测试
async function testTranscriptionAccuracy() {
const testCases = [
{ audio: 'test1.wav', expected: '这是一个测试录音' },
{ audio: 'test2.wav', expected: 'This is a test recording' }
];
for (const testCase of testCases) {
const result = await transcribeAudio(testCase.audio);
const accuracy = calculateAccuracy(result.text, testCase.expected);
console.log(`Accuracy for ${testCase.audio}: ${accuracy}%`);
}
}
故障排除
常见问题
转录失败
bash
# 检查音频文件
file audio.wav
ffprobe -v quiet -print_format json -show_format audio.wav
# 检查模型状态
curl -X GET http://localhost:3001/api/transcribe/health
质量问题
bash
# 音频质量检查
ffmpeg -i input.wav -af "volumedetect" -f null -
# 转录质量分析
curl -X POST http://localhost:3001/api/transcribe/analyze \
-F "audio=@audio.wav"
性能问题
bash
# 检查系统资源
top -p $(pgrep -f whisper)
nvidia-smi # 如果使用GPU
# 监控转录队列
curl -X GET http://localhost:3001/api/transcribe/queue/status
调试工具
音频分析工具
javascript
// 音频质量分析
async function analyzeAudioQuality(audioFile) {
const analysis = await analyzeAudio(audioFile);
console.log(`Duration: ${analysis.duration}s`);
console.log(`Sample Rate: ${analysis.sampleRate}Hz`);
console.log(`Channels: ${analysis.channels}`);
console.log(`Bit Depth: ${analysis.bitDepth}`);
console.log(`SNR: ${analysis.snr}dB`);
return analysis;
}
转录调试
javascript
// 转录调试工具
async function debugTranscription(audioFile) {
const startTime = Date.now();
try {
const result = await transcribeAudio(audioFile, {
debug: true,
returnConfidence: true,
returnTimestamps: true
});
const endTime = Date.now();
const duration = endTime - startTime;
console.log(`Transcription completed in ${duration}ms`);
console.log(`Text: ${result.text}`);
console.log(`Confidence: ${result.confidence}`);
console.log(`Language: ${result.language}`);
return result;
} catch (error) {
console.error(`Transcription failed: ${error.message}`);
throw error;
}
}
最佳实践
生产部署
配置检查清单
- [ ] 转录模型已选择并测试
- [ ] API密钥已设置且有效
- [ ] 音频格式支持已配置
- [ ] 质量阈值已设置
- [ ] 监控已启用
- [ ] 错误处理已配置
- [ ] 性能基准已建立
性能优化建议
- 根据音频类型选择合适的模型
- 启用音频预处理提高质量
- 使用适当的并行处理配置
- 监控转录质量和性能
- 实施智能缓存策略
成本控制
- 使用本地模型减少API调用
- 优化音频质量减少重试
- 实施批量处理
- 监控API使用量
开发建议
测试策略
javascript
// 转录测试套件
describe('Transcription Integration', () => {
test('audio transcription', async () => {
const result = await transcribeAudio('test.wav');
expect(result.text).toBeDefined();
expect(result.confidence).toBeGreaterThan(0.7);
});
test('language detection', async () => {
const result = await transcribeAudio('chinese.wav');
expect(result.language).toBe('zh');
});
test('real-time transcription', async () => {
const stream = createAudioStream();
const transcription = await transcribeStream(stream);
expect(transcription).toBeDefined();
});
});
错误处理
javascript
// 健壮的转录处理
async function safeTranscription(audioFile) {
try {
// 预检查音频质量
const quality = await checkAudioQuality(audioFile);
if (quality.score < 0.5) {
audioFile = await enhanceAudio(audioFile);
}
return await transcribeAudio(audioFile);
} catch (error) {
if (error.code === 'audio_too_long') {
return await transcribeInChunks(audioFile);
}
// 使用备用模型
return await transcribeWithFallback(audioFile);
}
}
通过合理配置和优化转录模型,您可以为AnythingLLM添加强大的音频处理能力,使音频和视频内容也能被有效地搜索和分析。记住要根据具体的音频类型和质量要求选择最适合的转录模型和配置参数。