Merge pull request #15 from Craftech360-projects/timezone_in_chathistory

Timezone in chathistory
This commit is contained in:
rahulpscraftech360 2025-09-13 12:22:45 +05:30 committed by GitHub
commit 1f7c640fbb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 1289 additions and 1250 deletions

View file

@ -63,8 +63,8 @@ public class WebMvcConfig implements WebMvcConfigurer {
// 忽略未知属性
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 设置时区
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 设置时区 (IST - India Standard Time)
mapper.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
// 配置Java8日期时间序列化
JavaTimeModule javaTimeModule = new JavaTimeModule();

View file

@ -22,7 +22,7 @@ spring:
# password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK
driver-class-name: com.mysql.cj.jdbc.Driver
# Railway MySQL Configuration - Updated for Railway database
url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Kolkata&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
username: root
password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA

View file

@ -0,0 +1,17 @@
-- Add semantic search configuration for improved music search functionality
-- 添加语义搜索配置以改进音乐搜索功能
-- Delete existing semantic search params if they exist
delete from sys_params where id in (701, 702, 703, 704, 705, 706, 707);
-- Insert semantic search configuration parameters
INSERT INTO sys_params
(id, param_code, param_value, value_type, param_type, remark, creator, create_date, updater, update_date)
VALUES
(701, 'semantic_search.enabled', 'true', 'boolean', 1, 'Enable semantic music search using vector embeddings', NULL, NULL, NULL, NULL),
(702, 'semantic_search.qdrant_url', 'https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io', 'string', 1, 'Qdrant vector database URL for music embeddings', NULL, NULL, NULL, NULL),
(703, 'semantic_search.qdrant_api_key', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk', 'string', 1, 'Qdrant API key for authentication', NULL, NULL, NULL, NULL),
(704, 'semantic_search.collection_name', 'xiaozhi_music', 'string', 1, 'Vector collection name for music embeddings', NULL, NULL, NULL, NULL),
(705, 'semantic_search.embedding_model', 'all-MiniLM-L6-v2', 'string', 1, 'Sentence transformer model for generating embeddings', NULL, NULL, NULL, NULL),
(706, 'semantic_search.search_limit', '5', 'number', 1, 'Maximum number of search results to return', NULL, NULL, NULL, NULL),
(707, 'semantic_search.min_score_threshold', '0.5', 'number', 1, 'Minimum similarity score threshold (0.0-1.0)', NULL, NULL, NULL, NULL);

View file

@ -3,8 +3,29 @@ import RequestService from '../httpRequest';
export default {
// 获取智能体列表
getAgentList(callback) {
// 获取智能体列表 (Admin - shows all agents from all users)
getAgentList(params, callback) {
// Support both old callback-only format and new params format
if (typeof params === 'function') {
callback = params;
params = { page: 1, limit: 1000 }; // Default pagination for all agents
}
RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/all`)
.method('GET')
.data(params)
.success((res) => {
RequestService.clearRequestTime();
callback(res);
})
.networkFail(() => {
RequestService.reAjaxFun(() => {
this.getAgentList(params, callback);
});
}).send();
},
// 获取用户自己的智能体列表 (User - shows only current user's agents)
getUserAgentList(callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/list`)
.method('GET')
@ -14,7 +35,7 @@ export default {
})
.networkFail(() => {
RequestService.reAjaxFun(() => {
this.getAgentList(callback);
this.getUserAgentList(callback);
});
}).send();
},

View file

@ -96,7 +96,7 @@ export default {
const result = [];
const TIME_INTERVAL = 60 * 1000; // 1分钟的时间间隔(毫秒)
// 添加第一条消息的时间标记
// 添加第一条消息的时间标记 (converted to IST)
if (this.messages[0]) {
result.push({
type: 'time',
@ -118,7 +118,7 @@ export default {
if (nextTime - currentTime > TIME_INTERVAL) {
result.push({
type: 'time',
content: this.formatTime(this.messages[i + 1].createdAt),
content: this.formatTime(this.messages[i + 1].createdAt), // converted to IST
id: `time-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
});
}
@ -220,24 +220,36 @@ export default {
}, 200);
},
formatTime(timestamp) {
// Backend sends timestamps already in IST format, no timezone conversion needed
const date = new Date(timestamp);
const now = new Date();
// Create today and yesterday date objects for comparison
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const hours = date.getHours().toString().padStart(2, '0');
// Create message date object for comparison (without time)
const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Format time in 12-hour format
const hours = date.getHours();
const minutes = date.getMinutes().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
const displayHours = hours % 12 || 12; // Convert to 12-hour format
const timeStr = `${displayHours}:${minutes} ${ampm}`;
if (date >= today) {
return `Today ${hours}:${minutes}`;
} else if (date >= yesterday) {
return `Yesterday ${hours}:${minutes}`;
// Compare dates and return appropriate format
if (messageDate.getTime() === today.getTime()) {
return `Today ${timeStr}`;
} else if (messageDate.getTime() === yesterday.getTime()) {
return `Yesterday ${timeStr}`;
} else {
// For older dates, show full date and time
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
return `${year}-${month}-${day} ${timeStr}`;
}
},
getAudioIconClass(message) {

View file

@ -1,12 +1,17 @@
{
"production": {
"chat_servers": [
"ws://192.168.1.166:8000/toy/v1/"
"ws://139.59.7.72:8000/toy/v1/"
]
},
"development": {
"chat_servers": [
"ws://139.59.7.72:8000/toy/v1/"
],
"mac_addresss": [
]

View file

@ -19,10 +19,10 @@ import opuslib
# --- Configuration ---
SERVER_IP = "192.168.1.179" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8002
MQTT_BROKER_HOST = "192.168.1.179" # MQTT gateway IP
SERVER_IP = "192.168.1.166" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8003
MQTT_BROKER_HOST = "192.168.1.166" # MQTT gateway IP
MQTT_BROKER_PORT = 1883
# DEVICE_MAC is now dynamically generated for uniqueness

View file

@ -404,6 +404,43 @@ ASR:
# Language parameter, 1537 for Mandarin, specific reference: https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b
dev_pid: 1537
output_dir: tmp/
GoogleSpeechV2:
# Google Cloud Speech-to-Text v2 with Chirp 2 model
# Chirp 2 is Google's next-generation universal speech model with improved accuracy
# Setup instructions:
# 1. Enable Speech-to-Text API v2 in Google Cloud Console: https://console.cloud.google.com/apis/library/speech.googleapis.com
# 2. Create a service account: https://console.cloud.google.com/iam-admin/serviceaccounts
# 3. Download JSON credentials and set the path below
# Pricing: https://cloud.google.com/speech-to-text/v2/pricing
type: google_speech_v2
# Google Cloud project ID
project_id: gen-lang-client-0652043794
# Processing location for Chirp 2 (available in: us-central1, europe-west4, asia-southeast1)
# Note: API resource uses 'global' but processing happens in this region
location: us-central1
# Path to service account credentials JSON file
credentials_path: "C:\\Users\\Acer\\Cheeko-esp32-server\\main\\xiaozhi-server\\gen-lang-client-0652043794-e5f4175261a8.json"
# Model to use (chirp_2 for best accuracy, latest_long for standard)
model: chirp_2
# Language codes - Chirp 2 supports multiple languages simultaneously
# Examples: ["en-US"], ["zh-CN"], ["en-US", "zh-CN"] for multilingual
language_codes:
- en-US
# Audio encoding (LINEAR16 for PCM, OGG_OPUS for Opus)
encoding: LINEAR16
# Sample rate in Hz (16000 recommended)
sample_rate_hertz: 16000
# Enable automatic punctuation
enable_automatic_punctuation: true
# Enable word-level timestamps
enable_word_time_offsets: false
# Enable word confidence scores
enable_word_confidence: false
# Enable spoken punctuation (e.g., "period", "comma")
enable_spoken_punctuation: false
# Enable spoken emojis (e.g., "smiley face")
enable_spoken_emojis: false
output_dir: tmp/
VAD:
SileroVAD:
@ -867,6 +904,7 @@ TTS:
voice: "OUeAo1mhq6IBExi"
output_dir: tmp/
semantic_search:
# Enable semantic search for music (requires Qdrant and sentence-transformers)
enabled: true # Set to false to disable
@ -882,3 +920,4 @@ semantic_search:
search_limit: 5
# Minimum similarity score threshold (0.5 = 50% similarity required)
min_score_threshold: 0.5

View file

@ -1,204 +1,3 @@
# from core.handle.sendAudioHandle import send_stt_message
# from core.handle.intentHandler import handle_user_intent
# from core.utils.output_counter import check_device_output_limit
# from core.handle.abortHandle import handleAbortMessage
# import time
# import asyncio
# import json
# from core.handle.sendAudioHandle import SentenceType
# from core.utils.util import audio_to_data
# TAG = __name__
# async def handleAudioMessage(conn, audio):
# # Log that we received audio (only log periodically to avoid spam)
# if not hasattr(conn, '_audio_log_counter'):
# conn._audio_log_counter = 0
# conn._audio_log_counter += 1
# if conn._audio_log_counter % 200 == 0: # Log every 200th packet (reduced from 50)
# conn.logger.bind(tag=TAG).debug(f"Received audio packet #{conn._audio_log_counter}, size: {len(audio)} bytes")
# # Skip VAD/ASR processing when server is speaking (streaming audio to client)
# # This prevents interruptions during TTS playback
# if conn.client_is_speaking:
# # conn.logger.bind(tag=TAG).debug("Server is speaking - skipping audio processing to prevent interruption")
# return
# # 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:
# current_time = asyncio.get_event_loop().time()
# if current_time - conn.initial_connection_time < 1.0: # Ignore first 1 second
# have_voice = False
# conn.asr_audio.clear() # Clear any accumulated audio
# return
# else:
# conn.initial_connection_handled = True
# # If the device was just woken up, briefly ignore VAD detection
# if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
# have_voice = False
# # Set a brief delay before resuming VAD detection
# conn.asr_audio.clear()
# if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
# conn.vad_resume_task = asyncio.create_task(
# resume_vad_detection(conn))
# return
# if have_voice:
# if conn.client_is_speaking:
# await handleAbortMessage(conn)
# # Device long-term idle detection, used for say goodbye
# await no_voice_close_connect(conn, have_voice)
# # Receive audio
# await conn.asr.receive_audio(conn, audio, have_voice)
# async def resume_vad_detection(conn):
# # Wait 2 seconds before resuming VAD detection
# await asyncio.sleep(1)
# conn.just_woken_up = False
# async def startToChat(conn, text):
# # Check if input is in JSON format (containing speaker information)
# speaker_name = None
# actual_text = text
# try:
# # Try to parse JSON format input
# if text.strip().startswith('{') and text.strip().endswith('}'):
# data = json.loads(text)
# if 'speaker' in data and 'content' in data:
# speaker_name = data['speaker']
# actual_text = data['content']
# conn.logger.bind(tag=TAG).info(
# f"Parsed speaker information: {speaker_name}")
# # Use JSON format text directly, do not parse
# actual_text = text
# except (json.JSONDecodeError, KeyError):
# # If parsing fails, continue using original text
# pass
# # Save speaker information to connection object
# if speaker_name:
# conn.current_speaker = speaker_name
# else:
# conn.current_speaker = None
# if conn.need_bind:
# await check_bind_device(conn)
# return
# # If the daily output word count exceeds the limit
# if conn.max_output_size > 0:
# if check_device_output_limit(
# conn.headers.get("device-id"), conn.max_output_size
# ):
# await max_out_size(conn)
# return
# if conn.client_is_speaking:
# await handleAbortMessage(conn)
# # First perform intent analysis, using actual text content
# intent_handled = await handle_user_intent(conn, actual_text)
# if intent_handled:
# # If intent has been handled, no longer proceed with chat
# return
# # Intent not handled, continue with regular chat flow, using actual text content
# await send_stt_message(conn, actual_text)
# conn.executor.submit(conn.chat, actual_text)
# async def no_voice_close_connect(conn, have_voice):
# if have_voice:
# conn.last_activity_time = time.time() * 1000
# return
# # Only perform timeout check when timestamp has been initialized
# if conn.last_activity_time > 0.0:
# no_voice_time = time.time() * 1000 - conn.last_activity_time
# close_connection_no_voice_time = int(
# conn.config.get("close_connection_no_voice_time", 120)
# )
# if (
# not conn.close_after_chat
# and no_voice_time > 1000 * close_connection_no_voice_time
# ):
# conn.close_after_chat = True
# conn.client_abort = False
# end_prompt = conn.config.get("end_prompt", {})
# if end_prompt and end_prompt.get("enable", True) is False:
# conn.logger.bind(tag=TAG).info(
# "End conversation, no need to send ending prompt")
# await conn.close()
# return
# prompt = end_prompt.get("prompt")
# if not prompt:
# prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!"
# await startToChat(conn, prompt)
# async def max_out_size(conn):
# text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!"
# await send_stt_message(conn, text)
# file_path = "config/assets/max_output_size.wav"
# opus_packets, _ = audio_to_data(file_path)
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
# conn.close_after_chat = True
# async def check_bind_device(conn):
# if conn.bind_code:
# # Ensure bind_code is a 6-digit number
# if len(conn.bind_code) != 6:
# conn.logger.bind(tag=TAG).error(
# f"Invalid binding code format: {conn.bind_code}")
# text = "Binding code format error, please check configuration."
# await send_stt_message(conn, text)
# return
# text = f"Please log into the control panel and enter {conn.bind_code} to bind the device."
# await send_stt_message(conn, text)
# # Play notification sound
# music_path = "config/assets/bind_code.wav"
# opus_packets, _ = audio_to_data(music_path)
# conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# # Play digits one by one
# for i in range(6): # Ensure only 6 digits are played
# try:
# digit = conn.bind_code[i]
# num_path = f"config/assets/bind_code/{digit}.wav"
# num_packets, _ = audio_to_data(num_path)
# conn.tts.tts_audio_queue.put(
# (SentenceType.MIDDLE, num_packets, None))
# except Exception as e:
# conn.logger.bind(tag=TAG).error(
# f"Failed to play digit audio: {e}")
# continue
# conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
# else:
# text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware."
# await send_stt_message(conn, text)
# music_path = "config/assets/bind_not_found.wav"
# opus_packets, _ = audio_to_data(music_path)
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit

View file

@ -0,0 +1,556 @@
import os
import time
import json
import asyncio
from google.cloud import speech_v2
from google.api_core import exceptions
from google.api_core.client_options import ClientOptions
from config.logger import setup_logging
from typing import Optional, Tuple, List, AsyncIterator
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class ASRProvider(ASRProviderBase):
"""
Google Cloud Speech-to-Text v2 Provider with Chirp 2 model support
Chirp 2 is Google's next-generation universal speech model with improved accuracy
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__(config)
self.interface_type = InterfaceType.NON_STREAM
# Google Cloud configuration
self.project_id = config.get("project_id")
self.location = config.get("location", "global") # Chirp 2 is available globally
self.credentials_path = config.get("credentials_path")
# Model configuration - Chirp 2 specific
self.model = config.get("model", "chirp_2") # Use Chirp 2 by default
language_codes_from_config = config.get("language_codes", ["en-US"])
# Ensure language_codes is never empty (Google API requirement)
if not language_codes_from_config or not isinstance(language_codes_from_config, list):
self.language_codes = ["en-US"]
logger.bind(tag=TAG).warning(f"Invalid or empty language_codes in config, using default: ['en-US']")
else:
self.language_codes = language_codes_from_config
# Debug logging for language codes
logger.bind(tag=TAG).info(f"Configured language_codes: {self.language_codes} (type: {type(self.language_codes)})")
# Audio configuration
self.sample_rate_hertz = config.get("sample_rate_hertz", 16000)
self.encoding = config.get("encoding", "LINEAR16")
# Recognition configuration
self.enable_automatic_punctuation = config.get("enable_automatic_punctuation", True)
self.enable_word_time_offsets = config.get("enable_word_time_offsets", False)
self.enable_word_confidence = config.get("enable_word_confidence", False)
self.enable_spoken_punctuation = config.get("enable_spoken_punctuation", False)
self.enable_spoken_emojis = config.get("enable_spoken_emojis", False)
# File management
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
# Set credentials if provided
if self.credentials_path:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = self.credentials_path
# Initialize the Speech client with v2 API
try:
# For Chirp 2, use regional endpoint and recognizer
if self.model == "chirp_2":
# Use regional API endpoint for Chirp 2
api_endpoint = f"{self.location}-speech.googleapis.com"
client_options = ClientOptions(api_endpoint=api_endpoint)
self.client = speech_v2.SpeechClient(client_options=client_options)
# Use regional recognizer path to match regional endpoint
# Note: When using regional endpoint, recognizer path must also use same region
self.recognizer_name = f"projects/{self.project_id}/locations/{self.location}/recognizers/_"
logger.bind(tag=TAG).info(f"Using regional API endpoint: {api_endpoint}")
else:
# Use default global client and recognizer for standard models
self.client = speech_v2.SpeechClient()
self.recognizer_name = f"projects/{self.project_id}/locations/global/recognizers/_"
logger.bind(tag=TAG).info(
f"Google Speech v2 initialized with model: {self.model}, "
f"project: {self.project_id}, recognizer: {self.recognizer_name}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to initialize Google Speech v2 client: {e}")
raise
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
# Streaming session management
self.streaming_sessions = {} # conn.session_id -> streaming session data
def _get_audio_encoding(self):
"""Map encoding string to Google Speech enum"""
try:
encoding_map = {
"LINEAR16": speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16,
"FLAC": speech_v2.ExplicitDecodingConfig.AudioEncoding.FLAC,
"MULAW": speech_v2.ExplicitDecodingConfig.AudioEncoding.MULAW,
"AMR": speech_v2.ExplicitDecodingConfig.AudioEncoding.AMR,
"AMR_WB": speech_v2.ExplicitDecodingConfig.AudioEncoding.AMR_WB,
"OGG_OPUS": speech_v2.ExplicitDecodingConfig.AudioEncoding.OGG_OPUS,
"MP3": speech_v2.ExplicitDecodingConfig.AudioEncoding.MP3,
"WEBM_OPUS": speech_v2.ExplicitDecodingConfig.AudioEncoding.WEBM_OPUS,
}
# Add SPEEX if available (not all versions support it)
if hasattr(speech_v2.ExplicitDecodingConfig.AudioEncoding, 'SPEEX_WITH_HEADER_BYTE'):
encoding_map["SPEEX_WITH_HEADER_BYTE"] = speech_v2.ExplicitDecodingConfig.AudioEncoding.SPEEX_WITH_HEADER_BYTE
return encoding_map.get(self.encoding, speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16)
except AttributeError as e:
logger.bind(tag=TAG).warning(f"Audio encoding {self.encoding} not supported, using LINEAR16: {e}")
return speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16
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 Google Cloud Speech v2 API with Chirp 2"""
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
else:
pcm_data = opus_data
# Save audio to file for logging/debugging
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Combine PCM data
audio_content = b"".join(pcm_data)
# Calculate audio length for logging
audio_length_seconds = len(audio_content) / (self.sample_rate_hertz * 2) # 16-bit audio
# Configure recognition request - use model name as-is
model_name = self.model
encoding = self._get_audio_encoding()
logger.bind(tag=TAG).debug(f"Using model: {model_name} for recognition")
logger.bind(tag=TAG).debug(f"Audio encoding: {encoding}, sample_rate: {self.sample_rate_hertz}, audio_length: {len(audio_content)} bytes")
# Configure recognition request based on model type
if self.model == "chirp_2":
# Use explicit decoding config for Chirp 2 with proper audio format
config = speech_v2.RecognitionConfig(
explicit_decoding_config=speech_v2.ExplicitDecodingConfig(
encoding=encoding,
sample_rate_hertz=self.sample_rate_hertz,
audio_channel_count=1,
),
language_codes=self.language_codes,
model=model_name, # chirp_2
features=speech_v2.RecognitionFeatures(
enable_automatic_punctuation=self.enable_automatic_punctuation,
enable_word_time_offsets=self.enable_word_time_offsets,
enable_word_confidence=self.enable_word_confidence,
enable_spoken_punctuation=self.enable_spoken_punctuation,
enable_spoken_emojis=self.enable_spoken_emojis,
profanity_filter=False,
),
)
else:
# Use explicit decoding for standard models
config = speech_v2.RecognitionConfig(
explicit_decoding_config=speech_v2.ExplicitDecodingConfig(
encoding=encoding,
sample_rate_hertz=self.sample_rate_hertz,
audio_channel_count=1,
),
language_codes=self.language_codes,
model=model_name,
features=speech_v2.RecognitionFeatures(
enable_automatic_punctuation=self.enable_automatic_punctuation,
enable_word_time_offsets=self.enable_word_time_offsets,
enable_word_confidence=self.enable_word_confidence,
enable_spoken_punctuation=self.enable_spoken_punctuation,
enable_spoken_emojis=self.enable_spoken_emojis,
profanity_filter=False,
),
)
# Create recognition request
request = speech_v2.RecognizeRequest(
recognizer=self.recognizer_name,
config=config,
content=audio_content,
)
# Perform synchronous speech recognition
try:
response = self.client.recognize(request=request)
# Extract transcription from response
transcript = ""
confidence_scores = []
for result in response.results:
# Get the best alternative (highest confidence)
if result.alternatives:
best_alternative = result.alternatives[0]
transcript += best_alternative.transcript + " "
# Collect confidence scores if available
if hasattr(best_alternative, 'confidence'):
confidence_scores.append(best_alternative.confidence)
# Log word-level details if enabled
if self.enable_word_time_offsets and hasattr(best_alternative, 'words'):
for word_info in best_alternative.words:
logger.bind(tag=TAG).debug(
f"Word: {word_info.word}, "
f"Start: {word_info.start_offset}, "
f"End: {word_info.end_offset}"
)
transcript = transcript.strip()
# Calculate average confidence if available
avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else None
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Google Speech v2 (Chirp 2) transcription completed in {elapsed_time:.2f}s"
f"{f', confidence: {avg_confidence:.2f}' if avg_confidence else ''}: {transcript}"
)
# Log the transcript for debugging/analysis
if transcript:
self.log_audio_transcript(audio_file_path, audio_length_seconds, transcript)
return transcript, audio_file_path
except exceptions.GoogleAPIError as e:
logger.bind(tag=TAG).error(f"Google Speech API error: {e}")
return "", audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
import traceback
logger.bind(tag=TAG).debug(f"Traceback: {traceback.format_exc()}")
return "", 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 start_streaming_session(self, conn, session_id: str) -> bool:
"""Start a streaming ASR session for real-time transcription.
Args:
conn: Connection object
session_id: Unique session identifier
Returns:
True if session started successfully, False otherwise
"""
try:
logger.bind(tag=TAG).info(f"[STREAM-START] Starting streaming session: {session_id}")
# Validate language codes
safe_language_codes = self.language_codes if self.language_codes else ["en-US"]
logger.bind(tag=TAG).debug(f"[STREAM-START] Using language_codes: {safe_language_codes}")
# Create simplified session data with direct audio buffer
session_data = {
'language_codes': safe_language_codes,
'model': self.model,
'audio_buffer': [], # Simple list to collect audio chunks
'stream_iterator': None,
'streaming_task': None,
'final_transcript': "",
'partial_transcript': "",
'session_active': True,
'audio_count': 0
}
# Store session
self.streaming_sessions[session_id] = session_data
logger.bind(tag=TAG).info(f"[STREAM-START] Session {session_id} created with simplified data structure")
# Start the streaming task
session_data['streaming_task'] = asyncio.create_task(
self._simplified_streaming_task(session_id, session_data)
)
logger.bind(tag=TAG).info(f"[STREAM-START] Streaming session {session_id} started successfully")
return True
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-START] Failed to start streaming session {session_id}: {e}")
import traceback
logger.bind(tag=TAG).error(f"[STREAM-START] Traceback: {traceback.format_exc()}")
return False
async def _simplified_streaming_task(self, session_id: str, session_data: dict):
"""Simplified streaming task that processes audio directly without complex queues."""
logger.bind(tag=TAG).info(f"[STREAM-TASK] Starting simplified streaming task for session {session_id}")
try:
# Create streaming configuration with explicit decoding (matches non-streaming config)
config = speech_v2.StreamingRecognitionConfig(
config=speech_v2.RecognitionConfig(
explicit_decoding_config=speech_v2.ExplicitDecodingConfig(
encoding=self._get_audio_encoding(),
sample_rate_hertz=self.sample_rate_hertz,
audio_channel_count=1,
),
language_codes=session_data['language_codes'],
model=session_data['model'],
features=speech_v2.RecognitionFeatures(
enable_automatic_punctuation=self.enable_automatic_punctuation,
enable_word_time_offsets=self.enable_word_time_offsets,
enable_word_confidence=self.enable_word_confidence,
enable_spoken_punctuation=self.enable_spoken_punctuation,
enable_spoken_emojis=self.enable_spoken_emojis,
profanity_filter=False,
),
),
streaming_features=speech_v2.StreamingRecognitionFeatures(
interim_results=True,
enable_voice_activity_events=True,
)
)
logger.bind(tag=TAG).info(f"[STREAM-TASK] Created config for {session_id}:")
logger.bind(tag=TAG).info(f" - Language codes: {session_data['language_codes']}")
logger.bind(tag=TAG).info(f" - Model: {session_data['model']}")
logger.bind(tag=TAG).info(f" - Encoding: {self._get_audio_encoding()}")
logger.bind(tag=TAG).info(f" - Sample rate: {self.sample_rate_hertz} Hz")
logger.bind(tag=TAG).info(f" - Channels: 1 (mono)")
# Use a thread-safe queue to pass audio data to generator
import queue
import threading
audio_queue = queue.Queue()
def audio_generator():
"""Generator that yields audio requests to Google API."""
logger.bind(tag=TAG).debug(f"[AUDIO-GEN] Starting audio generator for {session_id}")
# First request: configuration
config_request = speech_v2.StreamingRecognizeRequest(
recognizer=self.recognizer_name,
streaming_config=config
)
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Sending config request for {session_id}")
yield config_request
# Track audio chunks sent
chunks_sent = 0
# Process audio chunks from queue
while True:
try:
# Wait for audio data with timeout
audio_chunk = audio_queue.get(timeout=1.0)
if audio_chunk is None: # End signal
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Received end signal for {session_id}")
break
chunks_sent += 1
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Sending audio chunk #{chunks_sent} ({len(audio_chunk)} bytes) for {session_id}")
# Create and yield audio request
audio_request = speech_v2.StreamingRecognizeRequest(audio=audio_chunk)
yield audio_request
except queue.Empty:
# Timeout - check if session is still active
if not session_data['session_active']:
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Session {session_id} no longer active, stopping generator")
break
continue
except Exception as e:
logger.bind(tag=TAG).error(f"[AUDIO-GEN] Error in generator for {session_id}: {e}")
break
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Audio generator finished for {session_id} (sent {chunks_sent} chunks)")
# Function to feed audio data from buffer to queue
def audio_feeder():
"""Feed audio data from session buffer to generator queue."""
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Starting audio feeder for {session_id}")
try:
while session_data['session_active']:
# Check if we have audio data in buffer
if session_data['audio_buffer']:
audio_chunk = session_data['audio_buffer'].pop(0)
audio_queue.put(audio_chunk)
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Moved audio chunk to queue for {session_id}")
else:
# No audio data, sleep briefly
import time
time.sleep(0.01) # 10ms
# Send end signal when session ends
audio_queue.put(None)
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Sent end signal for {session_id}")
except Exception as e:
logger.bind(tag=TAG).error(f"[AUDIO-FEEDER] Error in feeder for {session_id}: {e}")
finally:
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Audio feeder finished for {session_id}")
# Start audio feeder in separate thread
feeder_thread = threading.Thread(target=audio_feeder, daemon=True)
feeder_thread.start()
# Start streaming recognition
logger.bind(tag=TAG).info(f"[STREAM-TASK] Starting Google API streaming for {session_id}")
responses = self.client.streaming_recognize(audio_generator())
# Process responses
response_count = 0
for response in responses:
if not session_data['session_active']:
logger.bind(tag=TAG).info(f"[STREAM-TASK] Session {session_id} no longer active, stopping")
break
response_count += 1
logger.bind(tag=TAG).debug(f"[STREAM-TASK] Processing response #{response_count} for {session_id}")
# Process recognition results
for result in response.results:
if result.alternatives:
transcript = result.alternatives[0].transcript
confidence = getattr(result.alternatives[0], 'confidence', 0.0)
if result.is_final:
session_data['final_transcript'] += transcript + " "
session_data['partial_transcript'] = ""
logger.bind(tag=TAG).info(f"[STREAM-TASK] FINAL transcript for {session_id}: '{transcript}' (confidence: {confidence:.2f})")
else:
session_data['partial_transcript'] = transcript
logger.bind(tag=TAG).debug(f"[STREAM-TASK] PARTIAL transcript for {session_id}: '{transcript}'")
logger.bind(tag=TAG).info(f"[STREAM-TASK] Completed streaming for {session_id} (processed {response_count} responses)")
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-TASK] Error in streaming task for {session_id}: {e}")
import traceback
logger.bind(tag=TAG).error(f"[STREAM-TASK] Traceback: {traceback.format_exc()}")
finally:
logger.bind(tag=TAG).info(f"[STREAM-TASK] Streaming task ended for {session_id}")
async def stream_audio_chunk(self, conn, audio_chunk: bytes, session_id: str) -> Optional[str]:
"""Stream an audio chunk to the active ASR session.
Args:
conn: Connection object
audio_chunk: PCM audio data to stream
session_id: Session identifier
Returns:
Latest partial transcript if available, None otherwise
"""
logger.bind(tag=TAG).info(f"[STREAM-AUDIO] stream_audio_chunk called for {session_id} with {len(audio_chunk)} bytes")
try:
if session_id not in self.streaming_sessions:
logger.bind(tag=TAG).warning(f"[STREAM-AUDIO] No active streaming session for {session_id}")
return None
session_data = self.streaming_sessions[session_id]
session_data['audio_count'] += 1
# Add audio chunk directly to buffer
session_data['audio_buffer'].append(audio_chunk)
logger.bind(tag=TAG).info(f"[STREAM-AUDIO] Added audio chunk #{session_data['audio_count']} ({len(audio_chunk)} bytes) to session {session_id}. Buffer size: {len(session_data['audio_buffer'])}")
# Return latest partial transcript if available
partial = session_data.get('partial_transcript', '')
if partial:
logger.bind(tag=TAG).debug(f"[STREAM-AUDIO] Returning partial transcript for {session_id}: '{partial}'")
return partial
return None
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-AUDIO] Error streaming audio chunk for {session_id}: {e}")
return None
async def end_streaming_session(self, conn, session_id: str) -> Tuple[str, Optional[str]]:
"""End the streaming ASR session and get final transcript.
Args:
conn: Connection object
session_id: Session identifier
Returns:
Tuple of (final_transcript, file_path)
"""
try:
if session_id not in self.streaming_sessions:
logger.bind(tag=TAG).warning(f"[STREAM-END] No active streaming session for {session_id}")
return "", None
session_data = self.streaming_sessions[session_id]
logger.bind(tag=TAG).info(f"[STREAM-END] Ending streaming session: {session_id}")
# Signal end of audio stream
session_data['session_active'] = False
logger.bind(tag=TAG).debug(f"[STREAM-END] Marked session {session_id} as inactive")
# Wait for streaming task to complete
if session_data['streaming_task']:
try:
logger.bind(tag=TAG).debug(f"[STREAM-END] Waiting for streaming task to complete for {session_id}")
await asyncio.wait_for(session_data['streaming_task'], timeout=3.0)
logger.bind(tag=TAG).debug(f"[STREAM-END] Streaming task completed for {session_id}")
except asyncio.TimeoutError:
logger.bind(tag=TAG).warning(f"[STREAM-END] Streaming task timeout for {session_id}, cancelling")
session_data['streaming_task'].cancel()
try:
await session_data['streaming_task']
except asyncio.CancelledError:
pass
# Get final transcript
final_transcript = session_data.get('final_transcript', '').strip()
audio_count = session_data.get('audio_count', 0)
logger.bind(tag=TAG).info(f"[STREAM-END] Session {session_id} processed {audio_count} audio chunks")
logger.bind(tag=TAG).info(f"[STREAM-END] Final transcript for {session_id}: '{final_transcript}'")
# Clean up session
del self.streaming_sessions[session_id]
return final_transcript, None
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-END] Error ending streaming session {session_id}: {e}")
import traceback
logger.bind(tag=TAG).error(f"[STREAM-END] Traceback: {traceback.format_exc()}")
return "", None

View file

@ -1,194 +1,376 @@
{
"Baa Baa Black Sheep": {
"romanized": "Baa Baa Black Sheep",
"filename": "Baa Baa Black Sheep.mp3",
"alternatives": [
"Baa Baa Black Sheep",
"baa baa black sheep",
"black sheep song",
"sheep song",
"nursery rhyme sheep",
"wool song",
"classic nursery rhyme",
"baa baa"
]
},
"Baby Shark Dance": {
"romanized": "Baby Shark Dance",
"filename": "Baby Shark Dance.mp3",
"alternatives": [
"Baby Shark Dance",
"baby shark",
"shark song",
"doo doo doo",
"baby shark family",
"shark dance",
"kids shark song",
"popular kids song",
"viral kids song"
]
},
"Five Little Animals": {
"romanized": "Five Little Animals",
"filename": "Five Little Animals.mp3",
"alternatives": [
"Five Little Animals",
"five animals",
"little animals",
"counting animals",
"animal counting song",
"5 little animals",
"animals song",
"counting song"
]
},
"Five Little Ducks": {
"romanized": "Five Little Ducks",
"filename": "Five Little Ducks.mp3",
"alternatives": [
"Five Little Ducks",
"five ducks",
"little ducks",
"duck song",
"counting ducks",
"5 little ducks",
"ducks went swimming",
"mother duck song",
"quack quack song"
]
},
"Once I Caught A Fish Alive": {
"romanized": "Once I Caught A Fish Alive",
"filename": "Once I Caught A Fish Alive.mp3",
"alternatives": [
"Once I Caught A Fish Alive",
"fish alive",
"caught a fish",
"fishing song",
"fish counting song",
"1 2 3 4 5 fish",
"counting fish",
"fish nursery rhyme"
]
},
"Ten Little Dinos": {
"romanized": "Ten Little Dinos",
"filename": "Ten Little Dinos.mp3",
"alternatives": [
"Ten Little Dinos",
"ten dinos",
"little dinosaurs",
"dinosaur song",
"counting dinosaurs",
"10 little dinos",
"dino counting song",
"prehistoric song",
"kids dinosaur song"
]
},
"The Wheels on the Bus": {
"romanized": "The Wheels on the Bus",
"filename": "The Wheels on the Bus.mp3",
"alternatives": [
"The Wheels on the Bus",
"wheels on the bus",
"bus song",
"wheels go round and round",
"children's bus song",
"classic kids song",
"nursery rhyme bus",
"preschool bus song",
"traditional children's song",
"kids transport song",
"bus wheels song",
"go round and round"
]
"Baa Baa Black Sheep": {
"romanized": "Baa Baa Black Sheep",
"filename": "Baa Baa Black Sheep.mp3",
"alternatives": [
"Baa Baa Black Sheep",
"baa baa black sheep",
"black sheep song",
"sheep song",
"nursery rhyme sheep",
"wool song",
"classic nursery rhyme",
"baa baa"
]
},
"Head Shoulders Knees and Toes": {
"romanized": "Head Shoulders Knees and Toes",
"filename": "Head, Shoulders, Knees and Toes.mp3",
"alternatives": [
"head shoulders knees and toes",
"body parts song",
"action song",
"exercise song",
"kids body song",
"nursery action song",
"movement song",
"body song"
]
},
"Hot Cross Buns": {
"romanized": "Hot Cross Buns",
"filename": "Hot Cross Buns.mp3",
"alternatives": [
"hot cross buns",
"easter song",
"buns song",
"one a penny",
"two a penny",
"traditional nursery rhyme",
"food song",
"classic rhyme"
]
},
"I'm A Little Teapot": {
"romanized": "I'm A Little Teapot",
"filename": "I'm A Little Teapot.mp3",
"alternatives": [
"i'm a little teapot",
"little teapot",
"teapot song",
"short and stout",
"tip me over",
"pour me out",
"action nursery rhyme",
"tea song"
]
},
"Johny Johny Yes Papa": {
"romanized": "Johny Johny Yes Papa",
"filename": "Johny Johny Yes Papa.mp3",
"alternatives": [
"johny johny yes papa",
"johnny johnny",
"yes papa",
"eating sugar",
"no papa",
"telling lies",
"open your mouth",
"ha ha ha",
"popular kids song"
]
},
"Rain Rain Go Away": {
"romanized": "Rain Rain Go Away",
"filename": "Rain rain go away.mp3",
"alternatives": [
"rain rain go away",
"come again another day",
"rain song",
"weather song",
"little johnny wants to play",
"rainy day song",
"nursery weather song",
"rain rhyme"
]
},
"Twinkle Twinkle Little Star": {
"romanized": "Twinkle Twinkle Little Star",
"filename": "Twinkle Twinkle Little Star.mp3",
"alternatives": [
"twinkle twinkle little star",
"twinkle twinkle",
"little star",
"how i wonder what you are",
"star song",
"night song",
"lullaby",
"classic nursery rhyme",
"bedtime song",
"diamond in the sky"
]
}
}
"Baby Shark Dance": {
"romanized": "Baby Shark Dance",
"filename": "Baby Shark Dance.mp3",
"alternatives": [
"Baby Shark Dance",
"baby shark",
"shark song",
"doo doo doo",
"baby shark family",
"shark dance",
"kids shark song",
"popular kids song",
"viral kids song"
]
},
"Five Little Animals": {
"romanized": "Five Little Animals",
"filename": "Five Little Animals.mp3",
"alternatives": [
"Five Little Animals",
"five animals",
"little animals",
"counting animals",
"animal counting song",
"5 little animals",
"animals song",
"counting song"
]
},
"Five Little Ducks": {
"romanized": "Five Little Ducks",
"filename": "Five Little Ducks.mp3",
"alternatives": [
"Five Little Ducks",
"five ducks",
"little ducks",
"duck song",
"counting ducks",
"5 little ducks",
"ducks went swimming",
"mother duck song",
"quack quack song"
]
},
"Once I Caught A Fish Alive": {
"romanized": "Once I Caught A Fish Alive",
"filename": "Once I Caught A Fish Alive.mp3",
"alternatives": [
"Once I Caught A Fish Alive",
"fish alive",
"caught a fish",
"fishing song",
"fish counting song",
"1 2 3 4 5 fish",
"counting fish",
"fish nursery rhyme"
]
},
"Ten Little Dinos": {
"romanized": "Ten Little Dinos",
"filename": "Ten Little Dinos.mp3",
"alternatives": [
"Ten Little Dinos",
"ten dinos",
"little dinosaurs",
"dinosaur song",
"counting dinosaurs",
"10 little dinos",
"dino counting song",
"prehistoric song",
"kids dinosaur song"
]
},
"The Wheels on the Bus": {
"romanized": "The Wheels on the Bus",
"filename": "The Wheels on the Bus.mp3",
"alternatives": [
"The Wheels on the Bus",
"wheels on the bus",
"bus song",
"wheels go round and round",
"children's bus song",
"classic kids song",
"nursery rhyme bus",
"preschool bus song",
"traditional children's song",
"kids transport song",
"bus wheels song",
"go round and round"
]
},
"Head Shoulders Knees and Toes": {
"romanized": "Head Shoulders Knees and Toes",
"filename": "Head, Shoulders, Knees and Toes.mp3",
"alternatives": [
"head shoulders knees and toes",
"body parts song",
"action song",
"exercise song",
"kids body song",
"nursery action song",
"movement song",
"body song"
]
},
"Hot Cross Buns": {
"romanized": "Hot Cross Buns",
"filename": "Hot Cross Buns.mp3",
"alternatives": [
"hot cross buns",
"easter song",
"buns song",
"one a penny",
"two a penny",
"traditional nursery rhyme",
"food song",
"classic rhyme"
]
},
"I'm A Little Teapot": {
"romanized": "I'm A Little Teapot",
"filename": "I'm A Little Teapot.mp3",
"alternatives": [
"i'm a little teapot",
"little teapot",
"teapot song",
"short and stout",
"tip me over",
"pour me out",
"action nursery rhyme",
"tea song"
]
},
"Johny Johny Yes Papa": {
"romanized": "Johny Johny Yes Papa",
"filename": "Johny Johny Yes Papa.mp3",
"alternatives": [
"johny johny yes papa",
"johnny johnny",
"yes papa",
"eating sugar",
"no papa",
"telling lies",
"open your mouth",
"ha ha ha",
"popular kids song"
]
},
"Rain Rain Go Away": {
"romanized": "Rain Rain Go Away",
"filename": "Rain rain go away.mp3",
"alternatives": [
"rain rain go away",
"come again another day",
"rain song",
"weather song",
"little johnny wants to play",
"rainy day song",
"nursery weather song",
"rain rhyme"
]
},
"Twinkle Twinkle Little Star": {
"romanized": "Twinkle Twinkle Little Star",
"filename": "Twinkle Twinkle Little Star.mp3",
"alternatives": [
"twinkle twinkle little star",
"twinkle twinkle",
"little star",
"how i wonder what you are",
"star song",
"night song",
"lullaby",
"classic nursery rhyme",
"bedtime song",
"diamond in the sky"
]
},
"River Woods": {
"romanized": "River Woods",
"filename": "River Woods.mp3",
"alternatives": [
"river woods",
"nature song",
"forest song",
"woodland song",
"river song",
"outdoor song",
"kids nature song"
]
},
"Hickory": {
"romanized": "Hickory",
"filename": "Hickory.mp3",
"alternatives": [
"hickory",
"hickory dickory dock",
"mouse ran up the clock",
"clock song",
"time song",
"mouse song",
"classic nursery rhyme"
]
},
"Mary Lamb": {
"romanized": "Mary Lamb",
"filename": "Mary Lamb.mp3",
"alternatives": [
"mary had a little lamb",
"little lamb",
"lamb song",
"mary lamb",
"fleece was white as snow",
"school song",
"classic nursery rhyme"
]
},
"One Two": {
"romanized": "One Two",
"filename": "One Two.mp3",
"alternatives": [
"one two",
"buckle my shoe",
"counting song",
"number song",
"1 2 buckle my shoe",
"learning numbers",
"counting rhyme"
]
},
"Bingo": {
"romanized": "Bingo",
"filename": "Bingo.mp3",
"alternatives": [
"bingo",
"b-i-n-g-o",
"farmer had a dog",
"dog song",
"spelling song",
"letter song",
"classic nursery rhyme"
]
},
"Hush Baby": {
"romanized": "Hush Baby",
"filename": "Hush Baby.mp3",
"alternatives": [
"hush baby",
"hush little baby",
"don't say a word",
"mockingbird",
"lullaby",
"bedtime song",
"sleep song"
]
},
"Happy": {
"romanized": "Happy",
"filename": "Happy.mp3",
"alternatives": [
"happy",
"if you're happy and you know it",
"clap your hands",
"action song",
"movement song",
"kids activity song"
]
},
"Sleeping": {
"romanized": "Sleeping",
"filename": "Sleeping.mp3",
"alternatives": [
"sleeping",
"are you sleeping",
"brother john",
"frere jacques",
"morning bells",
"wake up song",
"lullaby"
]
},
"Hokey": {
"romanized": "Hokey",
"filename": "Hokey.mp3",
"alternatives": [
"hokey",
"hokey pokey",
"put your right hand in",
"shake it all about",
"action song",
"dance song",
"movement song"
]
},
"ABC Song": {
"romanized": "ABC Song",
"filename": "ABC Song.mp3",
"alternatives": [
"abc song",
"alphabet song",
"a b c d e f g",
"learning letters",
"alphabet",
"letter song",
"educational song"
]
},
"Splashing In The Sea Numbers": {
"romanized": "Splashing In The Sea Numbers",
"filename": "Splashing In The Sea Numbers.mp3",
"alternatives": [
"splashing in the sea",
"sea numbers",
"ocean counting",
"water song",
"beach song",
"counting song",
"sea creatures"
]
},
"Five Little Monkeys Jumping On The Bed": {
"romanized": "Five Little Monkeys Jumping On The Bed",
"filename": "Five Little Monkeys Jumping On The Bed.mp3",
"alternatives": [
"five little monkeys",
"jumping on the bed",
"monkeys jumping",
"one fell off",
"no more monkeys",
"counting monkeys",
"bedtime story song"
]
},
"Five Little Piggies Jumping On The Bed": {
"romanized": "Five Little Piggies Jumping On The Bed",
"filename": "Five Little Piggies Jumping On The Bed.mp3",
"alternatives": [
"five little piggies",
"piggies jumping on bed",
"little pigs jumping",
"pig song",
"counting pigs",
"farm animals",
"bedtime song"
]
},
"Old MacDonald": {
"romanized": "Old MacDonald",
"filename": "Old MacDonald.mp3",
"alternatives": [
"old macdonald",
"had a farm",
"e-i-e-i-o",
"farm song",
"animal sounds",
"cow goes moo",
"farm animals",
"classic nursery rhyme"
]
}
}

View file

@ -449,7 +449,9 @@ def initialize_multilingual_music_system(conn):
if SEMANTIC_SEARCH is None:
try:
semantic_config = conn.config.get('semantic_search', {})
if semantic_config.get('enabled', True):
if semantic_config.get('enabled', False):
SEMANTIC_SEARCH = SemanticMusicSearch(semantic_config)
if SEMANTIC_SEARCH.initialize():
conn.logger.bind(tag=TAG).info("Semantic music search initialized successfully")

View file

@ -1,839 +1,3 @@
# import os
# import re
# import time
# import random
# import difflib
# import traceback
# from pathlib import Path
# from core.handle.sendAudioHandle import send_stt_message
# from plugins_func.register import register_function, ToolType, ActionResponse, Action
# from core.utils.dialogue import Message
# from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
# from plugins_func.utils.multilingual_matcher import MultilingualMatcher
# # S3 Streaming imports
# import boto3
# from botocore.exceptions import ClientError
# import logging
# # CDN Download imports
# from core.utils.cdn_manager import download_cdn_file
# TAG = __name__
# STORY_CACHE = {}
# STORY_MULTILINGUAL_MATCHER = None
# # S3 Configuration
# S3_CLIENT = None
# S3_BUCKET_NAME = "cheeko-audio-files"
# # Story categories mapping for better recognition
# STORY_CATEGORIES = {
# "bedtime": ["Bedtime", "bedtime story", "sleep story", "night story"],
# "fantasy": ["Fantasy", "fantasy story", "magical story", "magic story"],
# "fairy tales": ["Fairy Tales", "fairy tale", "fairytale"],
# "educational": ["Educational", "educational story", "learning story", "education"],
# "adventure": ["Adventure", "adventure story", "exciting story"]
# }
# play_story_function_desc = {
# "type": "function",
# "function": {
# "name": "play_story",
# "description": (
# "CRITICAL: This function ONLY plays pre-recorded story audio files from the stories folder. "
# "NEVER generate, create, or tell stories using text. ALWAYS call this function for ANY story request. "
# "This plays actual audio story files, not generated text stories. "
# "MANDATORY: Use this function for ALL story requests including: 'tell me a story', 'story please', "
# "'I want to hear a story', 'play a bedtime story', 'tell me The Boy Who Cried Wolf', etc. "
# "DO NOT create stories with text - only play pre-recorded audio story files. "
# "Examples: 'tell me a story' → play random story file, 'bedtime story' → play bedtime category file, "
# "'कहानी सुनाओ' (Hindi) → play story file, 'ಕಥೆ ಹೇಳಿ' (Kannada) → play story file"
# ),
# "parameters": {
# "type": "object",
# "properties": {
# "user_request": {
# "type": "string",
# "description": "Complete user request for story. Examples: 'tell me a story', 'tell me The Boy Who Cried Wolf story', 'play a bedtime story', 'I want to hear a fantasy story', 'story please', 'कहानी सुनाओ', 'ಕಥೆ ಹೇಳಿ'",
# },
# "story_type": {
# "type": "string",
# "enum": ["specific", "category", "random"],
# "description": "Use 'specific' for ANY story title, name, or specific story request (e.g., 'golden gift story', 'The Boy Who Cried Wolf', 'Cinderella', 'three little pigs'). Use 'category' for category requests like 'bedtime story', 'fantasy story'. Use 'random' ONLY for very general requests like 'tell me any story', 'play a story'."
# },
# "category_preference": {
# "type": "string",
# "description": "Story category if mentioned: 'bedtime', 'fantasy', 'fairy tales', 'educational', 'adventure'. Only set if explicitly mentioned.",
# },
# "requested_language": {
# "type": "string",
# "description": "Language user requested the story in (e.g., 'hindi', 'english', 'kannada'). Note: Stories may be available in multiple languages depending on metadata.",
# }
# },
# "required": ["user_request", "story_type"],
# },
# },
# }
# @register_function("play_story", play_story_function_desc, ToolType.SYSTEM_CTL)
# def play_story(conn, user_request: str, story_type: str = "random", category_preference: str = None, requested_language: str = None):
# try:
# # Initialize multilingual story system
# initialize_multilingual_story_system(conn)
# # Log the request for debugging
# conn.logger.bind(tag=TAG).info(f"Story request: '{user_request}', type: {story_type}, category: {category_preference}, language: {requested_language}")
# # Check event loop status
# if not conn.loop.is_running():
# conn.logger.bind(tag=TAG).error("Event loop not running, cannot submit task")
# return ActionResponse(
# action=Action.RESPONSE, result="System busy", response="Please try again later"
# )
# # Submit async task with enhanced parameters
# task = conn.loop.create_task(
# handle_multilingual_story_command(conn, user_request, story_type, category_preference, requested_language)
# )
# # Non-blocking callback handling
# def handle_done(f):
# try:
# f.result()
# conn.logger.bind(tag=TAG).info("Multilingual story playback completed")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Multilingual story playback failed: {e}")
# task.add_done_callback(handle_done)
# return ActionResponse(
# action=Action.NONE,
# result="Multilingual story command received",
# response="Let me find a wonderful story for you!"
# )
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Error handling multilingual story request: {e}")
# return ActionResponse(
# action=Action.RESPONSE, result=str(e), response="Error occurred while processing your story request"
# )
# def normalize_category_name(category_input):
# """Normalize story category name to match folder names"""
# if not category_input:
# return None
# category_lower = category_input.lower().strip()
# # Direct mapping for exact matches from LLM
# direct_mappings = {
# "bedtime": "Bedtime",
# "fantasy": "Fantasy",
# "fairy tales": "Fairy Tales",
# "educational": "Educational",
# "adventure": "Adventure",
# "random": None # None means select random category
# }
# # Check direct mappings first
# if category_lower in direct_mappings:
# return direct_mappings[category_lower]
# # Check against category variations
# for key, variations in STORY_CATEGORIES.items():
# for variation in variations:
# if variation.lower() in category_lower or category_lower in variation.lower():
# # Return the actual folder name
# if key == "bedtime":
# return "Bedtime"
# elif key == "fantasy":
# return "Fantasy"
# elif key == "fairy tales":
# return "Fairy Tales"
# elif key == "educational":
# return "Educational"
# elif key == "adventure":
# return "Adventure"
# # If no match, return None to trigger random selection
# return None
# def get_story_files(story_dir, story_ext):
# """Get all story files organized by category - S3 MODE: Read from metadata.json"""
# import json
# story_dir = Path(story_dir)
# story_files_by_category = {}
# all_story_files = []
# # Check if stories directory exists
# if not story_dir.exists():
# return {}, []
# # Iterate through category folders
# for category_folder in story_dir.iterdir():
# if category_folder.is_dir():
# category_name = category_folder.name
# story_files_by_category[category_name] = []
# # Check for metadata.json file first (S3 mode)
# metadata_file = category_folder / "metadata.json"
# if metadata_file.exists():
# try:
# with open(metadata_file, 'r', encoding='utf-8') as f:
# metadata = json.load(f)
# # Add stories from metadata
# for story_title, story_info in metadata.items():
# filename = story_info.get('filename', f"{story_title}.mp3")
# relative_path = f"{category_name}/{filename}"
# story_files_by_category[category_name].append(relative_path)
# all_story_files.append(relative_path)
# logging.info(f"Loaded {len(metadata)} stories from {category_name} metadata")
# continue
# except Exception as e:
# logging.error(f"Error reading metadata from {metadata_file}: {e}")
# # Fallback: scan for actual audio files (legacy mode)
# for file in category_folder.rglob("*"):
# if file.is_file():
# ext = file.suffix.lower()
# if ext in story_ext:
# relative_path = str(file.relative_to(story_dir))
# story_files_by_category[category_name].append(relative_path)
# all_story_files.append(relative_path)
# return story_files_by_category, all_story_files
# def initialize_s3_client():
# """Initialize S3 client for streaming with SigV4"""
# global S3_CLIENT
# if S3_CLIENT is None:
# try:
# from botocore.config import Config
# aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
# aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
# aws_region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
# if aws_access_key and aws_secret_key:
# S3_CLIENT = boto3.client(
# 's3',
# aws_access_key_id=aws_access_key,
# aws_secret_access_key=aws_secret_key,
# region_name=aws_region,
# config=Config(signature_version="s3v4")
# )
# logging.info(f"S3 client initialized for story streaming (region: {aws_region})")
# else:
# logging.warning("AWS credentials not found, S3 streaming disabled")
# except Exception as e:
# logging.error(f"Failed to initialize S3 client: {e}")
# S3_CLIENT = None
# def generate_cdn_story_url(category, filename):
# """Generate CDN streaming URL for story file"""
# try:
# # Import CDN helper
# from utils.cdn_helper import get_audio_url
# # Ensure proper capitalization for S3 key (S3 folders are capitalized)
# # Handle special cases like "Fairy Tales"
# if category.lower() == "fairy tales":
# category_capitalized = "Fairy Tales"
# else:
# category_capitalized = category.capitalize()
# audio_path = f"stories/{category_capitalized}/{filename}"
# # Use CDN helper to generate URL with automatic encoding
# cdn_url = get_audio_url(audio_path)
# logging.info(f"Generated CDN URL for story: {audio_path} -> {cdn_url}")
# return cdn_url
# except Exception as e:
# logging.error(f"Error generating CDN URL for story: {e}")
# # Fallback to S3 presigned URL if CDN fails
# return generate_s3_story_url_fallback(category, filename)
# def generate_s3_story_url_fallback(category, filename):
# """Fallback S3 streaming URL for story file"""
# global S3_CLIENT, S3_BUCKET_NAME
# if not S3_CLIENT:
# return None
# try:
# # Ensure proper capitalization for S3 key (S3 folders are capitalized)
# # Handle special cases like "Fairy Tales"
# if category.lower() == "fairy tales":
# category_capitalized = "Fairy Tales"
# else:
# category_capitalized = category.capitalize()
# s3_key = f"stories/{category_capitalized}/{filename}"
# url = S3_CLIENT.generate_presigned_url(
# 'get_object',
# Params={'Bucket': S3_BUCKET_NAME, 'Key': s3_key},
# ExpiresIn=7200 # 2 hours for streaming
# )
# logging.info(f"Generated fallback S3 URL for story: {s3_key}")
# return url
# except ClientError as e:
# logging.error(f"Error generating fallback S3 URL for story: {e}")
# return None
# def initialize_story_handler(conn):
# """Initialize story handler with configuration"""
# global STORY_CACHE
# # Initialize S3 client
# initialize_s3_client()
# if STORY_CACHE == {}:
# if "play_story" in conn.config["plugins"]:
# STORY_CACHE["story_config"] = conn.config["plugins"]["play_story"]
# STORY_CACHE["story_dir"] = os.path.abspath(
# STORY_CACHE["story_config"].get("story_dir", "./stories")
# )
# STORY_CACHE["story_ext"] = STORY_CACHE["story_config"].get(
# "story_ext", (".mp3", ".wav", ".p3")
# )
# STORY_CACHE["refresh_time"] = STORY_CACHE["story_config"].get(
# "refresh_time", 300 # Refresh every 5 minutes
# )
# else:
# STORY_CACHE["story_dir"] = os.path.abspath("./stories")
# STORY_CACHE["story_ext"] = (".mp3", ".wav", ".p3")
# STORY_CACHE["refresh_time"] = 300
# # Get story files organized by category
# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files(
# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"]
# )
# STORY_CACHE["scan_time"] = time.time()
# # Log available categories
# if STORY_CACHE["story_files_by_category"]:
# conn.logger.bind(tag=TAG).info(
# f"Found story categories: {list(STORY_CACHE['story_files_by_category'].keys())}"
# )
# for category, files in STORY_CACHE["story_files_by_category"].items():
# conn.logger.bind(tag=TAG).info(f" {category}: {len(files)} stories")
# return STORY_CACHE
# def initialize_multilingual_story_system(conn):
# """Initialize the multilingual story matching system"""
# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE
# # Initialize basic story cache first
# initialize_story_handler(conn)
# # Initialize multilingual matcher if not already done
# if STORY_MULTILINGUAL_MATCHER is None:
# try:
# STORY_MULTILINGUAL_MATCHER = MultilingualMatcher(
# STORY_CACHE["story_dir"],
# STORY_CACHE["story_ext"]
# )
# if STORY_MULTILINGUAL_MATCHER.language_folders:
# conn.logger.bind(tag=TAG).info(f"Multilingual story matcher initialized with languages: {STORY_MULTILINGUAL_MATCHER.language_folders}")
# else:
# conn.logger.bind(tag=TAG).info("Multilingual story matcher initialized (no metadata.json found, using filesystem fallback)")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual story matcher: {e}")
# STORY_MULTILINGUAL_MATCHER = None
# async def handle_multilingual_story_command(conn, user_request: str, story_type: str, category_preference: str = None, requested_language: str = None):
# """Enhanced story command handler with multilingual AI matching"""
# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE
# conn.logger.bind(tag=TAG).debug(f"Processing multilingual story request: '{user_request}'")
# # Check if stories directory exists
# if not os.path.exists(STORY_CACHE["story_dir"]):
# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}")
# await send_stt_message(conn, "Sorry, I couldn't find the story collection.")
# return
# # Refresh cache if needed
# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]:
# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files(
# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"]
# )
# STORY_CACHE["scan_time"] = time.time()
# selected_story = None
# match_info = None
# # Try multilingual AI matching for specific stories
# if STORY_MULTILINGUAL_MATCHER and story_type == "specific":
# try:
# match_result = STORY_MULTILINGUAL_MATCHER.find_content_match(user_request, requested_language)
# if match_result:
# selected_story, detected_language, metadata_entry = match_result
# match_info = {
# 'method': 'ai_multilingual',
# 'language': detected_language,
# 'title': metadata_entry.get('romanized', 'Unknown'),
# 'original_title': list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[
# list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry)
# ] if detected_language in STORY_MULTILINGUAL_MATCHER.metadata_cache else 'Unknown',
# 'category': 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"AI story match found: {selected_story} ({detected_language})")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Error in AI story matching: {e}")
# # Try language-specific selection if no AI match and language is specified
# if not selected_story and requested_language and STORY_MULTILINGUAL_MATCHER:
# try:
# language_content = STORY_MULTILINGUAL_MATCHER.get_language_specific_content(requested_language)
# if language_content:
# selected_path, metadata_entry = random.choice(language_content)
# selected_story = selected_path
# match_info = {
# 'method': 'language_random',
# 'language': requested_language,
# 'title': metadata_entry.get('romanized', 'Unknown'),
# 'category': 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Language-specific story selection: {selected_story}")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Error in language-specific story selection: {e}")
# # Fallback to legacy category-based selection
# if not selected_story and category_preference:
# normalized_category = normalize_category_name(category_preference)
# if normalized_category and normalized_category in STORY_CACHE["story_files_by_category"]:
# if STORY_CACHE["story_files_by_category"][normalized_category]:
# selected_story = random.choice(STORY_CACHE["story_files_by_category"][normalized_category])
# match_info = {
# 'method': 'category_selection',
# 'language': 'english', # Default assumption
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': normalized_category
# }
# conn.logger.bind(tag=TAG).info(f"Category-based story selection: {selected_story}")
# # Try legacy specific story matching (for explicit specific requests)
# if not selected_story and story_type == "specific":
# # Extract story name and try fuzzy matching
# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"])
# if story_name_match:
# selected_story = story_name_match
# match_info = {
# 'method': 'legacy_fuzzy',
# 'language': 'english',
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Legacy fuzzy story match: {selected_story}")
# # SMART FALLBACK: Try specific story matching even for "random" requests that might contain story names
# # This handles cases where LLM misclassifies specific story requests as random
# if not selected_story and story_type != "specific":
# # Check if the request might contain a specific story name by trying fuzzy matching
# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"])
# if story_name_match:
# selected_story = story_name_match
# match_info = {
# 'method': 'smart_fallback_fuzzy',
# 'language': 'english',
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Smart fallback story match (LLM misclassified): {selected_story}")
# # Final fallback to random selection
# if not selected_story and STORY_CACHE["all_story_files"]:
# selected_story = random.choice(STORY_CACHE["all_story_files"])
# match_info = {
# 'method': 'random_fallback',
# 'language': 'english',
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Random story fallback: {selected_story}")
# # Play the selected story
# if selected_story:
# await play_multilingual_story(conn, selected_story, match_info, user_request)
# else:
# conn.logger.bind(tag=TAG).error("No stories found to play")
# await send_stt_message(conn, "Sorry, I couldn't find any stories to play.")
# async def play_multilingual_story(conn, selected_story: str, match_info: dict, original_request: str):
# """Play selected story with contextual introduction - CDN STREAMING VERSION"""
# global STORY_CACHE
# try:
# # Extract category and filename from selected_story path
# # selected_story format: "Fantasy/story.mp3" or "Adventure/story.mp3"
# path_parts = selected_story.split('/')
# if len(path_parts) >= 2:
# category = path_parts[0]
# filename = path_parts[1]
# else:
# # Fallback: try to get from match_info
# category = match_info.get('category', 'Fantasy')
# filename = os.path.basename(selected_story)
# # Generate CDN streaming URL
# cdn_url = generate_cdn_story_url(category, filename)
# if not cdn_url:
# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}")
# await send_stt_message(conn, "Sorry, I couldn't access the story file.")
# return
# # CRITICAL CHANGE: Download from CDN to local file first
# local_file_path = await download_cdn_file(cdn_url, conn)
# if not local_file_path:
# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}")
# await send_stt_message(conn, "Sorry, I couldn't download the story file.")
# return
# # Generate contextual introduction based on match info
# intro_text = generate_multilingual_story_intro(match_info, original_request)
# await send_stt_message(conn, intro_text)
# conn.dialogue.put(Message(role="assistant", content=intro_text))
# # Queue TTS messages with S3 URL
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.FIRST,
# content_type=ContentType.ACTION,
# )
# )
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.TEXT,
# content_detail=intro_text,
# )
# )
# # Use CDN URL instead of local file path
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.FILE,
# content_file=local_file_path, # LOCAL FILE, NOT CDN URL!
# )
# )
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.LAST,
# content_type=ContentType.ACTION,
# )
# )
# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes
# conn.llm_finish_task = True
# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}")
# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
# def generate_multilingual_story_intro(match_info: dict, original_request: str) -> str:
# """Generate contextual introduction based on matching method and info"""
# method = match_info.get('method', 'unknown')
# language = match_info.get('language', 'english')
# title = match_info.get('title', 'Unknown Story')
# category = match_info.get('category', 'story')
# original_title = match_info.get('original_title', title)
# # Clean up the title (remove underscores, etc.)
# clean_title = title.replace("_", " ").replace("-", " ")
# if method == 'ai_multilingual':
# if language != 'english':
# intros = [
# f"Perfect! I found '{clean_title}' for you!",
# f"Great choice! Here's the story '{clean_title}'!",
# f"I found exactly what you wanted: '{clean_title}'!",
# f"Let me tell you '{clean_title}' - this should be perfect!"
# ]
# else:
# intros = [
# f"I found '{clean_title}' which matches your request perfectly!",
# f"Here's '{clean_title}' - I think you'll love this story!",
# f"Playing '{clean_title}' based on your request!"
# ]
# elif method == 'language_random':
# intros = [
# f"Here's a wonderful story for you: '{clean_title}'!",
# f"Let me tell you '{clean_title}' - a beautiful story!",
# f"I picked '{clean_title}' from our collection!"
# ]
# elif method == 'category_selection':
# if category != 'unknown':
# intros = [
# f"Here's a lovely {category.lower()} story: '{clean_title}'!",
# f"Perfect! I have a {category.lower()} story for you: '{clean_title}'!",
# f"Let me tell you this {category.lower()} story called '{clean_title}'!"
# ]
# else:
# intros = [
# f"Here's a wonderful story: '{clean_title}'!",
# f"Let me tell you '{clean_title}'!",
# f"I have a great story for you: '{clean_title}'!"
# ]
# elif method == 'legacy_fuzzy':
# intros = [
# f"I think you'll love '{clean_title}'!",
# f"Here's '{clean_title}' - hope this is what you wanted!",
# f"Let me tell you the story of '{clean_title}'!"
# ]
# else: # random_fallback
# intros = [
# f"Let me tell you a wonderful story: '{clean_title}'!",
# f"Here's a great story for you: '{clean_title}'!",
# f"I have a special story called '{clean_title}'!"
# ]
# return random.choice(intros)
# def find_best_story_match(story_name, story_files):
# """Find the best matching story from available files with enhanced matching"""
# best_match = None
# highest_score = 0
# # Clean and normalize the input story name
# clean_story_name = story_name.lower().strip()
# # Remove common story words that don't help with matching
# story_words_to_remove = ['story', 'tale', 'a', 'the', 'play', 'tell', 'me']
# story_name_words = [word for word in clean_story_name.split() if word not in story_words_to_remove]
# for story_file in story_files:
# # Extract just the filename without path and extension
# file_name = os.path.splitext(os.path.basename(story_file))[0].lower()
# file_name_words = file_name.split()
# # Method 1: Direct sequence matching (existing approach)
# sequence_ratio = difflib.SequenceMatcher(None, clean_story_name, file_name).ratio()
# # Method 2: Word-based matching - check how many words match
# word_match_score = 0
# if story_name_words:
# matching_words = 0
# for word in story_name_words:
# if any(word in file_word for file_word in file_name_words):
# matching_words += 1
# word_match_score = matching_words / len(story_name_words)
# # Method 3: Partial string matching - check if story name is contained in filename
# containment_score = 0
# if clean_story_name in file_name or file_name in clean_story_name:
# containment_score = 0.8
# # Combine scores with weights
# combined_score = (sequence_ratio * 0.4) + (word_match_score * 0.4) + (containment_score * 0.2)
# # Lower threshold but use combined scoring for better matches
# if combined_score > highest_score and combined_score > 0.3:
# highest_score = combined_score
# best_match = story_file
# return best_match
# async def handle_story_command(conn, category, specific_story=None, requested_language=None):
# """Handle story playback command"""
# initialize_story_handler(conn)
# global STORY_CACHE
# conn.logger.bind(tag=TAG).debug(f"Handling story command - Category: {category}, Story: {specific_story}, Language: {requested_language}")
# # Check if stories directory exists
# if not os.path.exists(STORY_CACHE["story_dir"]):
# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}")
# await send_stt_message(conn, "Sorry, I couldn't find the story collection.")
# return
# # Refresh cache if needed
# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]:
# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files(
# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"]
# )
# STORY_CACHE["scan_time"] = time.time()
# selected_story = None
# # If specific story name is provided, try to find it
# if specific_story:
# selected_story = find_best_story_match(specific_story, STORY_CACHE["all_story_files"])
# if selected_story:
# conn.logger.bind(tag=TAG).info(f"Found matching story: {selected_story}")
# # If no specific story found, select based on category
# if not selected_story:
# if category and category.lower() != "random":
# # Normalize category name
# normalized_category = normalize_category_name(category)
# # Try to find the category
# matching_category = None
# for cat_name in STORY_CACHE["story_files_by_category"].keys():
# if cat_name.lower() == normalized_category.lower():
# matching_category = cat_name
# break
# if matching_category and STORY_CACHE["story_files_by_category"][matching_category]:
# selected_story = random.choice(STORY_CACHE["story_files_by_category"][matching_category])
# conn.logger.bind(tag=TAG).info(f"Selected {matching_category} story: {selected_story}")
# else:
# conn.logger.bind(tag=TAG).warning(f"Category '{category}' not found or empty, selecting random story")
# if STORY_CACHE["all_story_files"]:
# selected_story = random.choice(STORY_CACHE["all_story_files"])
# else:
# # Select random story from all available
# if STORY_CACHE["all_story_files"]:
# selected_story = random.choice(STORY_CACHE["all_story_files"])
# conn.logger.bind(tag=TAG).info(f"Selected random story: {selected_story}")
# if selected_story:
# await play_story_file(conn, selected_story, requested_language)
# else:
# conn.logger.bind(tag=TAG).error("No stories found in the collection")
# await send_stt_message(conn, "I'm sorry, I couldn't find any stories to play.")
# def get_story_intro(story_file, requested_language=None):
# """Generate an introduction for the story"""
# # Extract story name and category
# parts = story_file.split(os.sep)
# if len(parts) > 1:
# category = parts[0]
# story_name = os.path.splitext(parts[-1])[0]
# else:
# category = "story"
# story_name = os.path.splitext(story_file)[0]
# # Clean up the story name (remove underscores, etc.)
# story_name = story_name.replace("_", " ").replace("-", " ")
# # Always use English intros since stories are in English
# intros = [
# f"Let me tell you a wonderful {category.lower()} story called '{story_name}'",
# f"Here's a {category.lower()} story for you: '{story_name}'",
# f"Get comfortable and enjoy this {category.lower()} story: '{story_name}'",
# f"I have a special {category.lower()} story for you called '{story_name}'",
# f"Listen carefully to this amazing story: '{story_name}'",
# f" Let's begin '{story_name}'",
# ]
# intro = random.choice(intros)
# # Add note if requested in another language
# if requested_language and requested_language != "english":
# intro = f"Playing English story. {intro}"
# return intro
# async def play_story_file(conn, story_file, requested_language=None):
# """Play the selected story file - CDN STREAMING VERSION"""
# try:
# # Extract category and filename from story_file path
# path_parts = story_file.split('/')
# if len(path_parts) >= 2:
# category = path_parts[0]
# filename = path_parts[1]
# else:
# # Fallback
# category = "Fantasy"
# filename = os.path.basename(story_file)
# # Generate CDN streaming URL
# cdn_url = generate_cdn_story_url(category, filename)
# if not cdn_url:
# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}")
# await send_stt_message(conn, "Sorry, I couldn't access the story file.")
# return
# # CRITICAL CHANGE: Download from CDN to local file first
# local_file_path = await download_cdn_file(cdn_url, conn)
# if not local_file_path:
# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}")
# await send_stt_message(conn, "Sorry, I couldn't download the story file.")
# return
# # Generate and send introduction (always in English)
# intro_text = get_story_intro(story_file, requested_language)
# await send_stt_message(conn, intro_text)
# conn.dialogue.put(Message(role="assistant", content=intro_text))
# # Send TTS messages to play the story from CDN
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.FIRST,
# content_type=ContentType.ACTION,
# )
# )
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.TEXT,
# content_detail=intro_text,
# )
# )
# # Use CDN URL instead of local file path
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.FILE,
# content_file=local_file_path, # LOCAL FILE, NOT CDN URL!
# )
# )
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.LAST,
# content_type=ContentType.ACTION,
# )
# )
# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes
# conn.llm_finish_task = True
# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}")
# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
import os
import re
import time

View file

@ -53,8 +53,10 @@ class SemanticMusicSearch:
self.is_available = True
# Qdrant configuration
self.qdrant_url = self.config.get("qdrant_url", "https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io")
self.qdrant_api_key = self.config.get("qdrant_api_key", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk")
self.collection_name = self.config.get("collection_name", "xiaozhi_music")
# Embedding model configuration

View file

@ -43,4 +43,10 @@ amazon_transcribe
# Semantic search dependencies
qdrant-client>=1.7.0
sentence-transformers>=2.2.0
pyspellchecker>=0.7.0
pyspellchecker>=0.7.0
# Google Cloud Speech v2 dependencies
google-cloud-speech>=2.26.0
pyspellchecker>=0.7.0

View file

@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""
Test script for Google Cloud Speech-to-Text v2 ASR Provider
This script validates the provider implementation without requiring actual credentials
"""
import sys
import os
import asyncio
from unittest.mock import Mock, patch, MagicMock
# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Mock the Google Cloud Speech v2 imports before importing our provider
sys.modules['google.cloud.speech_v2'] = Mock()
sys.modules['google.api_core.exceptions'] = Mock()
from core.providers.asr.google_speech_v2 import ASRProvider
def test_provider_initialization():
"""Test that the provider initializes correctly with valid configuration"""
config = {
"project_id": "test-project-123",
"location": "global",
"credentials_path": "/path/to/credentials.json",
"model": "chirp_2",
"language_codes": ["en-US"],
"sample_rate_hertz": 16000,
"encoding": "LINEAR16",
"enable_automatic_punctuation": True,
"enable_word_time_offsets": False,
"enable_word_confidence": False,
"output_dir": "./tmp/"
}
print("Testing provider initialization...")
# Mock the Google Cloud client
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient') as mock_client:
mock_instance = Mock()
mock_client.return_value = mock_instance
try:
provider = ASRProvider(config, delete_audio_file=True)
print("[PASS] Provider initialized successfully")
# Verify configuration
assert provider.project_id == "test-project-123"
assert provider.model == "chirp_2"
assert provider.language_codes == ["en-US"]
assert provider.sample_rate_hertz == 16000
print("[PASS] Configuration validated")
# Verify recognizer name format
expected_recognizer = f"projects/{config['project_id']}/locations/{config['location']}/recognizers/_"
assert provider.recognizer_name == expected_recognizer
print("[PASS] Recognizer name format correct")
except Exception as e:
print(f"[FAIL] Provider initialization failed: {e}")
return False
return True
def test_audio_encoding_mapping():
"""Test the audio encoding mapping function"""
config = {
"project_id": "test-project",
"encoding": "LINEAR16"
}
print("Testing audio encoding mapping...")
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient'):
provider = ASRProvider(config, delete_audio_file=True)
# Test various encoding mappings
test_cases = [
("LINEAR16", "LINEAR16"),
("FLAC", "FLAC"),
("MP3", "MP3"),
("OGG_OPUS", "OGG_OPUS"),
]
for input_encoding, expected in test_cases:
provider.encoding = input_encoding
result = provider._get_audio_encoding()
print(f"[PASS] {input_encoding} -> {result}")
return True
async def test_speech_to_text_mock():
"""Test the speech_to_text method with mocked Google Cloud API response"""
config = {
"project_id": "test-project",
"location": "global",
"model": "chirp_2",
"language_codes": ["en-US"],
"sample_rate_hertz": 16000,
"encoding": "LINEAR16",
"output_dir": "./tmp/"
}
print("Testing speech_to_text method...")
# Create mock audio data (simulating Opus packets)
mock_opus_data = [b"fake_opus_packet_1", b"fake_opus_packet_2"]
# Mock the Google Cloud response
mock_alternative = Mock()
mock_alternative.transcript = "Hello, this is a test transcript"
mock_alternative.confidence = 0.95
mock_result = Mock()
mock_result.alternatives = [mock_alternative]
mock_channel = Mock()
mock_channel.alternatives = [mock_alternative]
mock_response = Mock()
mock_response.results = [mock_result]
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient') as mock_client_class:
mock_client = Mock()
mock_client_class.return_value = mock_client
mock_client.recognize.return_value = mock_response
# Mock other dependencies
with patch('core.providers.asr.google_speech_v2.ASRProviderBase.decode_opus') as mock_decode, \
patch('core.providers.asr.google_speech_v2.ASRProviderBase.save_audio_to_file') as mock_save, \
patch('core.providers.asr.google_speech_v2.ASRProviderBase.log_audio_transcript') as mock_log, \
patch('os.makedirs'):
# Configure mocks
mock_decode.return_value = [b"pcm_data_1", b"pcm_data_2"]
mock_save.return_value = "/tmp/test_audio.wav"
provider = ASRProvider(config, delete_audio_file=False)
# Test the speech_to_text method
try:
result_text, file_path = await provider.speech_to_text(
mock_opus_data,
session_id="test_session_123",
audio_format="opus"
)
print(f"[PASS] Speech-to-text completed")
print(f" Result: '{result_text}'")
print(f" File path: {file_path}")
# Verify the result
assert result_text == "Hello, this is a test transcript"
assert file_path == "/tmp/test_audio.wav"
# Verify Google Cloud API was called correctly
mock_client.recognize.assert_called_once()
print("[PASS] Google Cloud API called with correct parameters")
except Exception as e:
print(f"[FAIL] Speech-to-text test failed: {e}")
import traceback
traceback.print_exc()
return False
return True
def test_configuration_validation():
"""Test configuration validation and edge cases"""
print("Testing configuration validation...")
# Test minimal configuration
minimal_config = {
"project_id": "test-project"
}
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient'), \
patch('os.makedirs'):
provider = ASRProvider(minimal_config, delete_audio_file=True)
# Verify defaults
assert provider.location == "global"
assert provider.model == "chirp_2"
assert provider.language_codes == ["en-US"]
assert provider.sample_rate_hertz == 16000
assert provider.encoding == "LINEAR16"
print("[PASS] Default values applied correctly")
return True
def main():
"""Run all tests"""
print("Testing Google Cloud Speech-to-Text v2 ASR Provider")
print("=" * 60)
tests = [
("Provider Initialization", test_provider_initialization),
("Audio Encoding Mapping", test_audio_encoding_mapping),
("Configuration Validation", test_configuration_validation),
("Speech-to-Text (Mocked)", lambda: asyncio.run(test_speech_to_text_mock())),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
print(f"\nRunning: {test_name}")
try:
if test_func():
print(f"[PASS] {test_name}: PASSED")
passed += 1
else:
print(f"[FAIL] {test_name}: FAILED")
except Exception as e:
print(f"[ERROR] {test_name}: ERROR - {e}")
print("\n" + "=" * 60)
print(f"Test Results: {passed}/{total} tests passed")
if passed == total:
print("All tests passed! Google Speech v2 provider is ready to use.")
print("\nNext steps:")
print("1. Install dependencies: pip install google-cloud-speech>=2.26.0")
print("2. Set up Google Cloud credentials")
print("3. Update selected_module.ASR in config.yaml to: GoogleSpeechV2")
print("4. Configure your Google Cloud project settings")
else:
print("Some tests failed. Please check the implementation.")
sys.exit(1)
if __name__ == "__main__":
main()