This commit is contained in:
rahulpscraftech360 2025-08-26 12:13:58 +05:30
parent 2b956a925f
commit 7ccdbe3c96
58 changed files with 1406 additions and 54 deletions

View file

@ -19,9 +19,9 @@ import opuslib
# --- Configuration ---
SERVER_IP = "192.168.1.105" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8002
MQTT_BROKER_HOST = "192.168.1.105" # MQTT gateway IP
SERVER_IP = "192.168.1.107" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8003
MQTT_BROKER_HOST = "192.168.1.107" # MQTT gateway IP
MQTT_BROKER_PORT = 1883

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -9,81 +9,208 @@ 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
TAG = __name__
MUSIC_CACHE = {}
MULTILINGUAL_MATCHER = None
play_music_function_desc = {
"type": "function",
"function": {
"name": "play_music",
"description": "唱歌、听歌、播放音乐的方法。",
"description": "Advanced multilingual music player that understands natural language requests in any language. Supports specific song requests, language preferences, mood-based selection, and educational content. Handles requests like 'play Baa Baa Black Sheep', 'sing a Hindi song', 'play phonics', 'I want energetic music', 'play something in Telugu', etc. Uses AI-powered matching to find songs even with different spellings or scripts.",
"parameters": {
"type": "object",
"properties": {
"song_name": {
"user_request": {
"type": "string",
"description": "歌曲名称,如果用户没有指定具体歌名则为'random', 明确指定的时返回音乐的名字 示例: ```用户:播放两只老虎\n参数:两只老虎``` ```用户:播放音乐 \n参数:random ```",
"description": "Complete user request for music. Include the full original request to enable intelligent matching. Examples: 'play Baa Baa Black Sheep', 'sing Hanuman Chalisa', 'play any Hindi song', 'I want Telugu music', 'play phonics songs', 'something energetic', 'play music for kids'",
},
"language_preference": {
"type": "string",
"description": "Detected or requested language preference. Options: 'english', 'hindi', 'telugu', 'kannada', 'tamil', 'phonics', or 'any'. Only set if explicitly mentioned or clearly implied.",
},
"song_type": {
"type": "string",
"enum": ["specific", "random", "language_specific", "educational"],
"description": "Type of request: 'specific' for named songs (e.g., 'play Hanuman Chalisa', 'bandar mama song'), 'random' for any song, 'language_specific' for language-only requests (e.g., 'play Hindi song'), 'educational' for phonics/learning content"
}
},
"required": ["song_name"],
"required": ["user_request", "song_type"],
},
},
}
@register_function("play_music", play_music_function_desc, ToolType.SYSTEM_CTL)
def play_music(conn, song_name: str):
def play_music(conn, user_request: str, song_type: str = "random", language_preference: str = None):
try:
music_intent = (
f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
)
# Initialize multilingual matcher
initialize_multilingual_music_system(conn)
# Log the request for debugging
conn.logger.bind(tag=TAG).info(f"Music request: '{user_request}', type: {song_type}, language: {language_preference}")
# 检查事件循环状态
# Check event loop status
if not conn.loop.is_running():
conn.logger.bind(tag=TAG).error("事件循环未运行,无法提交任务")
conn.logger.bind(tag=TAG).error("Event loop is not running, unable to submit task")
return ActionResponse(
action=Action.RESPONSE, result="系统繁忙", response="请稍后再试"
action=Action.RESPONSE, result="System busy", response="Please try again later"
)
# 提交异步任务
# Submit async task with enhanced parameters
task = conn.loop.create_task(
handle_music_command(conn, music_intent) # 封装异步逻辑
handle_multilingual_music_command(conn, user_request, song_type, language_preference)
)
# 非阻塞回调处理
# Non-blocking callback handling
def handle_done(f):
try:
f.result() # 可在此处理成功逻辑
conn.logger.bind(tag=TAG).info("播放完成")
f.result()
conn.logger.bind(tag=TAG).info("Multilingual music playback completed")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放失败: {e}")
conn.logger.bind(tag=TAG).error(f"Multilingual music playback failed: {e}")
task.add_done_callback(handle_done)
return ActionResponse(
action=Action.NONE, result="指令已接收", response="正在为您播放音乐"
action=Action.NONE,
result="Multilingual music command received",
response="Let me find the perfect song for you!"
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
conn.logger.bind(tag=TAG).error(f"Error handling multilingual music request: {e}")
return ActionResponse(
action=Action.RESPONSE, result=str(e), response="播放音乐时出错了"
action=Action.RESPONSE, result=str(e), response="Error occurred while processing your music request"
)
def _extract_song_name(text):
"""从用户输入中提取歌名"""
for keyword in ["播放音乐"]:
if keyword in text:
parts = text.split(keyword)
if len(parts) > 1:
return parts[1].strip()
"""Extract song name from user input with multiple trigger patterns"""
# Define various music-related keywords and patterns
music_keywords = [
"play music",
"play",
"sing",
"sing a song",
"sing me",
"can you sing",
"put on some music",
"put on",
"I want to hear",
"listen to",
"play some music",
"music"
]
text_lower = text.lower()
# Try to extract song name after various patterns
for keyword in music_keywords:
keyword_lower = keyword.lower()
if keyword_lower in text_lower:
# Find the position of the keyword
keyword_pos = text_lower.find(keyword_lower)
# Extract everything after the keyword
after_keyword = text[keyword_pos + len(keyword):].strip()
# Remove common words that might follow
common_words = ["for me", "please", "now", "some", "a song", "the song"]
for word in common_words:
after_keyword = after_keyword.replace(word, "").strip()
# If we found something meaningful after the keyword, return it
if after_keyword and len(after_keyword) > 1:
return after_keyword
return None
def _detect_language_request(text):
"""Detect if user is requesting music from a specific language/folder"""
text_lower = text.lower()
# Define language mappings (you can add more languages as needed)
language_mappings = {
# Phonics variations (Educational content)
"phonics": "phonics",
"phonics song": "phonics",
"phonics music": "phonics",
"play phonics": "phonics",
"sing phonics": "phonics",
"learn phonics": "phonics",
"phonics sounds": "phonics",
"alphabet sounds": "phonics",
"letter sounds": "phonics",
# English variations
"english": "English",
"english song": "English",
"english music": "English",
"any english": "English",
# Telugu variations
"telugu": "Telugu",
"telugu song": "Telugu",
"telugu music": "Telugu",
"any telugu": "Telugu",
# Hindi variations
"hindi": "Hindi",
"hindi song": "Hindi",
"hindi music": "Hindi",
"any hindi": "Hindi",
# Tamil variations
"tamil": "Tamil",
"tamil song": "Tamil",
"tamil music": "Tamil",
"any tamil": "Tamil",
# Add more languages as needed
"kannada": "Kannada",
"malayalam": "Malayalam",
"bengali": "Bengali",
"punjabi": "Punjabi",
"marathi": "Marathi",
"gujarati": "Gujarati",
}
# Check for language requests
for key, folder_name in language_mappings.items():
if key in text_lower:
return folder_name
return None
def _get_language_specific_files(music_dir, music_ext, language_folder):
"""Get music files from a specific language folder"""
language_path = Path(music_dir) / language_folder
if not language_path.exists():
return [], []
music_files = []
music_file_names = []
for file in language_path.rglob("*"):
if file.is_file():
ext = file.suffix.lower()
if ext in music_ext:
# Get relative path from the main music directory
relative_path = str(file.relative_to(Path(music_dir)))
music_files.append(relative_path)
music_file_names.append(os.path.splitext(relative_path)[0])
return music_files, music_file_names
def _find_best_match(potential_song, music_files):
"""查找最匹配的歌曲"""
"""Find the best matching song"""
best_match = None
highest_ratio = 0
@ -101,13 +228,13 @@ def get_music_files(music_dir, music_ext):
music_files = []
music_file_names = []
for file in music_dir.rglob("*"):
# 判断是否是文件
# Check if it's a file
if file.is_file():
# 获取文件扩展名
# Get file extension
ext = file.suffix.lower()
# 判断扩展名是否在列表中
# Check if extension is in the list
if ext in music_ext:
# 添加相对路径
# Add relative path
music_files.append(str(file.relative_to(music_dir)))
music_file_names.append(
os.path.splitext(str(file.relative_to(music_dir)))[0]
@ -121,7 +248,7 @@ def initialize_music_handler(conn):
if "play_music" in conn.config["plugins"]:
MUSIC_CACHE["music_config"] = conn.config["plugins"]["play_music"]
MUSIC_CACHE["music_dir"] = os.path.abspath(
MUSIC_CACHE["music_config"].get("music_dir", "./music") # 默认路径修改
MUSIC_CACHE["music_config"].get("music_dir", "./music") # Default path modified
)
MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get(
"music_ext", (".mp3", ".wav", ".p3")
@ -133,47 +260,320 @@ def initialize_music_handler(conn):
MUSIC_CACHE["music_dir"] = os.path.abspath("./music")
MUSIC_CACHE["music_ext"] = (".mp3", ".wav", ".p3")
MUSIC_CACHE["refresh_time"] = 60
# 获取音乐文件列表
# Get music file list
MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(
MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"]
)
MUSIC_CACHE["scan_time"] = time.time()
return MUSIC_CACHE
def initialize_multilingual_music_system(conn):
"""Initialize the multilingual music matching system"""
global MULTILINGUAL_MATCHER, MUSIC_CACHE
# Initialize basic music cache first
initialize_music_handler(conn)
# Initialize multilingual matcher if not already done
if MULTILINGUAL_MATCHER is None:
try:
MULTILINGUAL_MATCHER = MultilingualMatcher(
MUSIC_CACHE["music_dir"],
MUSIC_CACHE["music_ext"]
)
conn.logger.bind(tag=TAG).info(f"Multilingual music matcher initialized with languages: {MULTILINGUAL_MATCHER.language_folders}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual matcher: {e}")
MULTILINGUAL_MATCHER = None
async def handle_multilingual_music_command(conn, user_request: str, song_type: str, language_preference: str = None):
"""Enhanced music command handler with multilingual AI matching"""
global MULTILINGUAL_MATCHER, MUSIC_CACHE
conn.logger.bind(tag=TAG).debug(f"Processing multilingual music request: '{user_request}'")
# Check if music directory exists
if not os.path.exists(MUSIC_CACHE["music_dir"]):
conn.logger.bind(tag=TAG).error(f"Music directory does not exist: {MUSIC_CACHE['music_dir']}")
await send_stt_message(conn, "Sorry, I couldn't find the music collection.")
return
# Refresh cache if needed
if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]:
MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(
MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"]
)
MUSIC_CACHE["scan_time"] = time.time()
selected_music = None
match_info = None
# Detect language from request if not provided
if not language_preference and MULTILINGUAL_MATCHER:
language_preference = MULTILINGUAL_MATCHER.detect_language_from_request(user_request)
# Check if this is a language-only request
is_language_only = MULTILINGUAL_MATCHER and MULTILINGUAL_MATCHER.is_language_only_request(user_request)
# Try multilingual AI matching for specific songs (ignore LLM language hint for better accuracy)
if MULTILINGUAL_MATCHER and song_type in ["specific", "random"] and not is_language_only:
try:
# First try without language hint to find best match across all languages
match_result = MULTILINGUAL_MATCHER.find_content_match(user_request, None)
if match_result:
selected_music, detected_language, metadata_entry = match_result
match_info = {
'method': 'ai_multilingual',
'language': detected_language,
'title': metadata_entry.get('romanized', 'Unknown'),
'original_title': list(MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[
list(MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry)
] if detected_language in MULTILINGUAL_MATCHER.metadata_cache else 'Unknown'
}
conn.logger.bind(tag=TAG).info(f"AI match found: {selected_music} ({detected_language}) - overriding LLM language hint: {language_preference}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Error in AI matching: {e}")
# Try language-specific selection for language requests or when language is detected
if not selected_music and language_preference and MULTILINGUAL_MATCHER:
try:
language_content = MULTILINGUAL_MATCHER.get_language_specific_content(language_preference)
if language_content:
selected_path, metadata_entry = random.choice(language_content)
selected_music = selected_path
match_info = {
'method': 'language_random',
'language': language_preference,
'title': metadata_entry.get('romanized', 'Unknown')
}
conn.logger.bind(tag=TAG).info(f"Language-specific random selection: {selected_music}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Error in language-specific selection: {e}")
# Fallback to legacy matching methods
if not selected_music:
# Try legacy language detection and matching
requested_language = _detect_language_request(user_request)
if requested_language:
language_files, language_file_names = _get_language_specific_files(
MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"], requested_language
)
if language_files:
selected_music = random.choice(language_files)
match_info = {
'method': 'legacy_language',
'language': requested_language,
'title': os.path.splitext(os.path.basename(selected_music))[0]
}
conn.logger.bind(tag=TAG).info(f"Legacy language match: {selected_music}")
# Try legacy song name matching
if not selected_music:
potential_song = _extract_song_name(user_request)
if potential_song:
best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"])
if best_match:
selected_music = best_match
match_info = {
'method': 'legacy_fuzzy',
'language': 'unknown',
'title': os.path.splitext(os.path.basename(selected_music))[0]
}
conn.logger.bind(tag=TAG).info(f"Legacy fuzzy match: {selected_music}")
# Final fallback to random selection
if not selected_music and MUSIC_CACHE["music_files"]:
selected_music = random.choice(MUSIC_CACHE["music_files"])
match_info = {
'method': 'random_fallback',
'language': 'unknown',
'title': os.path.splitext(os.path.basename(selected_music))[0]
}
conn.logger.bind(tag=TAG).info(f"Random fallback: {selected_music}")
# Play the selected music
if selected_music:
await play_multilingual_music(conn, selected_music, match_info, user_request)
else:
conn.logger.bind(tag=TAG).error("No music found to play")
await send_stt_message(conn, "Sorry, I couldn't find any music to play.")
async def play_multilingual_music(conn, selected_music: str, match_info: dict, original_request: str):
"""Play selected music with contextual introduction"""
global MUSIC_CACHE
try:
# Ensure path correctness
if not os.path.isabs(selected_music):
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
else:
music_path = selected_music
if not os.path.exists(music_path):
conn.logger.bind(tag=TAG).error(f"Selected music file does not exist: {music_path}")
return
# Generate contextual introduction based on match info
intro_text = generate_multilingual_intro(match_info, original_request)
await send_stt_message(conn, intro_text)
conn.dialogue.put(Message(role="assistant", content=intro_text))
# Queue TTS messages
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,
)
)
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.MIDDLE,
content_type=ContentType.FILE,
content_file=music_path,
)
)
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,
)
)
conn.logger.bind(tag=TAG).info(f"Playing multilingual music: {music_path}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to play multilingual music: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
def generate_multilingual_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', 'unknown')
title = match_info.get('title', 'Unknown Song')
original_title = match_info.get('original_title', title)
# Ensure language is a string and handle None case
if not language or not isinstance(language, str):
language = 'unknown'
try:
if method == 'ai_multilingual':
if language != 'unknown':
intros = [
f"Perfect! I found '{title}' in {language.title()} for you!",
f"Great choice! Here's '{title}' - a beautiful {language.title()} song!",
f"I found exactly what you wanted: '{title}' in {language.title()}!",
f"Playing '{title}' - this {language.title()} song should be perfect!"
]
else:
intros = [
f"I found '{title}' which matches your request perfectly!",
f"Here's '{title}' - I think you'll love it!",
f"Playing '{title}' based on your request!"
]
elif method == 'language_random':
intros = [
f"Here's a lovely {language.title()} song for you: '{title}'!",
f"Playing '{title}' - a beautiful {language.title()} selection!",
f"I picked '{title}' from our {language.title()} collection!"
]
elif method == 'legacy_language':
intros = [
f"Playing a {language.title()} song: '{title}'!",
f"Here's '{title}' in {language.title()} for you!",
f"Enjoy this {language.title()} music: '{title}'!"
]
elif method == 'legacy_fuzzy':
intros = [
f"I think you'll like '{title}'!",
f"Playing '{title}' - hope this is what you wanted!",
f"Here's '{title}' for you!"
]
else: # random_fallback
intros = [
f"Let me play '{title}' for you!",
f"Here's a nice song: '{title}'!",
f"Playing '{title}' - enjoy the music!"
]
return random.choice(intros)
except Exception as e:
# Fallback intro if there's any error
return f"Playing '{title}' for you!"
async def handle_music_command(conn, text):
initialize_music_handler(conn)
global MUSIC_CACHE
"""处理音乐播放指令"""
"""Handle music playback commands"""
clean_text = re.sub(r"[^\w\s]", "", text).strip()
conn.logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
conn.logger.bind(tag=TAG).debug(f"Check if it's a music command: {clean_text}")
# 尝试匹配具体歌名
# Check if user is requesting a specific language
requested_language = _detect_language_request(clean_text)
if os.path.exists(MUSIC_CACHE["music_dir"]):
if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]:
# 刷新音乐文件列表
# Refresh music file list
MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = (
get_music_files(MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"])
)
MUSIC_CACHE["scan_time"] = time.time()
# If language is specified, get files from that language folder
if requested_language:
conn.logger.bind(tag=TAG).info(f"Language request detected: {requested_language}")
language_files, language_file_names = _get_language_specific_files(
MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"], requested_language
)
if language_files:
# Play random song from the requested language folder
selected_music = random.choice(language_files)
conn.logger.bind(tag=TAG).info(f"Playing {requested_language} song: {selected_music}")
await play_local_music(conn, specific_file=selected_music)
return True
else:
conn.logger.bind(tag=TAG).warning(f"No {requested_language} songs found")
# Fall back to general music if no songs found in requested language
# Try to match specific song name
potential_song = _extract_song_name(clean_text)
if potential_song:
best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"])
if best_match:
conn.logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
conn.logger.bind(tag=TAG).info(f"Found best matching song: {best_match}")
await play_local_music(conn, specific_file=best_match)
return True
# 检查是否是通用播放音乐命令
# Check if it's a general play music command
await play_local_music(conn)
return True
def _get_random_play_prompt(song_name):
"""生成随机播放引导语"""
# 移除文件扩展名
clean_name = os.path.splitext(song_name)[0]
"""Generate random play prompt"""
# Remove file extension and extract just the filename (not the folder path)
clean_name = os.path.splitext(os.path.basename(song_name))[0]
prompts = [
f"Now playing for you, '{clean_name}'",
f"Please enjoy the song, '{clean_name}'",
@ -183,33 +583,33 @@ def _get_random_play_prompt(song_name):
f"Next, please enjoy, '{clean_name}'",
f"At this moment, presenting to you, '{clean_name}'",
]
# 直接使用random.choice,不设置seed
# Use random.choice directly, don't set seed
return random.choice(prompts)
async def play_local_music(conn, specific_file=None):
global MUSIC_CACHE
"""播放本地音乐文件"""
"""Play local music file"""
try:
if not os.path.exists(MUSIC_CACHE["music_dir"]):
conn.logger.bind(tag=TAG).error(
f"音乐目录不存在: " + MUSIC_CACHE["music_dir"]
f"Music directory does not exist: " + MUSIC_CACHE["music_dir"]
)
return
# 确保路径正确性
# Ensure path correctness
if specific_file:
selected_music = specific_file
music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file)
else:
if not MUSIC_CACHE["music_files"]:
conn.logger.bind(tag=TAG).error("未找到MP3音乐文件")
conn.logger.bind(tag=TAG).error("No MP3 music files found")
return
selected_music = random.choice(MUSIC_CACHE["music_files"])
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
if not os.path.exists(music_path):
conn.logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
conn.logger.bind(tag=TAG).error(f"Selected music file does not exist: {music_path}")
return
text = _get_random_play_prompt(selected_music)
await send_stt_message(conn, text)
@ -249,5 +649,5 @@ async def play_local_music(conn, specific_file=None):
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
conn.logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
conn.logger.bind(tag=TAG).error(f"Failed to play music: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")

View file

@ -0,0 +1,632 @@
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
TAG = __name__
STORY_CACHE = {}
STORY_MULTILINGUAL_MATCHER = None
# 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": "ALWAYS use 'random' for general requests like 'tell me a story'. Use 'specific' only for named stories like 'The Boy Who Cried Wolf'. Use 'category' for requests like 'bedtime story', 'fantasy 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"""
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] = []
# Get all story files in this category
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_story_handler(conn):
"""Initialize story handler with configuration"""
global STORY_CACHE
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
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}")
# 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"""
global STORY_CACHE
try:
# Ensure path correctness
if not os.path.isabs(selected_story):
story_path = os.path.join(STORY_CACHE["story_dir"], selected_story)
else:
story_path = selected_story
if not os.path.exists(story_path):
conn.logger.bind(tag=TAG).error(f"Selected story file does not exist: {story_path}")
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
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,
)
)
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.MIDDLE,
content_type=ContentType.FILE,
content_file=story_path,
)
)
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,
)
)
conn.logger.bind(tag=TAG).info(f"Playing multilingual story: {story_path}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to play multilingual story: {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"""
best_match = None
highest_ratio = 0
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]
ratio = difflib.SequenceMatcher(None, story_name.lower(), file_name.lower()).ratio()
if ratio > highest_ratio and ratio > 0.5: # Higher threshold for stories
highest_ratio = ratio
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"""
try:
story_path = os.path.join(STORY_CACHE["story_dir"], story_file)
if not os.path.exists(story_path):
conn.logger.bind(tag=TAG).error(f"Story file does not exist: {story_path}")
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
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,
)
)
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.MIDDLE,
content_type=ContentType.FILE,
content_file=story_path,
)
)
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,
)
)
conn.logger.bind(tag=TAG).info(f"Playing story: {story_path}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to play story: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")

View file

@ -0,0 +1,318 @@
"""
Multilingual content matching utility for music and stories
Based on the multilingual AI music app guide
"""
import os
import json
import difflib
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from fuzzywuzzy import fuzz
import re
class MultilingualMatcher:
"""
Handles multilingual content matching using metadata.json files
Supports fuzzy matching, romanization, and alternative names
"""
def __init__(self, content_dir: str, content_ext: List[str]):
self.content_dir = Path(content_dir)
self.content_ext = content_ext
self.metadata_cache = {}
self.language_folders = []
self._load_all_metadata()
def _load_all_metadata(self):
"""Load metadata.json from all language folders"""
if not self.content_dir.exists():
return
for folder in self.content_dir.iterdir():
if folder.is_dir():
metadata_file = folder / "metadata.json"
if metadata_file.exists():
try:
with open(metadata_file, 'r', encoding='utf-8') as f:
metadata = json.load(f)
self.metadata_cache[folder.name.lower()] = {
'metadata': metadata,
'folder_path': folder
}
self.language_folders.append(folder.name.lower())
except Exception as e:
print(f"Error loading metadata from {metadata_file}: {e}")
def detect_language_from_request(self, request: str) -> Optional[str]:
"""
Detect language from user request
Returns the language folder name if detected
"""
request_lower = request.lower()
# Language detection patterns (more comprehensive)
language_patterns = {
'english': [
'english', 'english song', 'english music', 'in english',
'any english', 'some english', 'play english'
],
'hindi': [
'hindi', 'hindi song', 'hindi music', 'in hindi', 'हिंदी',
'any hindi', 'some hindi', 'play hindi'
],
'telugu': [
'telugu', 'telugu song', 'telugu music', 'in telugu', 'తెలుగు',
'any telugu', 'some telugu', 'play telugu'
],
'kannada': [
'kannada', 'kannada song', 'kannada music', 'in kannada', 'ಕನ್ನಡ',
'any kannada', 'some kannada', 'play kannada'
],
'tamil': [
'tamil', 'tamil song', 'tamil music', 'in tamil', 'தமிழ்',
'any tamil', 'some tamil', 'play tamil'
],
'phonics': [
'phonics', 'phonics song', 'phonics music', 'alphabet', 'abc',
'play phonics', 'learn phonics', 'phonics sounds'
]
}
# Check for exact pattern matches first
for language, patterns in language_patterns.items():
for pattern in patterns:
if pattern in request_lower:
# Check if this language folder exists
if language in self.language_folders:
return language
# Check for word boundary matches (more precise)
for language, patterns in language_patterns.items():
for pattern in patterns:
if re.search(r'\b' + re.escape(pattern) + r'\b', request_lower):
if language in self.language_folders:
return language
return None
def extract_content_name_from_request(self, request: str) -> Optional[str]:
"""
Extract content name from user request
Removes common trigger words and language indicators
"""
# First, check if this is a language-only request
language_only_patterns = [
r'\b(play|sing|put on|listen to)\s+(any\s+)?(english|hindi|telugu|kannada|tamil|phonics)\s+(song|music)\b',
r'\b(english|hindi|telugu|kannada|tamil|phonics)\s+(song|music)\s+(please)?\b',
r'\bplay\s+(some\s+)?(english|hindi|telugu|kannada|tamil|phonics)\b'
]
request_lower = request.lower()
for pattern in language_only_patterns:
if re.search(pattern, request_lower):
return None # This is a language-only request, no specific content name
# Remove trigger words more carefully
trigger_patterns = [
r'\b(play|sing|put on|listen to|hear|tell)\s+', # Action words at start
r'\s+(for me|please|now)\b', # Politeness words at end
r'\b(a|the|some)\s+(song|story|music)\b', # Articles with content type
r'\s+(song|story|music)\b', # Content type words
r'\bin\s+(english|hindi|telugu|kannada|tamil)\b' # Language indicators
]
cleaned = request.lower()
for pattern in trigger_patterns:
cleaned = re.sub(pattern, ' ', cleaned)
# Remove extra spaces and punctuation
cleaned = re.sub(r'[^\w\s]', '', cleaned).strip()
cleaned = ' '.join(cleaned.split()) # Remove multiple spaces
# Don't return very short or empty strings
if len(cleaned) < 3:
return None
return cleaned if cleaned else None
def is_language_only_request(self, request: str) -> bool:
"""
Check if this is a language-only request (no specific content name)
"""
request_lower = request.lower()
# Patterns that indicate language-only requests
language_only_patterns = [
r'\b(play|sing|put on)\s+(any\s+)?(english|hindi|telugu|kannada|tamil|phonics)\s+(song|music)\b',
r'\b(english|hindi|telugu|kannada|tamil|phonics)\s+(song|music)\b',
r'\bplay\s+(some\s+)?(english|hindi|telugu|kannada|tamil|phonics)\b',
r'\b(any|some)\s+(english|hindi|telugu|kannada|tamil|phonics)\b'
]
for pattern in language_only_patterns:
if re.search(pattern, request_lower):
return True
return False
def find_content_match(self, request: str, language_hint: Optional[str] = None) -> Optional[Tuple[str, str, Dict]]:
"""
Find the best matching content based on request
Returns: (relative_file_path, language, metadata_entry) or None
Args:
request: User's request text
language_hint: Optional language hint from request analysis
"""
# Check if this is a language-only request
if self.is_language_only_request(request):
return None # Let the caller handle language-specific random selection
# Extract content name from request
content_name = self.extract_content_name_from_request(request)
if not content_name:
return None
# Detect language from request if not provided
if not language_hint:
language_hint = self.detect_language_from_request(request)
best_match = None
best_score = 0
# Search order: specific language first, then all languages
search_languages = []
if language_hint and language_hint in self.language_folders:
search_languages.append(language_hint)
# Add all other languages
for lang in self.language_folders:
if lang not in search_languages:
search_languages.append(lang)
for language in search_languages:
if language not in self.metadata_cache:
continue
metadata = self.metadata_cache[language]['metadata']
folder_path = self.metadata_cache[language]['folder_path']
for original_title, entry in metadata.items():
# Calculate match scores
scores = []
# Score against original title
scores.append(fuzz.ratio(content_name, original_title.lower()))
# Score against romanized version
if 'romanized' in entry:
scores.append(fuzz.ratio(content_name, entry['romanized'].lower()))
# Score against alternatives
if 'alternatives' in entry and entry['alternatives']:
for alt in entry['alternatives']:
scores.append(fuzz.ratio(content_name, alt.lower()))
# Score against filename (without extension)
if 'filename' in entry:
filename_base = os.path.splitext(entry['filename'])[0].lower()
scores.append(fuzz.ratio(content_name, filename_base))
# Take the best score for this entry
max_score = max(scores) if scores else 0
# Boost score if language matches hint
if language_hint and language == language_hint:
max_score += 10
# Update best match if this is better
if max_score > best_score and max_score > 60: # Minimum threshold
best_score = max_score
file_path = folder_path / entry['filename']
relative_path = str(file_path.relative_to(self.content_dir))
best_match = (relative_path, language, entry)
return best_match
def get_language_specific_content(self, language: str) -> List[Tuple[str, Dict]]:
"""
Get all content from a specific language folder
Returns: List of (relative_file_path, metadata_entry)
"""
if language.lower() not in self.metadata_cache:
return []
language_data = self.metadata_cache[language.lower()]
metadata = language_data['metadata']
folder_path = language_data['folder_path']
content_list = []
for original_title, entry in metadata.items():
if 'filename' in entry:
file_path = folder_path / entry['filename']
relative_path = str(file_path.relative_to(self.content_dir))
content_list.append((relative_path, entry))
return content_list
def get_all_content_with_metadata(self) -> List[Tuple[str, str, Dict]]:
"""
Get all content from all languages with metadata
Returns: List of (relative_file_path, language, metadata_entry)
"""
all_content = []
for language in self.language_folders:
content_list = self.get_language_specific_content(language)
for relative_path, entry in content_list:
all_content.append((relative_path, language, entry))
return all_content
def fallback_to_filesystem(self) -> List[str]:
"""
Fallback method to get content files directly from filesystem
Used when metadata.json is not available
"""
content_files = []
if not self.content_dir.exists():
return content_files
for file_path in self.content_dir.rglob("*"):
if file_path.is_file() and file_path.suffix.lower() in self.content_ext:
relative_path = str(file_path.relative_to(self.content_dir))
content_files.append(relative_path)
return content_files
def get_content_info(self, relative_path: str) -> Dict:
"""
Get metadata information for a specific content file
"""
file_path = Path(relative_path)
# Try to find in metadata
for language in self.language_folders:
if language not in self.metadata_cache:
continue
metadata = self.metadata_cache[language]['metadata']
for original_title, entry in metadata.items():
if entry.get('filename') == file_path.name:
return {
'title': original_title,
'language': language,
'romanized': entry.get('romanized', original_title),
'alternatives': entry.get('alternatives', []),
**entry
}
# Fallback to filename-based info
return {
'title': file_path.stem,
'language': file_path.parent.name if file_path.parent.name != '.' else 'unknown',
'romanized': file_path.stem,
'alternatives': []
}

View file

@ -36,4 +36,6 @@ psutil==7.0.0
portalocker==2.10.1
Jinja2==3.1.6
ten-vad==0.2.0
deepgram-sdk==4.8.1
deepgram-sdk==4.8.1
fuzzywuzzy
Levenshtein

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.