aws transcribe fiels added

This commit is contained in:
rahulpscraftech360 2025-08-29 05:42:33 +00:00
parent bb279a77e7
commit 1a6b7e7d48
7 changed files with 1149 additions and 3 deletions

View file

@ -21,7 +21,7 @@ Vue 3.x
# API Documentation
After starting, open: http://localhost:8002/xiaozhi/doc.html
run app
to run app
npm run serve
mvn spring-boot:run

View file

@ -0,0 +1,274 @@
import os
import time
import asyncio
import boto3
import json
from botocore.exceptions import ClientError, NoCredentialsError
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class ASRProvider(ASRProviderBase):
"""
Amazon Transcribe ASR Provider
Uses Amazon Transcribe service for speech-to-text transcription
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__(config)
self.interface_type = InterfaceType.NON_STREAM
# AWS Configuration
self.aws_access_key_id = config.get("aws_access_key_id")
self.aws_secret_access_key = config.get("aws_secret_access_key")
self.aws_region = config.get("aws_region", "us-east-1")
self.s3_bucket = config.get("s3_bucket")
# Transcription Configuration
self.language_code = config.get("language_code", "en-US")
self.sample_rate = config.get("sample_rate", 16000)
self.media_format = config.get("media_format", "wav")
self.vocabulary_name = config.get("vocabulary_name") # Optional custom vocabulary
self.vocabulary_filter_name = config.get("vocabulary_filter_name") # Optional vocabulary filter
# File management
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
self.s3_key_prefix = config.get("s3_key_prefix", "xiaozhi-audio/")
# Timeout configuration
timeout = config.get("timeout", 60)
self.timeout = int(timeout) if timeout else 60
# Initialize AWS clients
try:
session = boto3.Session(
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
region_name=self.aws_region
)
self.transcribe_client = session.client('transcribe')
self.s3_client = session.client('s3')
# Test S3 bucket access
self._test_s3_access()
except NoCredentialsError:
logger.bind(tag=TAG).error("AWS credentials not found. Please configure aws_access_key_id and aws_secret_access_key")
raise
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to initialize AWS clients: {e}")
raise
# Ensure output directory exists
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
logger.bind(tag=TAG).info(
f"Amazon Transcribe ASR initialized - Region: {self.aws_region}, "
f"Language: {self.language_code}, S3 Bucket: {self.s3_bucket}"
)
def _test_s3_access(self):
"""Test S3 bucket access"""
try:
self.s3_client.head_bucket(Bucket=self.s3_bucket)
logger.bind(tag=TAG).info(f"S3 bucket '{self.s3_bucket}' is accessible")
except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == '404':
logger.bind(tag=TAG).error(f"S3 bucket '{self.s3_bucket}' does not exist")
elif error_code == '403':
logger.bind(tag=TAG).error(f"Access denied to S3 bucket '{self.s3_bucket}'")
else:
logger.bind(tag=TAG).error(f"Error accessing S3 bucket: {e}")
raise
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using Amazon Transcribe"""
start_time = time.time()
audio_file_path = None
s3_key = None
job_name = None
try:
# Decode Opus to PCM if needed
if audio_format == "opus":
pcm_data = self.decode_opus(opus_data)
if not pcm_data:
logger.bind(tag=TAG).error("Failed to decode Opus audio")
return None, None
else:
pcm_data = opus_data
# Save audio to temporary file
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Calculate audio length for logging
audio_length_seconds = len(b"".join(pcm_data)) / (self.sample_rate * 2) # 16-bit audio
# Upload audio file to S3
s3_key = f"{self.s3_key_prefix}{session_id}_{int(time.time())}.wav"
try:
self.s3_client.upload_file(audio_file_path, self.s3_bucket, s3_key)
logger.bind(tag=TAG).debug(f"Uploaded audio to S3: s3://{self.s3_bucket}/{s3_key}")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to upload to S3: {e}")
return None, audio_file_path
# Create unique job name
job_name = f"xiaozhi-transcription-{session_id}-{int(time.time())}"
# Start transcription job
media_uri = f"s3://{self.s3_bucket}/{s3_key}"
job_args = {
'TranscriptionJobName': job_name,
'Media': {'MediaFileUri': media_uri},
'MediaFormat': self.media_format,
'LanguageCode': self.language_code,
'MediaSampleRateHertz': self.sample_rate
}
# Add optional parameters
if self.vocabulary_name:
job_args['Settings'] = job_args.get('Settings', {})
job_args['Settings']['VocabularyName'] = self.vocabulary_name
if self.vocabulary_filter_name:
job_args['Settings'] = job_args.get('Settings', {})
job_args['Settings']['VocabularyFilterName'] = self.vocabulary_filter_name
job_args['Settings']['VocabularyFilterMethod'] = 'remove'
# Start the transcription job
response = self.transcribe_client.start_transcription_job(**job_args)
logger.bind(tag=TAG).debug(f"Started transcription job: {job_name}")
# Poll for job completion
result_text = await self._wait_for_job_completion(job_name)
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Amazon Transcribe completed in {elapsed_time:.2f}s: {result_text}"
)
# Log the transcript for debugging/analysis
if result_text:
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
return result_text, audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
return None, audio_file_path
finally:
# Clean up audio file if configured
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
try:
os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
# Clean up AWS resources
await self._cleanup_aws_resources(job_name, s3_key)
async def _wait_for_job_completion(self, job_name: str) -> Optional[str]:
"""Wait for transcription job to complete and return the result"""
start_time = time.time()
while time.time() - start_time < self.timeout:
try:
response = self.transcribe_client.get_transcription_job(
TranscriptionJobName=job_name
)
status = response['TranscriptionJob']['TranscriptionJobStatus']
if status == 'COMPLETED':
# Get the transcript
transcript_uri = response['TranscriptionJob']['Transcript']['TranscriptFileUri']
return await self._fetch_transcript_from_uri(transcript_uri)
elif status == 'FAILED':
failure_reason = response['TranscriptionJob'].get('FailureReason', 'Unknown error')
logger.bind(tag=TAG).error(f"Transcription job failed: {failure_reason}")
return None
elif status in ['QUEUED', 'IN_PROGRESS']:
# Wait before checking again
await asyncio.sleep(1)
continue
except Exception as e:
logger.bind(tag=TAG).error(f"Error checking job status: {e}")
return None
logger.bind(tag=TAG).error(f"Transcription job timed out after {self.timeout} seconds")
return None
async def _fetch_transcript_from_uri(self, transcript_uri: str) -> Optional[str]:
"""Fetch transcript content from the provided URI"""
try:
import urllib.request
import json
# Use asyncio to run the blocking operation in a thread
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None, urllib.request.urlopen, transcript_uri
)
transcript_data = json.loads(response.read().decode('utf-8'))
# Extract the transcript text
results = transcript_data.get('results', {})
transcripts = results.get('transcripts', [])
if transcripts and len(transcripts) > 0:
return transcripts[0].get('transcript', '')
else:
logger.bind(tag=TAG).warning("No transcript found in response")
return ''
except Exception as e:
logger.bind(tag=TAG).error(f"Error fetching transcript: {e}")
return None
async def _cleanup_aws_resources(self, job_name: str, s3_key: str):
"""Clean up AWS resources"""
try:
# Delete transcription job (optional, jobs auto-delete after 90 days)
if job_name:
try:
self.transcribe_client.delete_transcription_job(
TranscriptionJobName=job_name
)
logger.bind(tag=TAG).debug(f"Deleted transcription job: {job_name}")
except ClientError as e:
# Job might not exist or already deleted
if e.response['Error']['Code'] != 'BadRequestException':
logger.bind(tag=TAG).warning(f"Could not delete job {job_name}: {e}")
# Delete S3 object
if s3_key:
try:
self.s3_client.delete_object(Bucket=self.s3_bucket, Key=s3_key)
logger.bind(tag=TAG).debug(f"Deleted S3 object: {s3_key}")
except ClientError as e:
logger.bind(tag=TAG).warning(f"Could not delete S3 object {s3_key}: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error during cleanup: {e}")

View file

@ -0,0 +1,330 @@
import os
import time
import asyncio
import boto3
from amazon_transcribe.client import TranscribeStreamingClient
from amazon_transcribe.handlers import TranscriptResultStreamHandler
from amazon_transcribe.model import TranscriptEvent, Result
from botocore.exceptions import ClientError, NoCredentialsError
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class MyEventHandler(TranscriptResultStreamHandler):
"""Custom handler for Amazon Transcribe streaming events"""
def __init__(self, output_stream):
super().__init__(output_stream)
self.transcript_parts = []
self.final_transcript = ""
self.detected_language = None
self.language_confidence = None
self.is_complete = False
async def handle_transcript_event(self, transcript_event: TranscriptEvent):
"""Handle incoming transcript events"""
try:
results = transcript_event.transcript.results
for result in results:
# Extract language identification if available
if hasattr(result, 'language_identification') and result.language_identification:
for lang_id in result.language_identification:
if hasattr(lang_id, 'language_code'):
self.detected_language = lang_id.language_code
if hasattr(lang_id, 'score'):
self.language_confidence = lang_id.score
logger.bind(tag=TAG).debug(f"Language detected: {self.detected_language} (confidence: {self.language_confidence})")
if not result.is_partial:
# Final result
for alt in result.alternatives:
text = alt.transcript.strip()
if text:
self.transcript_parts.append(text)
logger.bind(tag=TAG).debug(f"Final transcript part: {text}")
else:
# Partial result (for real-time feedback)
for alt in result.alternatives:
text = alt.transcript.strip()
if text:
logger.bind(tag=TAG).debug(f"Partial transcript: {text}")
# Combine all final parts
if self.transcript_parts:
self.final_transcript = " ".join(self.transcript_parts)
except Exception as e:
logger.bind(tag=TAG).error(f"Error handling transcript event: {e}")
class ASRProvider(ASRProviderBase):
"""
Amazon Transcribe Real-time Streaming ASR Provider
Uses Amazon Transcribe Streaming for true real-time speech recognition
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__(config)
self.interface_type = InterfaceType.NON_STREAM
# AWS Configuration
self.aws_access_key_id = config.get("aws_access_key_id")
self.aws_secret_access_key = config.get("aws_secret_access_key")
self.aws_region = config.get("aws_region", "us-east-1")
# Multi-language Configuration for India
self.language_code = config.get("language_code", "en-IN")
self.sample_rate = config.get("sample_rate", 16000)
self.media_encoding = "pcm" # Fixed for streaming
# Indian languages supported by Amazon Transcribe
self.supported_indian_languages = {
"hi-IN": "Hindi",
"bn-IN": "Bengali",
"te-IN": "Telugu",
"ta-IN": "Tamil",
"gu-IN": "Gujarati",
"kn-IN": "Kannada",
"ml-IN": "Malayalam",
"mr-IN": "Marathi",
"pa-IN": "Punjabi",
"en-IN": "English (India)"
}
# Multi-language detection settings - temporarily disabled due to API conflicts
self.enable_language_detection = config.get("enable_language_detection", False)
self.romanized_output = config.get("romanized_output", True)
# File management
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
# Timeout configuration (short for real-time)
timeout = config.get("timeout", 10)
self.timeout = int(timeout) if timeout else 10
# Test AWS credentials
try:
session = boto3.Session(
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
region_name=self.aws_region
)
# Test credentials
sts_client = session.client('sts')
sts_client.get_caller_identity()
logger.bind(tag=TAG).info("AWS credentials verified successfully")
except NoCredentialsError:
logger.bind(tag=TAG).error("AWS credentials not found")
raise
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to verify AWS credentials: {e}")
raise
# Ensure output directory exists
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
logger.bind(tag=TAG).info(
f"Amazon Transcribe Real-time ASR initialized - Region: {self.aws_region}, "
f"Language: {self.language_code}, Sample Rate: {self.sample_rate}"
)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using Amazon Transcribe Streaming"""
start_time = time.time()
audio_file_path = None
try:
# Decode Opus to PCM if needed
if audio_format == "opus":
pcm_data = self.decode_opus(opus_data)
if not pcm_data:
logger.bind(tag=TAG).error("Failed to decode Opus audio")
return None, None
else:
pcm_data = opus_data
# Save audio to temporary file for logging
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Calculate audio length for logging
combined_pcm_data = b"".join(pcm_data)
audio_length_seconds = len(combined_pcm_data) / (self.sample_rate * 2)
# Perform real-time streaming transcription
result_text = await self._stream_transcribe(combined_pcm_data)
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Amazon Transcribe Real-time completed in {elapsed_time:.2f}s: {result_text}"
)
# Log the transcript
if result_text:
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
return result_text, audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
return None, audio_file_path
finally:
# Clean up audio file if configured
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
try:
os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
async def _stream_transcribe(self, pcm_data: bytes) -> Optional[str]:
"""Perform real-time streaming transcription with language detection"""
try:
# Create streaming client
client = TranscribeStreamingClient(region=self.aws_region)
# Configure streaming parameters
stream_params = {
'media_sample_rate_hz': self.sample_rate,
'media_encoding': self.media_encoding,
}
# Use specific language for now (language detection has API conflicts)
stream_params['language_code'] = self.language_code
logger.bind(tag=TAG).info(f"Using specific language: {self.language_code}")
# Start streaming transcription
stream = await client.start_stream_transcription(**stream_params)
# Create handler for the stream
handler = MyEventHandler(stream.output_stream)
# Send audio in chunks
await self._send_audio_chunks(stream, pcm_data)
# Process the stream
await self._process_stream(stream, handler)
# Get the final transcript
final_text = handler.final_transcript.strip()
detected_language = getattr(handler, 'detected_language', self.language_code)
# Process romanized output if requested
if final_text and self.romanized_output:
final_text = await self._process_romanized_output(final_text, detected_language)
# Log detected language
if detected_language and detected_language != self.language_code:
language_name = self.supported_indian_languages.get(detected_language, detected_language)
logger.bind(tag=TAG).info(f"Detected language: {language_name} ({detected_language})")
return final_text if final_text else None
except Exception as e:
logger.bind(tag=TAG).error(f"Streaming transcription error: {e}")
return None
async def _send_audio_chunks(self, stream, pcm_data: bytes):
"""Send audio data in chunks to the streaming API"""
try:
chunk_size = 1024 * 4 # 4KB chunks
for i in range(0, len(pcm_data), chunk_size):
chunk = pcm_data[i:i + chunk_size]
await stream.input_stream.send_audio_event(audio_chunk=chunk)
await asyncio.sleep(0.01) # Small delay for streaming
# End the audio stream
await stream.input_stream.end_stream()
logger.bind(tag=TAG).debug("Audio streaming completed")
except Exception as e:
logger.bind(tag=TAG).error(f"Error sending audio chunks: {e}")
async def _process_stream(self, stream, handler):
"""Process the transcript stream"""
try:
# Process events with timeout
async def process_events():
async for event in stream.output_stream:
await handler.handle_transcript_event(event)
# Break if we have a complete transcript
if handler.final_transcript:
break
# Wait for processing with timeout
await asyncio.wait_for(process_events(), timeout=self.timeout)
except asyncio.TimeoutError:
logger.bind(tag=TAG).warning(f"Stream processing timed out after {self.timeout}s")
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing stream: {e}")
async def _process_romanized_output(self, text: str, language_code: str) -> str:
"""Process text to ensure romanized output for Indian languages"""
try:
# Amazon Transcribe already provides romanized output for Indian languages
# But we can add additional processing if needed
language_name = self.supported_indian_languages.get(language_code, "Unknown")
# Log the language detected
logger.bind(tag=TAG).info(f"Romanized {language_name} output: {text}")
# Add language indicator to the output if it's not English
if language_code != "en-IN" and language_code in self.supported_indian_languages:
# Optionally prefix with language indicator
# return f"[{language_name}] {text}"
return text # Return as-is since Amazon Transcribe provides romanized output
return text
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing romanized output: {e}")
return text
async def _simple_chunk_transcribe(self, pcm_data: bytes) -> Optional[str]:
"""Fallback: Simple chunked approach for better reliability"""
try:
# This is a more reliable approach that processes smaller chunks
# and combines results, mimicking real-time performance
chunk_size = len(pcm_data) // 3 # Split into 3 parts
if chunk_size < 1600: # Minimum chunk size
chunk_size = len(pcm_data)
results = []
for i in range(0, len(pcm_data), chunk_size):
chunk = pcm_data[i:i + chunk_size]
if len(chunk) < 800: # Skip very small chunks
continue
# Process chunk (simplified for reliability)
# In a full implementation, you'd send each chunk to streaming API
await asyncio.sleep(0.1) # Simulate processing time
# For now, return a simple acknowledgment that we received audio
# This can be enhanced with actual streaming implementation
if len(pcm_data) > 1600:
return "I heard you speaking" # Placeholder until full streaming is implemented
else:
return None
except Exception as e:
logger.bind(tag=TAG).error(f"Simple chunk transcribe error: {e}")
return None

View file

@ -0,0 +1,247 @@
import os
import time
import asyncio
import boto3
import json
from amazon_transcribe.client import TranscribeStreamingClient
from amazon_transcribe.handlers import TranscriptResultStreamHandler
from amazon_transcribe.model import TranscriptEvent
from botocore.exceptions import ClientError, NoCredentialsError
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class TranscriptEventHandler(TranscriptResultStreamHandler):
"""Handler for Amazon Transcribe streaming events"""
def __init__(self):
super().__init__()
self.transcript_text = ""
self.is_final = False
self.completed = False
async def handle_transcript_event(self, transcript_event: TranscriptEvent):
results = transcript_event.transcript.results
for result in results:
if result.is_partial:
# Handle partial results for real-time feedback
for alt in result.alternatives:
logger.bind(tag=TAG).debug(f"Partial transcript: {alt.transcript}")
else:
# Handle final results
for alt in result.alternatives:
self.transcript_text += alt.transcript + " "
logger.bind(tag=TAG).debug(f"Final transcript: {alt.transcript}")
self.is_final = True
# Check if stream is complete
if not results:
self.completed = True
class ASRProvider(ASRProviderBase):
"""
Amazon Transcribe Streaming ASR Provider
Uses Amazon Transcribe Streaming service for real-time speech-to-text
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__(config)
self.interface_type = InterfaceType.NON_STREAM # Keep as non-stream for compatibility
# AWS Configuration
self.aws_access_key_id = config.get("aws_access_key_id")
self.aws_secret_access_key = config.get("aws_secret_access_key")
self.aws_region = config.get("aws_region", "us-east-1")
# Transcription Configuration
self.language_code = config.get("language_code", "en-US")
self.sample_rate = config.get("sample_rate", 16000)
self.media_encoding = config.get("media_encoding", "pcm")
# File management
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
# Timeout configuration
timeout = config.get("timeout", 30)
self.timeout = int(timeout) if timeout else 30
# Initialize AWS session
try:
self.session = boto3.Session(
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
region_name=self.aws_region
)
# Test credentials
sts_client = self.session.client('sts')
sts_client.get_caller_identity()
except NoCredentialsError:
logger.bind(tag=TAG).error("AWS credentials not found. Please configure aws_access_key_id and aws_secret_access_key")
raise
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to initialize AWS session: {e}")
raise
# Ensure output directory exists
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
logger.bind(tag=TAG).info(
f"Amazon Transcribe Streaming ASR initialized - Region: {self.aws_region}, "
f"Language: {self.language_code}, Sample Rate: {self.sample_rate}"
)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using Amazon Transcribe Streaming"""
start_time = time.time()
audio_file_path = None
try:
# Decode Opus to PCM if needed
if audio_format == "opus":
pcm_data = self.decode_opus(opus_data)
if not pcm_data:
logger.bind(tag=TAG).error("Failed to decode Opus audio")
return None, None
else:
pcm_data = opus_data
# Save audio to temporary file for debugging/logging
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Calculate audio length for logging
combined_pcm_data = b"".join(pcm_data)
audio_length_seconds = len(combined_pcm_data) / (self.sample_rate * 2) # 16-bit audio
# Perform streaming transcription
result_text = await self._stream_transcribe(combined_pcm_data)
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Amazon Transcribe Streaming completed in {elapsed_time:.2f}s: {result_text}"
)
# Log the transcript for debugging/analysis
if result_text:
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
return result_text, audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
return None, audio_file_path
finally:
# Clean up audio file if configured
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
try:
os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
async def _stream_transcribe(self, pcm_data: bytes) -> Optional[str]:
"""Perform streaming transcription"""
try:
# Create streaming client
client = TranscribeStreamingClient(region=self.aws_region)
# Create event handler
handler = TranscriptEventHandler()
# Create audio stream generator
async def audio_generator():
# Split audio into chunks for streaming
chunk_size = 1024 * 8 # 8KB chunks
for i in range(0, len(pcm_data), chunk_size):
chunk = pcm_data[i:i + chunk_size]
yield {"AudioEvent": {"AudioChunk": chunk}}
await asyncio.sleep(0.01) # Small delay to simulate streaming
# Start streaming transcription
stream = await client.start_stream_transcription(
language_code=self.language_code,
media_sample_rate_hz=self.sample_rate,
media_encoding=self.media_encoding,
)
# Set up the event handler
async def handle_stream():
async for event in stream.output_stream:
await handler.handle_transcript_event(event)
if handler.completed:
break
# Send audio and handle responses concurrently
tasks = [
asyncio.create_task(stream.input_stream.send_audio_event(audio_generator())),
asyncio.create_task(handle_stream())
]
# Wait for completion with timeout
try:
await asyncio.wait_for(
asyncio.gather(*tasks, return_exceptions=True),
timeout=self.timeout
)
except asyncio.TimeoutError:
logger.bind(tag=TAG).warning(f"Streaming transcription timed out after {self.timeout}s")
return None
# End the stream
await stream.input_stream.end_stream()
# Return the final transcript
final_text = handler.transcript_text.strip()
return final_text if final_text else None
except Exception as e:
logger.bind(tag=TAG).error(f"Streaming transcription error: {e}")
return None
async def _simple_transcribe(self, pcm_data: bytes) -> Optional[str]:
"""Fallback: Simple in-memory transcription without actual streaming"""
try:
# This is a simplified approach that processes the entire audio at once
# but uses the streaming client for better performance than file-based
client = TranscribeStreamingClient(region=self.aws_region)
# Create a simple audio event
audio_event = {
"AudioEvent": {
"AudioChunk": pcm_data
}
}
# For now, let's use a simpler approach
# In a real implementation, you'd want proper streaming
# But this gives us the performance benefits without the complexity
# Simulate processing time (much faster than file-based)
await asyncio.sleep(0.5) # Much faster than 26 seconds!
# Return a placeholder - in reality you'd implement proper streaming
# For now, let's fall back to a simple mock for testing
logger.bind(tag=TAG).info("Using simplified streaming transcription")
# This is where you'd implement the actual streaming logic
# For now, return None to indicate we need the full implementation
return None
except Exception as e:
logger.bind(tag=TAG).error(f"Simple transcription error: {e}")
return None

View file

@ -0,0 +1,254 @@
import os
import time
import asyncio
import boto3
import tempfile
import uuid
from botocore.exceptions import ClientError, NoCredentialsError
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class ASRProvider(ASRProviderBase):
"""
Amazon Transcribe Streaming ASR Provider (Simplified)
Uses a simplified approach for faster transcription than file-based
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__(config)
self.interface_type = InterfaceType.NON_STREAM
# AWS Configuration
self.aws_access_key_id = config.get("aws_access_key_id")
self.aws_secret_access_key = config.get("aws_secret_access_key")
self.aws_region = config.get("aws_region", "us-east-1")
# Transcription Configuration
self.language_code = config.get("language_code", "en-US")
self.sample_rate = config.get("sample_rate", 16000)
# File management
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
# Timeout configuration (much shorter for streaming)
timeout = config.get("timeout", 10)
self.timeout = int(timeout) if timeout else 10
# Initialize AWS clients
try:
session = boto3.Session(
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
region_name=self.aws_region
)
# Test credentials
sts_client = session.client('sts')
sts_client.get_caller_identity()
# Create transcribe client for potential future streaming
self.transcribe_client = session.client('transcribe')
except NoCredentialsError:
logger.bind(tag=TAG).error("AWS credentials not found. Please configure aws_access_key_id and aws_secret_access_key")
raise
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to initialize AWS clients: {e}")
raise
# Ensure output directory exists
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
logger.bind(tag=TAG).info(
f"Amazon Transcribe Streaming ASR initialized - Region: {self.aws_region}, "
f"Language: {self.language_code}, Timeout: {self.timeout}s"
)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using simplified streaming approach"""
start_time = time.time()
audio_file_path = None
try:
# Decode Opus to PCM if needed
if audio_format == "opus":
pcm_data = self.decode_opus(opus_data)
if not pcm_data:
logger.bind(tag=TAG).error("Failed to decode Opus audio")
return None, None
else:
pcm_data = opus_data
# Save audio to temporary file
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Calculate audio length for logging
audio_length_seconds = len(b"".join(pcm_data)) / (self.sample_rate * 2) # 16-bit audio
# Perform fast transcription (simulate streaming performance)
result_text = await self._fast_transcribe(pcm_data)
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Amazon Transcribe Streaming completed in {elapsed_time:.2f}s: {result_text}"
)
# Log the transcript for debugging/analysis
if result_text:
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
return result_text, audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
return None, audio_file_path
finally:
# Clean up audio file if configured
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
try:
os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
async def _fast_transcribe(self, pcm_data: List[bytes]) -> Optional[str]:
"""Real Amazon Transcribe using start_transcription_job but optimized"""
try:
# Create temporary file for transcription
combined_data = b"".join(pcm_data)
# Create temporary WAV file in memory-like approach
temp_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
try:
# Write WAV header and data
import wave
with wave.open(temp_file.name, 'wb') as wav_file:
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(self.sample_rate) # Sample rate
wav_file.writeframes(combined_data)
# Use start_transcription_job for real transcription
job_name = f"xiaozhi-stream-{uuid.uuid4().hex[:8]}-{int(time.time())}"
# Upload to S3 first (required for Transcribe)
# But use a much more optimized approach
import boto3
s3_client = boto3.client(
's3',
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
region_name=self.aws_region
)
# Create a temporary bucket key
s3_key = f"temp-audio/{job_name}.wav"
s3_bucket = "cheeko-audio-files" # Use existing bucket
# Quick upload
s3_client.upload_file(temp_file.name, s3_bucket, s3_key)
# Start transcription job
response = self.transcribe_client.start_transcription_job(
TranscriptionJobName=job_name,
Media={'MediaFileUri': f's3://{s3_bucket}/{s3_key}'},
MediaFormat='wav',
LanguageCode=self.language_code,
MediaSampleRateHertz=self.sample_rate
)
# Poll for completion (optimized for speed)
max_attempts = self.timeout # Use timeout as max attempts (1 per second)
for attempt in range(max_attempts):
await asyncio.sleep(1) # Wait 1 second between checks
job_response = self.transcribe_client.get_transcription_job(
TranscriptionJobName=job_name
)
status = job_response['TranscriptionJob']['TranscriptionJobStatus']
if status == 'COMPLETED':
# Get transcript
transcript_uri = job_response['TranscriptionJob']['Transcript']['TranscriptFileUri']
# Download and parse transcript
import urllib.request
import json
response = urllib.request.urlopen(transcript_uri)
transcript_data = json.loads(response.read().decode('utf-8'))
# Extract text
results = transcript_data.get('results', {})
transcripts = results.get('transcripts', [])
if transcripts and len(transcripts) > 0:
final_text = transcripts[0].get('transcript', '')
# Cleanup job and S3 object
try:
self.transcribe_client.delete_transcription_job(
TranscriptionJobName=job_name
)
s3_client.delete_object(Bucket=s3_bucket, Key=s3_key)
except:
pass # Ignore cleanup errors
return final_text
else:
return None
elif status == 'FAILED':
failure_reason = job_response['TranscriptionJob'].get('FailureReason', 'Unknown error')
logger.bind(tag=TAG).error(f"Transcription failed: {failure_reason}")
return None
# Timeout
logger.bind(tag=TAG).warning(f"Transcription timed out after {self.timeout} seconds")
return None
finally:
# Clean up temporary file
try:
os.unlink(temp_file.name)
except:
pass
except Exception as e:
logger.bind(tag=TAG).error(f"Real transcription error: {e}")
return None
async def _future_streaming_implementation(self, pcm_data: List[bytes]) -> Optional[str]:
"""Placeholder for future true streaming implementation"""
# This is where you would implement the actual Amazon Transcribe Streaming
# For now, we're using the mock above to test the integration
try:
# Future implementation would:
# 1. Create TranscribeStreamingClient
# 2. Set up audio stream
# 3. Process results in real-time
# 4. Return final transcript
# Placeholder implementation
logger.bind(tag=TAG).debug("Future streaming implementation called")
return None
except Exception as e:
logger.bind(tag=TAG).error(f"Streaming implementation error: {e}")
return None

View file

@ -35,7 +35,7 @@ PyJWT==2.8.0
psutil==7.0.0
portalocker==2.10.1
Jinja2==3.1.6
ten-vad==0.2.0
deepgram-sdk==4.8.1
fuzzywuzzy
Levenshtein

41
requirements.txt Normal file
View file

@ -0,0 +1,41 @@
pyyml==0.0.2
torch
silero_vad==5.1.2
websockets==14.2
opuslib_next==1.1.2
numpy==1.26.4
pydub==0.25.1
funasr==1.2.3
torchaudio
openai==1.61.0
google-generativeai==0.8.4
edge_tts==7.0.0
httpx==0.27.2
aiohttp==3.9.3
aiohttp_cors==0.7.0
ormsgpack==1.7.0
ruamel.yaml==0.18.10
loguru==0.7.3
requests==2.32.3
cozepy==0.12.0
mem0ai==0.1.62
bs4==0.0.2
modelscope==1.23.2
sherpa_onnx==1.12.8
mcp==1.8.1
cnlunar==0.2.0
PySocks==1.7.1
dashscope==1.23.1
baidu-aip==4.16.13
chardet==5.2.0
aioconsole==0.8.1
markitdown==0.1.1
mcp-proxy==0.8.0
PyJWT==2.8.0
psutil==7.0.0
portalocker==2.10.1
Jinja2==3.1.6
deepgram-sdk==4.8.1
fuzzywuzzy
Levenshtein