From 00d91a1a7e3a44932035a7858a5b4caf56019f29 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 30 Aug 2025 13:26:48 +0530 Subject: [PATCH] fixed timer --- check_agent_functions.py | 360 ++++++++++++++++++ final_fix_story_playback.py | 197 ++++++++++ fix_story_playback.py | 270 +++++++++++++ main/xiaozhi-server/core/connection.py | 5 +- .../asr/amazon_transcribe_realtime.py | 4 +- .../xiaozhi-server/core/providers/asr/base.py | 22 +- simple_fix_story_playback.py | 213 +++++++++++ 7 files changed, 1061 insertions(+), 10 deletions(-) create mode 100644 check_agent_functions.py create mode 100644 final_fix_story_playback.py create mode 100644 fix_story_playback.py create mode 100644 simple_fix_story_playback.py diff --git a/check_agent_functions.py b/check_agent_functions.py new file mode 100644 index 000000000..30506105d --- /dev/null +++ b/check_agent_functions.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +""" +Script to check agent templates and functions structure, and fix Story Playback function placement +""" + +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_all_tables(connection): + """Get all tables in the database""" + cursor = connection.cursor() + try: + cursor.execute("SHOW TABLES") + tables = cursor.fetchall() + + print(f"\nAll tables in the database:") + for table in tables: + print(f" - {table[0]}") + + return [table[0] for table in tables] + + except Error as e: + print(f"Error getting tables: {e}") + return None + finally: + cursor.close() + +def search_agent_related_tables(connection): + """Search for agent-related tables""" + cursor = connection.cursor() + try: + cursor.execute("SHOW TABLES LIKE '%agent%'") + agent_tables = cursor.fetchall() + + cursor.execute("SHOW TABLES LIKE '%template%'") + template_tables = cursor.fetchall() + + cursor.execute("SHOW TABLES LIKE '%function%'") + function_tables = cursor.fetchall() + + print(f"\nAgent-related tables:") + for table in agent_tables: + print(f" - {table[0]}") + + print(f"\nTemplate-related tables:") + for table in template_tables: + print(f" - {table[0]}") + + print(f"\nFunction-related tables:") + for table in function_tables: + print(f" - {table[0]}") + + return agent_tables + template_tables + function_tables + + except Error as e: + print(f"Error searching agent tables: {e}") + return None + finally: + cursor.close() + +def examine_table_structure(connection, table_name): + """Get detailed structure of a table""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print(f"Structure of table '{table_name}':") + print('='*60) + + cursor.execute(f"DESCRIBE {table_name}") + columns = cursor.fetchall() + + headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] + print(tabulate(columns, headers=headers, tablefmt="grid")) + + # Get sample data + cursor.execute(f"SELECT * FROM {table_name} LIMIT 5") + sample_data = cursor.fetchall() + + if sample_data: + print(f"\nSample data from '{table_name}':") + column_names = [desc[0] for desc in cursor.description] + print(tabulate(sample_data, headers=column_names, tablefmt="grid")) + + return columns + + except Error as e: + print(f"Error examining table {table_name}: {e}") + return None + finally: + cursor.close() + +def search_story_playback(connection): + """Search for Story Playback function references""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("Searching for 'Story Playback' references in the database...") + print('='*60) + + # Get all tables + cursor.execute("SHOW TABLES") + tables = [table[0] for table in cursor.fetchall()] + + found_references = [] + + for table in tables: + try: + # Get column names for this table + cursor.execute(f"DESCRIBE {table}") + columns = cursor.fetchall() + text_columns = [col[0] for col in columns if 'text' in col[1].lower() or 'varchar' in col[1].lower() or 'json' in col[1].lower()] + + if text_columns: + # Search in each text column + for column in text_columns: + search_query = f"SELECT * FROM {table} WHERE {column} LIKE '%Story Playback%' OR {column} LIKE '%story_playback%' OR {column} LIKE '%storyplayback%'" + cursor.execute(search_query) + results = cursor.fetchall() + + if results: + found_references.append({ + 'table': table, + 'column': column, + 'results': results + }) + print(f"\nFound 'Story Playback' in {table}.{column}:") + column_names = [desc[0] for desc in cursor.description] + print(tabulate(results, headers=column_names, tablefmt="grid")) + + except Error as e: + # Skip tables that might cause errors + continue + + return found_references + + except Error as e: + print(f"Error searching for Story Playback: {e}") + return None + finally: + cursor.close() + +def check_agent_templates(connection): + """Check agent templates and their configurations""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("Checking agent templates...") + print('='*60) + + # Look for agent template related tables + possible_tables = ['agent_template', 'agent_templates', 'toy', 'agent_config', 'agent_configuration'] + + for table_name in possible_tables: + try: + cursor.execute(f"SELECT * FROM {table_name} LIMIT 3") + results = cursor.fetchall() + + if results: + print(f"\nFound data in table '{table_name}':") + column_names = [desc[0] for desc in cursor.description] + print(tabulate(results, headers=column_names, tablefmt="grid")) + + # Check if any columns contain JSON that might have function configurations + for i, row in enumerate(results[:1]): # Check first row only + for j, cell in enumerate(row): + if isinstance(cell, str) and (cell.strip().startswith('{') or cell.strip().startswith('[')): + try: + json_data = json.loads(cell) + print(f"\nJSON data in {table_name}.{column_names[j]} (row {i+1}):") + print(json.dumps(json_data, indent=2)) + except: + pass + + except Error: + continue + + except Error as e: + print(f"Error checking agent templates: {e}") + finally: + cursor.close() + +def fix_story_playback_function(connection): + """Fix Story Playback function to be in Selected Functions for all agent templates""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("Attempting to fix Story Playback function placement...") + print('='*60) + + # First, let's find where the functions are stored + # Look for common table names that might store agent configurations + possible_tables = ['toy', 'agent_template', 'agent_config'] + + for table_name in possible_tables: + try: + # Get all records from the table + cursor.execute(f"SELECT * FROM {table_name}") + results = cursor.fetchall() + column_names = [desc[0] for desc in cursor.description] + + if results: + print(f"\nChecking table '{table_name}' for function configurations...") + + for i, row in enumerate(results): + row_dict = dict(zip(column_names, row)) + + # Look for JSON fields that might contain function configurations + for col_name, cell_value in row_dict.items(): + if isinstance(cell_value, str) and cell_value.strip().startswith('{'): + try: + json_data = json.loads(cell_value) + + # Look for function-related keys + if any(key in json_data for key in ['selected_functions', 'unselected_functions', 'functions', 'selectedFunctions', 'unselectedFunctions']): + print(f"\nFound function configuration in {table_name}, row {i+1}, column '{col_name}':") + print(f"Record ID/identifier: {row_dict.get('id', row_dict.get('template_id', 'Unknown'))}") + + # Check if Story Playback is in unselected functions + needs_update = False + updated_data = json_data.copy() + + # Handle different possible key names + unselected_key = None + selected_key = None + + for key in ['unselected_functions', 'unselectedFunctions']: + if key in json_data: + unselected_key = key + break + + for key in ['selected_functions', 'selectedFunctions']: + if key in json_data: + selected_key = key + break + + if unselected_key and selected_key: + unselected_functions = json_data.get(unselected_key, []) + selected_functions = json_data.get(selected_key, []) + + # Look for Story Playback in unselected functions + story_playback_item = None + for func in unselected_functions: + if isinstance(func, dict) and 'Story Playback' in str(func): + story_playback_item = func + break + elif isinstance(func, str) and 'Story Playback' in func: + story_playback_item = func + break + + if story_playback_item: + print(f"Found Story Playback in unselected functions: {story_playback_item}") + + # Move it to selected functions + updated_data[unselected_key] = [f for f in unselected_functions if f != story_playback_item] + updated_data[selected_key] = selected_functions + [story_playback_item] + + # Update the database + update_query = f"UPDATE {table_name} SET {col_name} = %s WHERE " + if 'id' in row_dict: + update_query += "id = %s" + update_params = [json.dumps(updated_data), row_dict['id']] + else: + # Use the first column as identifier + first_col = column_names[0] + update_query += f"{first_col} = %s" + update_params = [json.dumps(updated_data), row_dict[first_col]] + + print(f"Executing update query: {update_query}") + print(f"Parameters: {update_params[1]} (ID), [JSON data]") + + cursor.execute(update_query, update_params) + connection.commit() + + print(f"✓ Successfully moved Story Playback to selected functions for record {row_dict.get('id', row_dict[column_names[0]])}") + needs_update = True + else: + print(f"Story Playback not found in unselected functions for this record") + + # Print the current function configuration + print(f"Current function configuration:") + print(json.dumps(json_data, indent=2)) + + except json.JSONDecodeError: + continue + + except Error as e: + print(f"Error processing table {table_name}: {e}") + continue + + print(f"\nFunction placement fix completed!") + + except Error as e: + print(f"Error fixing Story Playback function: {e}") + finally: + cursor.close() + +def main(): + print("Checking xiaozhi database for agent templates and Story Playback function") + print("=" * 80) + + # Connect to database + connection = connect_to_database() + if not connection: + return + + try: + # Get all tables + print("\n" + "="*60) + tables = get_all_tables(connection) + + # Search for agent-related tables + print("\n" + "="*60) + agent_tables = search_agent_related_tables(connection) + + # Examine key tables + key_tables = ['toy'] # Start with 'toy' as it's likely the main agent config table + for table in key_tables: + if table in tables: + examine_table_structure(connection, table) + + # Search for Story Playback references + search_story_playback(connection) + + # Check agent templates + check_agent_templates(connection) + + # Fix Story Playback function placement + fix_story_playback_function(connection) + + 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/final_fix_story_playback.py b/final_fix_story_playback.py new file mode 100644 index 000000000..d1f9030c9 --- /dev/null +++ b/final_fix_story_playback.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +""" +Final script to fix Story Playback function placement +""" + +import mysql.connector +from mysql.connector import Error +import json + +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 check_agents_and_templates(connection): + """Check both agent templates and actual agents""" + cursor = connection.cursor() + try: + print("\n1. Checking agent templates...") + cursor.execute("SELECT id, agent_name FROM ai_agent_template") + templates = cursor.fetchall() + + print(f"Found {len(templates)} agent templates:") + for template in templates: + print(f" Template ID: {template[0]}, Name: {template[1]}") + + print("\n2. Checking actual agents...") + cursor.execute("SELECT id, agent_name FROM ai_agent") + agents = cursor.fetchall() + + print(f"Found {len(agents)} agents:") + for agent in agents: + print(f" Agent ID: {agent[0]}, Name: {agent[1]}") + + print("\n3. Checking current Story Playback mappings...") + cursor.execute(""" + SELECT agent_id, param_info FROM ai_agent_plugin_mapping + WHERE plugin_id = 'SYSTEM_PLUGIN_STORY' + """) + story_mappings = cursor.fetchall() + + print(f"Found {len(story_mappings)} existing Story Playback mappings:") + for mapping in story_mappings: + print(f" Agent ID: {mapping[0]}") + + return agents, templates, story_mappings + + except Error as e: + print(f"Error checking agents and templates: {e}") + return [], [], [] + finally: + cursor.close() + +def add_missing_story_playback_mappings(connection, agents, story_mappings): + """Add Story Playback to agents that don't have it""" + cursor = connection.cursor() + try: + # Get list of agent IDs that already have Story Playback + existing_story_agent_ids = [mapping[0] for mapping in story_mappings] + + # Default parameters for Story Playback plugin + param_info = { + "story_dir": "./stories", + "story_ext": ".mp3;.wav;.m4a", + "refresh_time": "300" + } + + updates_made = 0 + + print(f"\n4. Adding Story Playback to agents without it...") + + for agent_id, agent_name in agents: + if agent_id not in existing_story_agent_ids: + print(f"Adding Story Playback to: {agent_name} (ID: {agent_id})") + + cursor.execute(""" + INSERT INTO ai_agent_plugin_mapping + (agent_id, plugin_id, param_info) + VALUES (%s, %s, %s) + """, (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info))) + + updates_made += 1 + print(f" Added successfully") + else: + print(f"Already has Story Playback: {agent_name} (ID: {agent_id})") + + if updates_made > 0: + connection.commit() + print(f"\nCommitted {updates_made} new Story Playback mappings to database") + else: + print(f"\nNo updates needed - all agents already have Story Playback") + + return updates_made + + except Error as e: + print(f"Error adding Story Playback mappings: {e}") + connection.rollback() + return 0 + finally: + cursor.close() + +def verify_final_state(connection): + """Verify all agents now have Story Playback""" + cursor = connection.cursor() + try: + print(f"\n5. Final verification...") + + cursor.execute(""" + SELECT + a.id, + a.agent_name, + CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_story_playback + FROM ai_agent a + LEFT JOIN ai_agent_plugin_mapping apm + ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' + ORDER BY a.agent_name + """) + + results = cursor.fetchall() + + total_agents = len(results) + with_story_playback = sum(1 for result in results if result[2] == 'YES') + + print(f"\nFinal Story Playback status:") + for result in results: + agent_id, agent_name, has_playback = result + status_symbol = "[YES]" if has_playback == 'YES' else "[NO] " + print(f" {status_symbol} {agent_name}") + + print(f"\nSUMMARY:") + print(f"Total agents: {total_agents}") + print(f"With Story Playback: {with_story_playback}") + + if with_story_playback == total_agents: + print("SUCCESS: All agents now have Story Playback function!") + else: + print(f"WARNING: {total_agents - with_story_playback} agents still missing Story Playback") + + return with_story_playback == total_agents + + except Error as e: + print(f"Error verifying final state: {e}") + return False + finally: + cursor.close() + +def main(): + print("Fixing Story Playback function for all agents") + print("=" * 50) + + connection = connect_to_database() + if not connection: + return + + try: + # Check current state + agents, templates, story_mappings = check_agents_and_templates(connection) + + if not agents: + print("ERROR: No agents found in database!") + return + + # Add Story Playback to agents that don't have it + updates_made = add_missing_story_playback_mappings(connection, agents, story_mappings) + + # Verify the final state + success = verify_final_state(connection) + + if success: + print("\nMission accomplished! All agents now have access to Story Playback function.") + else: + print("\nSome issues remain. Please check the output above.") + + finally: + if connection.is_connected(): + connection.close() + print(f"\nDatabase connection closed") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/fix_story_playback.py b/fix_story_playback.py new file mode 100644 index 000000000..50fb37638 --- /dev/null +++ b/fix_story_playback.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +""" +Script to fix Story Playback function placement in agent templates +""" + +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 examine_ai_agent_template(connection): + """Examine the ai_agent_template table""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("Structure of ai_agent_template table:") + print('='*60) + + cursor.execute("DESCRIBE ai_agent_template") + columns = cursor.fetchall() + + headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] + print(tabulate(columns, headers=headers, tablefmt="grid")) + + # Get all records + cursor.execute("SELECT * FROM ai_agent_template") + templates = cursor.fetchall() + column_names = [desc[0] for desc in cursor.description] + + print(f"\nFound {len(templates)} agent templates:") + + for i, template in enumerate(templates): + template_dict = dict(zip(column_names, template)) + print(f"\n--- Template {i+1} ---") + print(f"ID: {template_dict.get('id')}") + print(f"Template Name: {template_dict.get('template_name', template_dict.get('name'))}") + + # Look for JSON fields that might contain function configurations + for col_name, cell_value in template_dict.items(): + if isinstance(cell_value, str) and cell_value.strip().startswith('{'): + try: + json_data = json.loads(cell_value) + print(f"\nJSON field '{col_name}':") + + # Check if it contains function configurations + if any(key in json_data for key in ['selected_functions', 'unselected_functions', 'functions', 'selectedFunctions', 'unselectedFunctions', 'plugins']): + print(f" Contains function/plugin configuration:") + print(json.dumps(json_data, indent=4)) + else: + # Just show the structure + print(f" Keys: {list(json_data.keys())}") + + except json.JSONDecodeError: + if len(str(cell_value)) > 100: + print(f" {col_name}: [Long text content, first 100 chars]: {str(cell_value)[:100]}...") + else: + print(f" {col_name}: {cell_value}") + elif cell_value is not None: + if len(str(cell_value)) > 100: + print(f" {col_name}: [Long content]: {str(cell_value)[:100]}...") + else: + print(f" {col_name}: {cell_value}") + + return templates, column_names + + except Error as e: + print(f"Error examining ai_agent_template: {e}") + return None, None + finally: + cursor.close() + +def check_ai_agent_plugin_mapping(connection): + """Check the ai_agent_plugin_mapping table""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("ai_agent_plugin_mapping table:") + print('='*60) + + cursor.execute("DESCRIBE ai_agent_plugin_mapping") + columns = cursor.fetchall() + + headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] + print(tabulate(columns, headers=headers, tablefmt="grid")) + + # Get all records + cursor.execute("SELECT * FROM ai_agent_plugin_mapping") + mappings = cursor.fetchall() + column_names = [desc[0] for desc in cursor.description] + + if mappings: + print(f"\nPlugin mappings:") + print(tabulate(mappings, headers=column_names, tablefmt="grid")) + else: + print("\nNo plugin mappings found") + + return mappings, column_names + + except Error as e: + print(f"Error examining ai_agent_plugin_mapping: {e}") + return None, None + finally: + cursor.close() + +def fix_story_playback_in_templates(connection): + """Fix Story Playback function to be in selected functions for all agent templates""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("Fixing Story Playback function placement...") + print('='*60) + + # Get all agent templates + cursor.execute("SELECT * FROM ai_agent_template") + templates = cursor.fetchall() + column_names = [desc[0] for desc in cursor.description] + + story_playback_plugin_id = "SYSTEM_PLUGIN_STORY" + updates_made = 0 + + for template in templates: + template_dict = dict(zip(column_names, template)) + template_id = template_dict.get('id') + template_name = template_dict.get('template_name', template_dict.get('name', 'Unknown')) + + print(f"\nProcessing template: {template_name} (ID: {template_id})") + + # Check if this template already has the Story Playback plugin mapped + cursor.execute(""" + SELECT * FROM ai_agent_plugin_mapping + WHERE template_id = %s AND plugin_id = %s + """, (template_id, story_playback_plugin_id)) + existing_mapping = cursor.fetchone() + + if existing_mapping: + mapping_dict = dict(zip([desc[0] for desc in cursor.description], existing_mapping)) + current_status = mapping_dict.get('status', 0) + + print(f" Found existing mapping with status: {current_status}") + + if current_status != 1: # 1 = selected/enabled, 0 = unselected/disabled + # Update the mapping to enable the plugin + cursor.execute(""" + UPDATE ai_agent_plugin_mapping + SET status = 1, update_date = NOW(), updater = 0 + WHERE template_id = %s AND plugin_id = %s + """, (template_id, story_playback_plugin_id)) + + print(f" ✓ Updated Story Playback status from {current_status} to 1 (selected)") + updates_made += 1 + else: + print(f" ✓ Story Playback already selected for this template") + else: + # Create new mapping with status = 1 (selected) + cursor.execute(""" + INSERT INTO ai_agent_plugin_mapping + (template_id, plugin_id, status, sort, creator, create_date, updater, update_date) + VALUES (%s, %s, 1, 0, 0, NOW(), 0, NOW()) + """, (template_id, story_playback_plugin_id)) + + print(f" ✓ Created new mapping with Story Playback selected") + updates_made += 1 + + connection.commit() + print(f"\n{'='*60}") + print(f"Fix completed! Made {updates_made} updates to ensure Story Playback is selected for all agent templates.") + print('='*60) + + except Error as e: + print(f"Error fixing Story Playback function: {e}") + connection.rollback() + finally: + cursor.close() + +def verify_fix(connection): + """Verify that Story Playback is now selected for all templates""" + cursor = connection.cursor() + try: + print(f"\n{'='*60}") + print("Verifying fix...") + print('='*60) + + cursor.execute(""" + SELECT + at.id as template_id, + at.template_name, + apm.plugin_id, + apm.status, + amp.name as plugin_name + FROM ai_agent_template at + LEFT JOIN ai_agent_plugin_mapping apm ON at.id = apm.template_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' + LEFT JOIN ai_model_provider amp ON apm.plugin_id = amp.id + ORDER BY at.template_name + """) + + results = cursor.fetchall() + column_names = [desc[0] for desc in cursor.description] + + print(f"\nStory Playback status for all templates:") + print(tabulate(results, headers=column_names, tablefmt="grid")) + + # Count how many are selected + selected_count = sum(1 for result in results if result[3] == 1) # status column + total_templates = len([r for r in results if r[0] is not None]) # templates with non-null id + + print(f"\nSummary:") + print(f"Total templates: {total_templates}") + print(f"Templates with Story Playback selected: {selected_count}") + + if selected_count == total_templates: + print("✅ SUCCESS: Story Playback is now selected for ALL agent templates!") + else: + print(f"⚠️ WARNING: {total_templates - selected_count} templates still don't have Story Playback selected") + + except Error as e: + print(f"Error verifying fix: {e}") + finally: + cursor.close() + +def main(): + print("Fixing Story Playback function placement in xiaozhi database") + print("=" * 70) + + # Connect to database + connection = connect_to_database() + if not connection: + return + + try: + # Examine agent template structure + examine_ai_agent_template(connection) + + # Check plugin mapping table + check_ai_agent_plugin_mapping(connection) + + # Fix Story Playback placement + fix_story_playback_in_templates(connection) + + # Verify the fix + verify_fix(connection) + + 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/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 48bc10291..dd1a63984 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -2363,10 +2363,13 @@ class ConnectionHandler: self.asr_audio.clear() # Reset VAD recording start time for timeout if hasattr(self, 'vad_recording_start_time'): - delattr(self, 'vad_recording_start_time') + self.vad_recording_start_time = None # Reset timeout flag if hasattr(self, '_timeout_triggered'): self._timeout_triggered = False + # Also reset listen start time to prevent conflicts + if hasattr(self, 'listen_start_time'): + self.listen_start_time = None # 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/providers/asr/amazon_transcribe_realtime.py b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py index e0adf789c..936e4686c 100644 --- a/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py +++ b/main/xiaozhi-server/core/providers/asr/amazon_transcribe_realtime.py @@ -154,7 +154,7 @@ class ASRProvider(ASRProviderBase): pcm_data = self.decode_opus(opus_data) if not pcm_data: logger.bind(tag=TAG).error("Failed to decode Opus audio") - return None, None + return ("", None) else: pcm_data = opus_data @@ -183,7 +183,7 @@ class ASRProvider(ASRProviderBase): logger.bind(tag=TAG).error( f"Speech-to-text error: {str(e)}, type: {type(e).__name__}" ) - return None, audio_file_path + return ("", audio_file_path) finally: # Clean up audio file if configured diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 7462a9d46..b0349e29a 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -91,9 +91,10 @@ class ASRProviderBase(ABC): # Process any accumulated audio before resetting (same as normal VAD flow) if len(conn.asr_audio) > 20: - logger.bind(tag=TAG).info(f"Processing {len(conn.asr_audio)} audio chunks after 10-second timeout") + logger.bind(tag=TAG).info(f"Processing {len(conn.asr_audio)} audio chunks after timeout") asr_audio_task = conn.asr_audio.copy() conn.asr_audio.clear() + # Reset states and clear timeout flag conn.reset_vad_states() # Process the accumulated audio asynchronously asyncio.create_task(self.handle_voice_stop(conn, asr_audio_task)) @@ -103,9 +104,9 @@ class ASRProviderBase(ABC): conn.reset_vad_states() return # Exit early like VAD does - else: - # Already triggered timeout, skip this audio chunk - return + + # If timeout already triggered, just skip this audio and return + return # Debug logging if not hasattr(conn, '_asr_log_counter'): @@ -133,9 +134,12 @@ 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'): + # Start recording timer for VAD-based sessions (only if not already set) + if not hasattr(conn, 'vad_recording_start_time') or conn.vad_recording_start_time is None: conn.vad_recording_start_time = time.time() + # Reset timeout flag when starting new recording session + if hasattr(conn, '_timeout_triggered'): + conn._timeout_triggered = False 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 @@ -247,7 +251,11 @@ class ASRProviderBase(ABC): results = {"asr": asr_result, "voiceprint": None} # Process results - raw_text, file_path = results.get("asr", ("", None)) + asr_result = results.get("asr", ("", None)) + if asr_result is None: + raw_text, file_path = "", None + else: + raw_text, file_path = asr_result speaker_name = results.get("voiceprint", None) # Apply ASR filtering if enabled diff --git a/simple_fix_story_playback.py b/simple_fix_story_playback.py new file mode 100644 index 000000000..8e6ef9d16 --- /dev/null +++ b/simple_fix_story_playback.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +""" +Simple script to fix Story Playback function placement in agent templates +""" + +import mysql.connector +from mysql.connector import Error +import json + +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 check_current_mappings(connection): + """Check current plugin mappings""" + cursor = connection.cursor() + try: + print("\nChecking current plugin mappings...") + + # Check if ai_agent_plugin_mapping has the right structure + cursor.execute("DESCRIBE ai_agent_plugin_mapping") + columns = cursor.fetchall() + + column_names = [col[0] for col in columns] + print(f"ai_agent_plugin_mapping columns: {column_names}") + + # Check if we should use template_id or agent_id + if 'template_id' in column_names: + id_column = 'template_id' + elif 'agent_id' in column_names: + id_column = 'agent_id' + else: + print("ERROR: Neither template_id nor agent_id found in ai_agent_plugin_mapping table") + return None, None + + # Get all current mappings + cursor.execute(f"SELECT * FROM ai_agent_plugin_mapping") + mappings = cursor.fetchall() + + print(f"\nFound {len(mappings)} existing plugin mappings") + for mapping in mappings: + mapping_dict = dict(zip(column_names, mapping)) + print(f"ID: {mapping_dict.get('id')}, {id_column}: {mapping_dict.get(id_column)}, plugin_id: {mapping_dict.get('plugin_id')}") + + return mappings, id_column + + except Error as e: + print(f"Error checking current mappings: {e}") + return None, None + finally: + cursor.close() + +def get_all_agent_templates(connection): + """Get all agent template IDs""" + cursor = connection.cursor() + try: + cursor.execute("SELECT id, agent_name FROM ai_agent_template") + templates = cursor.fetchall() + + print(f"\nFound {len(templates)} agent templates:") + for template in templates: + print(f" ID: {template[0]}, Name: {template[1]}") + + return templates + + except Error as e: + print(f"Error getting agent templates: {e}") + return [] + finally: + cursor.close() + +def add_story_playback_to_all_templates(connection, templates, id_column): + """Add Story Playback plugin to all templates""" + cursor = connection.cursor() + try: + story_playback_plugin_id = "SYSTEM_PLUGIN_STORY" + updates_made = 0 + + print(f"\nAdding Story Playback plugin to all templates...") + + for template_id, template_name in templates: + print(f"\nProcessing template: {template_name} (ID: {template_id})") + + # Check if mapping already exists + cursor.execute(f""" + SELECT * FROM ai_agent_plugin_mapping + WHERE {id_column} = %s AND plugin_id = %s + """, (template_id, story_playback_plugin_id)) + + existing = cursor.fetchone() + + if existing: + print(f" Already has Story Playback mapping") + else: + # Insert new mapping + # Create a basic param_info for the story plugin + param_info = { + "story_dir": "./stories", + "story_ext": ".mp3;.wav;.m4a", + "refresh_time": "300" + } + + cursor.execute(f""" + INSERT INTO ai_agent_plugin_mapping + ({id_column}, plugin_id, param_info) + VALUES (%s, %s, %s) + """, (template_id, story_playback_plugin_id, json.dumps(param_info))) + + print(f" Added Story Playback mapping") + updates_made += 1 + + connection.commit() + print(f"\nCompleted! Added Story Playback to {updates_made} templates.") + + except Error as e: + print(f"Error adding Story Playback mappings: {e}") + connection.rollback() + finally: + cursor.close() + +def verify_mappings(connection, id_column): + """Verify all templates now have Story Playback""" + cursor = connection.cursor() + try: + print(f"\nVerifying Story Playback mappings...") + + cursor.execute(f""" + SELECT + at.id, + at.agent_name, + CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_story_playback + FROM ai_agent_template at + LEFT JOIN ai_agent_plugin_mapping apm + ON at.id = apm.{id_column} AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' + ORDER BY at.agent_name + """) + + results = cursor.fetchall() + + total_templates = len(results) + with_story_playback = sum(1 for result in results if result[2] == 'YES') + + print(f"\nStory Playback status:") + for result in results: + template_id, agent_name, has_playback = result + status = "✓" if has_playback == 'YES' else "✗" + print(f" {status} {agent_name} (ID: {template_id})") + + print(f"\nSummary:") + print(f"Total templates: {total_templates}") + print(f"With Story Playback: {with_story_playback}") + + if with_story_playback == total_templates: + print(" SUCCESS: All templates now have Story Playback!") + else: + print(f" {total_templates - with_story_playback} templates still missing Story Playback") + + except Error as e: + print(f"Error verifying mappings: {e}") + finally: + cursor.close() + +def main(): + print("Fixing Story Playback function for all agent templates") + print("=" * 60) + + connection = connect_to_database() + if not connection: + return + + try: + # Check current state + mappings, id_column = check_current_mappings(connection) + if not id_column: + return + + # Get all templates + templates = get_all_agent_templates(connection) + if not templates: + print("No agent templates found!") + return + + # Add Story Playback to all templates + add_story_playback_to_all_templates(connection, templates, id_column) + + # Verify the fix + verify_mappings(connection, id_column) + + finally: + if connection.is_connected(): + connection.close() + print(f"\nMySQL connection closed") + +if __name__ == "__main__": + main() \ No newline at end of file