From 61546bec42e4fa2a63ab6597ee0ab48b860685d1 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Fri, 29 Aug 2025 14:18:27 +0530 Subject: [PATCH] debug addded for timer --- check_database_structure.py | 186 ++++++++++++++++++ ...291530_add_amazon_transcribe_streaming.sql | 27 +++ .../db/changelog/db.changelog-master.yaml | 7 + main/xiaozhi-server/client.py | 6 +- main/xiaozhi-server/core/connection.py | 3 + .../core/handle/receiveAudioHandle.py | 7 + .../core/providers/asr/amazon_transcribe.py | 2 +- .../asr/amazon_transcribe_realtime.py | 9 +- .../asr/amazon_transcribe_streaming.py | 2 +- .../asr/amazon_transcribe_streaming_simple.py | 2 +- .../xiaozhi-server/core/providers/asr/base.py | 26 +++ 11 files changed, 268 insertions(+), 9 deletions(-) create mode 100644 check_database_structure.py create mode 100644 main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql diff --git a/check_database_structure.py b/check_database_structure.py new file mode 100644 index 000000000..d0035451a --- /dev/null +++ b/check_database_structure.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +""" +Script to check the ai_model_provider table structure and existing ASR services +""" + +import mysql.connector +from mysql.connector import Error +import json +from tabulate import tabulate + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect( + host='nozomi.proxy.rlwy.net', + port=25037, + database='railway', + user='root', + password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + charset='utf8mb4', + use_unicode=True, + ssl_disabled=True + ) + + if connection.is_connected(): + print("Successfully connected to Railway MySQL database") + return connection + + except Error as e: + print(f"Error connecting to MySQL: {e}") + return None + +def get_table_structure(connection, table_name): + """Get the structure of a table""" + cursor = connection.cursor() + try: + cursor.execute(f"DESCRIBE {table_name}") + columns = cursor.fetchall() + + print(f"\nStructure of table '{table_name}':") + headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] + print(tabulate(columns, headers=headers, tablefmt="grid")) + + return columns + + except Error as e: + print(f"Error getting table structure: {e}") + return None + finally: + cursor.close() + +def get_existing_asr_providers(connection): + """Get all existing ASR providers""" + cursor = connection.cursor() + try: + cursor.execute(""" + SELECT id, model_type, provider_code, name, LENGTH(id) as id_length + FROM ai_model_provider + WHERE model_type = 'ASR' + ORDER BY id + """) + providers = cursor.fetchall() + + print(f"\nExisting ASR providers:") + headers = ["ID", "Model Type", "Provider Code", "Name", "ID Length"] + print(tabulate(providers, headers=headers, tablefmt="grid")) + + return providers + + except Error as e: + print(f"Error getting ASR providers: {e}") + return None + finally: + cursor.close() + +def get_existing_asr_configs(connection): + """Get all existing ASR model configurations""" + cursor = connection.cursor() + try: + cursor.execute(""" + SELECT id, model_type, model_code, model_name, LENGTH(id) as id_length + FROM ai_model_config + WHERE model_type = 'ASR' + ORDER BY id + """) + configs = cursor.fetchall() + + print(f"\nExisting ASR model configurations:") + headers = ["ID", "Model Type", "Model Code", "Model Name", "ID Length"] + print(tabulate(configs, headers=headers, tablefmt="grid")) + + return configs + + except Error as e: + print(f"Error getting ASR configs: {e}") + return None + finally: + cursor.close() + +def analyze_id_constraints(providers, configs): + """Analyze ID length constraints""" + print(f"\nID Length Analysis:") + + if providers: + provider_lengths = [row[4] for row in providers] # ID length is 5th column + print(f"Provider ID lengths: {provider_lengths}") + print(f"Max provider ID length: {max(provider_lengths)}") + print(f"Min provider ID length: {min(provider_lengths)}") + + if configs: + config_lengths = [row[4] for row in configs] # ID length is 5th column + print(f"Config ID lengths: {config_lengths}") + print(f"Max config ID length: {max(config_lengths)}") + print(f"Min config ID length: {min(config_lengths)}") + + # Check our proposed ID + proposed_provider_id = "SYSTEM_ASR_AmazonTranscribeStreaming" + proposed_config_id = "ASR_AmazonTranscribeStreaming" + + print(f"\nOur proposed IDs:") + print(f"Provider ID: '{proposed_provider_id}' (length: {len(proposed_provider_id)})") + print(f"Config ID: '{proposed_config_id}' (length: {len(proposed_config_id)})") + + if providers and len(proposed_provider_id) > max(provider_lengths): + print(f"WARNING: Proposed provider ID is longer than existing max ({max(provider_lengths)})") + + if configs and len(proposed_config_id) > max(config_lengths): + print(f"WARNING: Proposed config ID is longer than existing max ({max(config_lengths)})") + +def suggest_shorter_ids(): + """Suggest shorter ID alternatives""" + print(f"\nSuggested shorter IDs:") + + alternatives = [ + ("SYSTEM_ASR_AmazonTS", "ASR_AmazonTS"), + ("SYSTEM_ASR_AwsTranscribe", "ASR_AwsTranscribe"), + ("SYSTEM_ASR_AmazonStream", "ASR_AmazonStream"), + ("SYSTEM_ASR_AWSStream", "ASR_AWSStream"), + ] + + headers = ["Provider ID", "Config ID", "Provider Length", "Config Length"] + rows = [] + for provider_id, config_id in alternatives: + rows.append([provider_id, config_id, len(provider_id), len(config_id)]) + + print(tabulate(rows, headers=headers, tablefmt="grid")) + +def main(): + print("Checking xiaozhi database structure for Amazon Transcribe integration") + print("=" * 70) + + # Connect to database + connection = connect_to_database() + if not connection: + return + + try: + # Get table structures + print("\n" + "="*50) + provider_structure = get_table_structure(connection, "ai_model_provider") + + print("\n" + "="*50) + config_structure = get_table_structure(connection, "ai_model_config") + + # Get existing ASR services + print("\n" + "="*50) + providers = get_existing_asr_providers(connection) + + print("\n" + "="*50) + configs = get_existing_asr_configs(connection) + + # Analyze constraints + print("\n" + "="*50) + analyze_id_constraints(providers, configs) + + # Suggest alternatives + print("\n" + "="*50) + suggest_shorter_ids() + + finally: + if connection.is_connected(): + connection.close() + print(f"\nMySQL connection closed") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql b/main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql new file mode 100644 index 000000000..417e38e7b --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql @@ -0,0 +1,27 @@ +-- Amazon Transcribe Streaming ASR provider and model configuration + +-- Add Amazon Transcribe Streaming real-time ASR provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_ASR_AmazonStreamASR'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +VALUES ('SYSTEM_ASR_AmazonStreamASR', 'ASR', 'amazon_transcribe_realtime', 'Amazon Transcribe Streaming', +'[{"key":"aws_access_key_id","label":"AWS Access Key ID","type":"string"},{"key":"aws_secret_access_key","label":"AWS Secret Access Key","type":"string"},{"key":"aws_region","label":"AWS Region","type":"string"},{"key":"language_code","label":"Default Language Code","type":"string"},{"key":"enable_language_detection","label":"Enable Language Detection","type":"boolean"},{"key":"use_multiple_languages","label":"Support Multiple Languages","type":"boolean"},{"key":"romanized_output","label":"Romanized Output","type":"boolean"},{"key":"sample_rate","label":"Sample Rate","type":"number"},{"key":"media_encoding","label":"Media Encoding","type":"string"},{"key":"output_dir","label":"Output Directory","type":"string"},{"key":"timeout","label":"Timeout (seconds)","type":"number"}]', +4, 1, NOW(), 1, NOW()); + +-- Add Amazon Transcribe Streaming model configuration +DELETE FROM `ai_model_config` WHERE id = 'ASR_AmazonStreamASR'; +INSERT INTO `ai_model_config` VALUES ('ASR_AmazonStreamASR', 'ASR', 'AmazonStreamASR', 'Amazon Transcribe Streaming', 0, 1, +'{"type": "amazon_transcribe_realtime", "aws_access_key_id": "", "aws_secret_access_key": "", "aws_region": "us-east-1", "language_code": "en-IN", "enable_language_detection": true, "use_multiple_languages": true, "romanized_output": true, "sample_rate": 16000, "media_encoding": "pcm", "output_dir": "tmp/", "timeout": 30}', +'https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html', +'Amazon Transcribe Streaming Configuration: +1. Real-time speech recognition with fast response (seconds) +2. Supports automatic language detection for all major Indian languages +3. Supported languages: Hindi, Bengali, Telugu, Tamil, Gujarati, Kannada, Malayalam, Marathi, Punjabi, English (India) +4. Can output romanized text for local languages +5. Supports speakers switching languages mid-conversation +6. Requires AWS credentials and appropriate IAM permissions +7. Real-time transcription is better suited for conversation scenarios than batch processing +Setup Steps: +1. Visit AWS Console: https://console.aws.amazon.com/ +2. Create IAM user and get access keys: https://console.aws.amazon.com/iam/home#/security_credentials +3. Add Amazon Transcribe permissions policy to the user', +4, NULL, NULL, NULL, NULL); \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index c73a9d933..6142d8901 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -324,3 +324,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202501230005_translate_sys_params.sql + - changeSet: + id: 202508291530 + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508291530_add_amazon_transcribe_streaming.sql diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index a63a11e7c..0b537e4f9 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -19,9 +19,9 @@ import opuslib # --- Configuration --- -SERVER_IP = "192.168.1.111" # !!! UPDATE with your server's local IP address !!! -OTA_PORT = 8003 -MQTT_BROKER_HOST = "192.168.1.111" # MQTT gateway IP +SERVER_IP = "139.59.7.72" # !!! UPDATE with your server's local IP address !!! +OTA_PORT = 8002 +MQTT_BROKER_HOST = "139.59.7.72" # MQTT gateway IP MQTT_BROKER_PORT = 1883 diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index d675562db..d4013834b 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1135,6 +1135,9 @@ class ConnectionHandler: # Clear ASR audio buffer to prevent processing leftover audio if hasattr(self, 'asr_audio'): self.asr_audio.clear() + # Reset VAD recording start time for 10-second timeout + if hasattr(self, 'vad_recording_start_time'): + delattr(self, 'vad_recording_start_time') # Clear ASR audio queue for this specific connection only if hasattr(self, 'asr_audio_queue'): # Empty the queue by getting all items without blocking diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index c049c12a3..83acb044e 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -28,6 +28,13 @@ async def handleAudioMessage(conn, audio): # Whether the current segment has someone speaking have_voice = conn.vad.is_vad(conn, audio) + + # Track when voice recording starts in auto VAD mode (for 10-second timeout) + if have_voice and not hasattr(conn, 'vad_recording_start_time'): + conn.vad_recording_start_time = time.time() + conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}") + elif have_voice and hasattr(conn, 'vad_recording_start_time'): + conn.logger.bind(tag=TAG).debug(f"VAD recording continues, started at: {conn.vad_recording_start_time}") # Check if this is the initial connection period (ignore first 1 second of audio) if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled: diff --git a/main/xiaozhi-server/core/providers/asr/amazon_transcribe.py b/main/xiaozhi-server/core/providers/asr/amazon_transcribe.py index 18f279c34..ab156d300 100644 --- a/main/xiaozhi-server/core/providers/asr/amazon_transcribe.py +++ b/main/xiaozhi-server/core/providers/asr/amazon_transcribe.py @@ -31,7 +31,7 @@ class ASRProvider(ASRProviderBase): # Transcription Configuration self.language_code = config.get("language_code", "en-US") - self.sample_rate = config.get("sample_rate", 16000) + self.sample_rate = int(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 diff --git a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py index 769d81120..e0adf789c 100644 --- a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py +++ b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py @@ -80,7 +80,7 @@ class ASRProvider(ASRProviderBase): # Multi-language Configuration for India self.language_code = config.get("language_code", "en-IN") - self.sample_rate = config.get("sample_rate", 16000) + self.sample_rate = int(config.get("sample_rate", 16000)) self.media_encoding = "pcm" # Fixed for streaming # Indian languages supported by Amazon Transcribe @@ -98,8 +98,11 @@ class ASRProvider(ASRProviderBase): } # 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) + enable_lang_detect = config.get("enable_language_detection", False) + self.enable_language_detection = enable_lang_detect if isinstance(enable_lang_detect, bool) else str(enable_lang_detect).lower() == "true" + + romanized = config.get("romanized_output", True) + self.romanized_output = romanized if isinstance(romanized, bool) else str(romanized).lower() == "true" # File management self.output_dir = config.get("output_dir", "./audio_files") diff --git a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming.py b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming.py index 38167ca4e..afd21830e 100644 --- a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming.py +++ b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming.py @@ -61,7 +61,7 @@ class ASRProvider(ASRProviderBase): # Transcription Configuration self.language_code = config.get("language_code", "en-US") - self.sample_rate = config.get("sample_rate", 16000) + self.sample_rate = int(config.get("sample_rate", 16000)) self.media_encoding = config.get("media_encoding", "pcm") # File management diff --git a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming_simple.py b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming_simple.py index 48eb94f39..17223664d 100644 --- a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming_simple.py +++ b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_streaming_simple.py @@ -31,7 +31,7 @@ class ASRProvider(ASRProviderBase): # Transcription Configuration self.language_code = config.get("language_code", "en-US") - self.sample_rate = config.get("sample_rate", 16000) + self.sample_rate = int(config.get("sample_rate", 16000)) # File management self.output_dir = config.get("output_dir", "./audio_files") diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 2e3a49e0d..4fa07e544 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -62,6 +62,28 @@ class ASRProviderBase(ABC): else: have_voice = conn.client_have_voice + # Check for maximum recording timeout (default 10 seconds) + # This applies when we're actively recording (have accumulated audio) + recording_start_time = None + if hasattr(conn, 'listen_start_time'): + recording_start_time = conn.listen_start_time # Manual listen mode + logger.bind(tag=TAG).debug(f"Using manual listen start time: {recording_start_time}") + elif hasattr(conn, 'vad_recording_start_time'): + recording_start_time = conn.vad_recording_start_time # Auto VAD mode + logger.bind(tag=TAG).debug(f"Using VAD recording start time: {recording_start_time}") + else: + logger.bind(tag=TAG).debug("No recording start time found") + + if len(conn.asr_audio) > 0 and recording_start_time: + current_time = time.time() + recording_duration = current_time - recording_start_time + max_recording_time = conn.config.get('max_recording_time', 10.0) + logger.bind(tag=TAG).debug(f"Recording duration: {recording_duration:.2f}s, max: {max_recording_time}s, audio chunks: {len(conn.asr_audio)}") + if recording_duration >= max_recording_time: + logger.bind(tag=TAG).info(f"Maximum recording time reached ({recording_duration:.2f}s) - forcing voice stop") + conn.client_voice_stop = True + have_voice = False # Force stop current voice detection + # Debug logging if not hasattr(conn, '_asr_log_counter'): conn._asr_log_counter = 0 @@ -88,6 +110,10 @@ class ASRProviderBase(ABC): # Clear the just_started_listening flag when actual voice is detected if hasattr(conn, 'just_started_listening'): conn.just_started_listening = False + # Start recording timer for VAD-based sessions + if not hasattr(conn, 'vad_recording_start_time'): + conn.vad_recording_start_time = time.time() + logger.bind(tag=TAG).debug("VAD recording session started") # Add pre-buffered audio to the beginning of ASR audio conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio conn.audio_pre_buffer.clear()