mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Semantic search implemented
This commit is contained in:
parent
0e791e9155
commit
54f65d844e
4 changed files with 857 additions and 12 deletions
428
main/xiaozhi-server/index_music.py
Normal file
428
main/xiaozhi-server/index_music.py
Normal file
|
|
@ -0,0 +1,428 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Music Metadata Indexing Script for Semantic Search
|
||||
Run this script to index all music metadata into Qdrant vector database
|
||||
Usage: python index_music.py [--clear] [--verify]
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import argparse
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
from dataclasses import dataclass, asdict
|
||||
|
||||
# Add project root to path
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from qdrant_client import QdrantClient, models
|
||||
from sentence_transformers import SentenceTransformer
|
||||
import hashlib
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@dataclass
|
||||
class IndexingStats:
|
||||
"""Statistics for indexing operation"""
|
||||
total_languages: int = 0
|
||||
total_songs: int = 0
|
||||
songs_indexed: int = 0
|
||||
songs_failed: int = 0
|
||||
time_taken: float = 0
|
||||
languages_processed: List[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
if self.languages_processed is None:
|
||||
self.languages_processed = []
|
||||
|
||||
class MusicIndexer:
|
||||
"""Handles indexing of music metadata into Qdrant"""
|
||||
|
||||
def __init__(self, config_path: str = "data/.config.yaml"):
|
||||
"""Initialize the indexer with configuration"""
|
||||
self.config = self._load_config(config_path)
|
||||
self.stats = IndexingStats()
|
||||
|
||||
# Get semantic search config
|
||||
self.semantic_config = self.config.get('semantic_search', {})
|
||||
if not self.semantic_config.get('enabled', False):
|
||||
logger.warning("Semantic search is disabled in configuration!")
|
||||
|
||||
# Qdrant settings
|
||||
self.qdrant_url = self.semantic_config.get('qdrant_url')
|
||||
self.qdrant_api_key = self.semantic_config.get('qdrant_api_key')
|
||||
self.collection_name = self.semantic_config.get('collection_name', 'xiaozhi_music')
|
||||
|
||||
# Embedding settings
|
||||
self.model_name = self.semantic_config.get('embedding_model', 'all-MiniLM-L6-v2')
|
||||
|
||||
# Music directory settings
|
||||
self.music_dir = Path(self.config.get('plugins', {}).get('play_music', {}).get('music_dir', './music'))
|
||||
self.music_ext = ('.mp3', '.wav', '.p3')
|
||||
|
||||
# Initialize clients
|
||||
self.qdrant_client = None
|
||||
self.embedding_model = None
|
||||
|
||||
def _load_config(self, config_path: str) -> dict:
|
||||
"""Load configuration from YAML file"""
|
||||
yaml = YAML()
|
||||
yaml.preserve_quotes = True
|
||||
|
||||
try:
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = yaml.load(f)
|
||||
logger.info(f"Loaded configuration from {config_path}")
|
||||
return config
|
||||
except FileNotFoundError:
|
||||
logger.error(f"Configuration file not found: {config_path}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load configuration: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
def initialize(self) -> bool:
|
||||
"""Initialize Qdrant client and embedding model"""
|
||||
try:
|
||||
# Initialize Qdrant client
|
||||
logger.info(f"Connecting to Qdrant at {self.qdrant_url}...")
|
||||
self.qdrant_client = QdrantClient(
|
||||
url=self.qdrant_url,
|
||||
api_key=self.qdrant_api_key,
|
||||
timeout=60 # Increased timeout
|
||||
)
|
||||
|
||||
# Test connection
|
||||
collections = self.qdrant_client.get_collections()
|
||||
logger.info(f"Connected to Qdrant. Found {len(collections.collections)} collections")
|
||||
|
||||
# Initialize embedding model
|
||||
logger.info(f"Loading embedding model: {self.model_name}...")
|
||||
self.embedding_model = SentenceTransformer(self.model_name)
|
||||
self.embedding_size = self.embedding_model.get_sentence_embedding_dimension()
|
||||
logger.info(f"Embedding model loaded. Dimension: {self.embedding_size}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize: {e}")
|
||||
return False
|
||||
|
||||
def create_collection(self, recreate: bool = False) -> bool:
|
||||
"""Create or recreate the Qdrant collection"""
|
||||
try:
|
||||
# Check if collection exists
|
||||
collections = self.qdrant_client.get_collections()
|
||||
exists = any(c.name == self.collection_name for c in collections.collections)
|
||||
|
||||
if exists:
|
||||
if recreate:
|
||||
logger.info(f"Deleting existing collection '{self.collection_name}'...")
|
||||
self.qdrant_client.delete_collection(self.collection_name)
|
||||
logger.info("Collection deleted")
|
||||
else:
|
||||
logger.info(f"Collection '{self.collection_name}' already exists")
|
||||
return True
|
||||
|
||||
# Create new collection
|
||||
logger.info(f"Creating collection '{self.collection_name}'...")
|
||||
self.qdrant_client.create_collection(
|
||||
collection_name=self.collection_name,
|
||||
vectors_config=models.VectorParams(
|
||||
size=self.embedding_size,
|
||||
distance=models.Distance.COSINE
|
||||
),
|
||||
)
|
||||
logger.info("Collection created successfully")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create collection: {e}")
|
||||
return False
|
||||
|
||||
def load_music_metadata(self) -> Dict[str, Dict]:
|
||||
"""Load all music metadata from the music directory"""
|
||||
metadata_cache = {}
|
||||
|
||||
if not self.music_dir.exists():
|
||||
logger.error(f"Music directory does not exist: {self.music_dir}")
|
||||
return metadata_cache
|
||||
|
||||
logger.info(f"Scanning music directory: {self.music_dir}")
|
||||
|
||||
for language_folder in self.music_dir.iterdir():
|
||||
if not language_folder.is_dir():
|
||||
continue
|
||||
|
||||
language_name = language_folder.name
|
||||
metadata_file = language_folder / "metadata.json"
|
||||
|
||||
if metadata_file.exists():
|
||||
try:
|
||||
with open(metadata_file, 'r', encoding='utf-8') as f:
|
||||
metadata = json.load(f)
|
||||
|
||||
metadata_cache[language_name] = {
|
||||
'metadata': metadata,
|
||||
'folder_path': str(language_folder)
|
||||
}
|
||||
|
||||
self.stats.total_songs += len(metadata)
|
||||
self.stats.languages_processed.append(language_name)
|
||||
logger.info(f"Loaded {len(metadata)} songs from {language_name}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load metadata from {metadata_file}: {e}")
|
||||
else:
|
||||
# Scan for actual music files if no metadata.json
|
||||
music_files = []
|
||||
for ext in self.music_ext:
|
||||
music_files.extend(language_folder.glob(f"*{ext}"))
|
||||
|
||||
if music_files:
|
||||
logger.warning(f"No metadata.json in {language_name}, found {len(music_files)} music files")
|
||||
# Create basic metadata from filenames
|
||||
metadata = {}
|
||||
for file in music_files:
|
||||
song_name = file.stem
|
||||
metadata[song_name] = {
|
||||
'filename': file.name,
|
||||
'romanized': song_name
|
||||
}
|
||||
|
||||
metadata_cache[language_name] = {
|
||||
'metadata': metadata,
|
||||
'folder_path': str(language_folder)
|
||||
}
|
||||
|
||||
self.stats.total_songs += len(metadata)
|
||||
self.stats.languages_processed.append(language_name)
|
||||
|
||||
self.stats.total_languages = len(metadata_cache)
|
||||
logger.info(f"Total: {self.stats.total_languages} languages, {self.stats.total_songs} songs")
|
||||
return metadata_cache
|
||||
|
||||
def index_metadata(self, metadata_cache: Dict[str, Dict]) -> bool:
|
||||
"""Index all metadata into Qdrant"""
|
||||
if not metadata_cache:
|
||||
logger.warning("No metadata to index")
|
||||
return False
|
||||
|
||||
try:
|
||||
points = []
|
||||
point_id = 0
|
||||
|
||||
logger.info("Generating embeddings and preparing data...")
|
||||
|
||||
for language, lang_data in metadata_cache.items():
|
||||
metadata = lang_data.get('metadata', {})
|
||||
|
||||
for song_title, song_info in metadata.items():
|
||||
try:
|
||||
# Prepare searchable text
|
||||
searchable_texts = [
|
||||
song_title,
|
||||
song_info.get('romanized', ''),
|
||||
]
|
||||
|
||||
# Add alternatives
|
||||
alternatives = song_info.get('alternatives', [])
|
||||
if isinstance(alternatives, list):
|
||||
searchable_texts.extend(alternatives)
|
||||
|
||||
# Add keywords
|
||||
keywords = song_info.get('keywords', [])
|
||||
if isinstance(keywords, list):
|
||||
searchable_texts.extend(keywords)
|
||||
|
||||
# Add language context
|
||||
searchable_texts.append(language)
|
||||
|
||||
# Combine all text
|
||||
combined_text = " ".join(filter(None, searchable_texts)).strip()
|
||||
|
||||
if not combined_text:
|
||||
logger.warning(f"Skipping {song_title} - no searchable text")
|
||||
continue
|
||||
|
||||
# Generate embedding
|
||||
embedding = self.embedding_model.encode(combined_text).tolist()
|
||||
|
||||
# Prepare payload
|
||||
payload = {
|
||||
'title': song_title,
|
||||
'language': language,
|
||||
'romanized': song_info.get('romanized', song_title),
|
||||
'alternatives': alternatives,
|
||||
'keywords': keywords,
|
||||
'filename': song_info.get('filename', f"{song_title}.mp3"),
|
||||
'file_path': f"{language}/{song_info.get('filename', f'{song_title}.mp3')}",
|
||||
'searchable_text': combined_text,
|
||||
'metadata': song_info
|
||||
}
|
||||
|
||||
points.append(
|
||||
models.PointStruct(
|
||||
id=point_id,
|
||||
vector=embedding,
|
||||
payload=payload
|
||||
)
|
||||
)
|
||||
point_id += 1
|
||||
self.stats.songs_indexed += 1
|
||||
|
||||
if point_id % 50 == 0:
|
||||
logger.info(f"Processed {point_id} songs...")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to process {song_title}: {e}")
|
||||
self.stats.songs_failed += 1
|
||||
|
||||
# Upload to Qdrant in batches
|
||||
if points:
|
||||
logger.info(f"Uploading {len(points)} songs to Qdrant...")
|
||||
batch_size = 100
|
||||
|
||||
for i in range(0, len(points), batch_size):
|
||||
batch = points[i:i+batch_size]
|
||||
self.qdrant_client.upsert(
|
||||
collection_name=self.collection_name,
|
||||
points=batch,
|
||||
wait=True # Wait for indexing to complete
|
||||
)
|
||||
logger.info(f"Uploaded batch {i//batch_size + 1}/{(len(points)-1)//batch_size + 1}")
|
||||
|
||||
logger.info(f"Successfully indexed {len(points)} songs")
|
||||
return True
|
||||
else:
|
||||
logger.warning("No valid songs to index")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to index metadata: {e}")
|
||||
return False
|
||||
|
||||
def verify_indexing(self) -> bool:
|
||||
"""Verify that indexing was successful"""
|
||||
try:
|
||||
collection_info = self.qdrant_client.get_collection(self.collection_name)
|
||||
point_count = collection_info.points_count
|
||||
|
||||
logger.info(f"Collection '{self.collection_name}' contains {point_count} songs")
|
||||
|
||||
# Try a sample search
|
||||
test_query = "twinkle twinkle little star"
|
||||
logger.info(f"Testing search with query: '{test_query}'")
|
||||
|
||||
query_embedding = self.embedding_model.encode(test_query).tolist()
|
||||
results = self.qdrant_client.search(
|
||||
collection_name=self.collection_name,
|
||||
query_vector=query_embedding,
|
||||
limit=3
|
||||
)
|
||||
|
||||
if results:
|
||||
logger.info("Sample search results:")
|
||||
for i, hit in enumerate(results, 1):
|
||||
logger.info(f" {i}. {hit.payload['title']} ({hit.payload['language']}) - Score: {hit.score:.3f}")
|
||||
else:
|
||||
logger.warning("No results found for test query")
|
||||
|
||||
return point_count > 0
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to verify indexing: {e}")
|
||||
return False
|
||||
|
||||
def run(self, clear: bool = False, verify_only: bool = False):
|
||||
"""Run the indexing process"""
|
||||
start_time = time.time()
|
||||
|
||||
# Initialize
|
||||
if not self.initialize():
|
||||
logger.error("Initialization failed")
|
||||
return False
|
||||
|
||||
if verify_only:
|
||||
# Just verify existing index
|
||||
success = self.verify_indexing()
|
||||
if success:
|
||||
logger.info("✅ Verification successful")
|
||||
else:
|
||||
logger.error("❌ Verification failed")
|
||||
return success
|
||||
|
||||
# Create/recreate collection
|
||||
if not self.create_collection(recreate=clear):
|
||||
logger.error("Failed to create collection")
|
||||
return False
|
||||
|
||||
# Load metadata
|
||||
metadata_cache = self.load_music_metadata()
|
||||
if not metadata_cache:
|
||||
logger.error("No metadata found")
|
||||
return False
|
||||
|
||||
# Index metadata
|
||||
success = self.index_metadata(metadata_cache)
|
||||
|
||||
# Calculate stats
|
||||
self.stats.time_taken = time.time() - start_time
|
||||
|
||||
# Print summary
|
||||
logger.info("=" * 60)
|
||||
logger.info("INDEXING SUMMARY")
|
||||
logger.info("=" * 60)
|
||||
logger.info(f"Languages processed: {self.stats.total_languages}")
|
||||
logger.info(f"Total songs found: {self.stats.total_songs}")
|
||||
logger.info(f"Songs indexed: {self.stats.songs_indexed}")
|
||||
logger.info(f"Songs failed: {self.stats.songs_failed}")
|
||||
logger.info(f"Time taken: {self.stats.time_taken:.2f} seconds")
|
||||
logger.info(f"Languages: {', '.join(self.stats.languages_processed)}")
|
||||
logger.info("=" * 60)
|
||||
|
||||
if success:
|
||||
logger.info("✅ Indexing completed successfully!")
|
||||
# Verify the indexing
|
||||
self.verify_indexing()
|
||||
else:
|
||||
logger.error("❌ Indexing failed")
|
||||
|
||||
return success
|
||||
|
||||
def main():
|
||||
"""Main entry point"""
|
||||
parser = argparse.ArgumentParser(description='Index music metadata for semantic search')
|
||||
parser.add_argument('--clear', action='store_true', help='Clear existing index before indexing')
|
||||
parser.add_argument('--verify', action='store_true', help='Only verify existing index')
|
||||
parser.add_argument('--config', default='data/.config.yaml', help='Path to configuration file')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Print header
|
||||
print("=" * 60)
|
||||
print("MUSIC METADATA INDEXER FOR XIAOZHI")
|
||||
print("=" * 60)
|
||||
print(f"Config file: {args.config}")
|
||||
print(f"Clear existing: {args.clear}")
|
||||
print(f"Verify only: {args.verify}")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# Run indexer
|
||||
indexer = MusicIndexer(config_path=args.config)
|
||||
success = indexer.run(clear=args.clear, verify_only=args.verify)
|
||||
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -10,6 +10,7 @@ from plugins_func.register import register_function, ToolType, ActionResponse, A
|
|||
from core.utils.dialogue import Message
|
||||
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
|
||||
from plugins_func.utils.multilingual_matcher import MultilingualMatcher
|
||||
from plugins_func.utils.semantic_music_search import SemanticMusicSearch
|
||||
|
||||
# S3 Streaming imports
|
||||
import boto3
|
||||
|
|
@ -23,6 +24,7 @@ TAG = __name__
|
|||
|
||||
MUSIC_CACHE = {}
|
||||
MULTILINGUAL_MATCHER = None
|
||||
SEMANTIC_SEARCH = None
|
||||
|
||||
# S3 Configuration
|
||||
S3_CLIENT = None
|
||||
|
|
@ -423,8 +425,8 @@ def initialize_music_handler(conn):
|
|||
return MUSIC_CACHE
|
||||
|
||||
def initialize_multilingual_music_system(conn):
|
||||
"""Initialize the multilingual music matching system"""
|
||||
global MULTILINGUAL_MATCHER, MUSIC_CACHE
|
||||
"""Initialize the multilingual music matching system with semantic search"""
|
||||
global MULTILINGUAL_MATCHER, SEMANTIC_SEARCH, MUSIC_CACHE
|
||||
|
||||
# Initialize basic music cache first
|
||||
initialize_music_handler(conn)
|
||||
|
|
@ -440,10 +442,35 @@ def initialize_multilingual_music_system(conn):
|
|||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual matcher: {e}")
|
||||
MULTILINGUAL_MATCHER = None
|
||||
|
||||
# Initialize semantic search if not already done
|
||||
if SEMANTIC_SEARCH is None:
|
||||
try:
|
||||
semantic_config = conn.config.get('semantic_search', {})
|
||||
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")
|
||||
|
||||
# Check if collection is already indexed
|
||||
if SEMANTIC_SEARCH.is_collection_indexed():
|
||||
stats = SEMANTIC_SEARCH.get_collection_stats()
|
||||
conn.logger.bind(tag=TAG).info(f"Using existing music index with {stats.get('points_count', 0)} songs")
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).warning("Music collection is empty. Please run 'python index_music.py' to index your music")
|
||||
# Don't try to index on-the-fly anymore to avoid timeouts
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).warning("Failed to initialize semantic search")
|
||||
SEMANTIC_SEARCH = None
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).info("Semantic search is disabled in configuration")
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Failed to initialize semantic search: {e}")
|
||||
SEMANTIC_SEARCH = None
|
||||
|
||||
async def handle_multilingual_music_command(conn, user_request: str, song_type: str, requested_language: str = None):
|
||||
"""Enhanced music command handler with multilingual AI matching"""
|
||||
global MULTILINGUAL_MATCHER, MUSIC_CACHE
|
||||
"""Enhanced music command handler with semantic search and multilingual matching"""
|
||||
global MULTILINGUAL_MATCHER, SEMANTIC_SEARCH, MUSIC_CACHE
|
||||
|
||||
conn.logger.bind(tag=TAG).debug(f"Processing multilingual music request: '{user_request}'")
|
||||
|
||||
|
|
@ -470,24 +497,41 @@ async def handle_multilingual_music_command(conn, user_request: str, song_type:
|
|||
# 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 semantic search for specific songs first (most accurate)
|
||||
if SEMANTIC_SEARCH and song_type in ["specific", "random"] and not is_language_only:
|
||||
try:
|
||||
# First try without language hint to find best match across all languages
|
||||
semantic_result = SEMANTIC_SEARCH.find_best_match(user_request)
|
||||
if semantic_result and semantic_result.score > 0.5: # Confidence threshold
|
||||
selected_music = semantic_result.file_path
|
||||
match_info = {
|
||||
'method': 'semantic_search',
|
||||
'language': semantic_result.language,
|
||||
'title': semantic_result.romanized,
|
||||
'original_title': semantic_result.title,
|
||||
'score': semantic_result.score
|
||||
}
|
||||
conn.logger.bind(tag=TAG).info(f"Semantic search match: {selected_music} ({semantic_result.language}) - score: {semantic_result.score:.3f}")
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Error in semantic search: {e}")
|
||||
|
||||
# Fallback to multilingual AI matching if semantic search didn't find a good match
|
||||
if not selected_music and MULTILINGUAL_MATCHER and song_type in ["specific", "random"] and not is_language_only:
|
||||
try:
|
||||
# Try multilingual matcher as fallback
|
||||
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',
|
||||
'method': 'ai_multilingual_fallback',
|
||||
'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: {requested_language}")
|
||||
conn.logger.bind(tag=TAG).info(f"Fallback AI match found: {selected_music} ({detected_language})")
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Error in AI matching: {e}")
|
||||
conn.logger.bind(tag=TAG).error(f"Error in AI matching fallback: {e}")
|
||||
|
||||
# Try language-specific selection for language requests or when language is detected
|
||||
if not selected_music and requested_language and MULTILINGUAL_MATCHER:
|
||||
|
|
@ -667,7 +711,36 @@ def generate_multilingual_intro(match_info: dict, original_request: str) -> str:
|
|||
language = 'unknown'
|
||||
|
||||
try:
|
||||
if method == 'ai_multilingual':
|
||||
if method == 'semantic_search':
|
||||
score = match_info.get('score', 0)
|
||||
if score > 0.8:
|
||||
if language != 'unknown':
|
||||
intros = [
|
||||
f"Perfect match! I found '{title}' in {language.title()} for you!",
|
||||
f"Excellent! Here's '{title}' - exactly what you asked for in {language.title()}!",
|
||||
f"Found it! Playing '{title}' - this {language.title()} song matches perfectly!",
|
||||
f"Great choice! '{title}' in {language.title()} is exactly what you wanted!"
|
||||
]
|
||||
else:
|
||||
intros = [
|
||||
f"Perfect! I found exactly what you wanted: '{title}'!",
|
||||
f"Excellent match! Here's '{title}' for you!",
|
||||
f"Found it! Playing '{title}' - this is exactly what you asked for!"
|
||||
]
|
||||
else:
|
||||
if language != 'unknown':
|
||||
intros = [
|
||||
f"I think you'll like '{title}' in {language.title()}!",
|
||||
f"Here's '{title}' - a great {language.title()} song that matches your request!",
|
||||
f"Playing '{title}' in {language.title()} - hope this is what you wanted!"
|
||||
]
|
||||
else:
|
||||
intros = [
|
||||
f"I found '{title}' which should match your request!",
|
||||
f"Here's '{title}' - I think this is what you're looking for!",
|
||||
f"Playing '{title}' based on your request!"
|
||||
]
|
||||
elif method == 'ai_multilingual' or method == 'ai_multilingual_fallback':
|
||||
if language != 'unknown':
|
||||
intros = [
|
||||
f"Perfect! I found '{title}' in {language.title()} for you!",
|
||||
|
|
|
|||
340
main/xiaozhi-server/plugins_func/utils/semantic_music_search.py
Normal file
340
main/xiaozhi-server/plugins_func/utils/semantic_music_search.py
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
"""
|
||||
Semantic Music Search Module using Qdrant Vector Database
|
||||
Integrates with the existing multilingual music matching system
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
from dataclasses import dataclass
|
||||
|
||||
try:
|
||||
from qdrant_client import QdrantClient, models
|
||||
from qdrant_client.http.exceptions import UnexpectedResponse
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from spellchecker import SpellChecker
|
||||
DEPENDENCIES_AVAILABLE = True
|
||||
except ImportError as e:
|
||||
DEPENDENCIES_AVAILABLE = False
|
||||
import_error = str(e)
|
||||
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
@dataclass
|
||||
class MusicSearchResult:
|
||||
"""Data class for music search results"""
|
||||
file_path: str
|
||||
title: str
|
||||
language: str
|
||||
romanized: str
|
||||
alternatives: List[str]
|
||||
score: float
|
||||
metadata: Dict
|
||||
|
||||
class SemanticMusicSearch:
|
||||
"""
|
||||
Semantic music search engine using Qdrant vector database
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict = None):
|
||||
"""Initialize the semantic music search system"""
|
||||
self.config = config or {}
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
# Check if dependencies are available
|
||||
if not DEPENDENCIES_AVAILABLE:
|
||||
self.logger.error(f"Semantic search dependencies not available: {import_error}")
|
||||
self.is_available = False
|
||||
return
|
||||
|
||||
self.is_available = True
|
||||
|
||||
# Qdrant configuration
|
||||
self.qdrant_url = self.config.get("qdrant_url", "https://localhost:6333")
|
||||
self.qdrant_api_key = self.config.get("qdrant_api_key", None)
|
||||
self.collection_name = self.config.get("collection_name", "xiaozhi_music")
|
||||
|
||||
# Embedding model configuration
|
||||
self.model_name = self.config.get("embedding_model", "all-MiniLM-L6-v2")
|
||||
|
||||
# Search parameters
|
||||
self.search_limit = self.config.get("search_limit", 5)
|
||||
self.min_score_threshold = self.config.get("min_score_threshold", 0.5)
|
||||
|
||||
# Initialize components
|
||||
self.qdrant_client = None
|
||||
self.embedding_model = None
|
||||
self.spell_checker = None
|
||||
self.embedding_size = None
|
||||
self.is_initialized = False
|
||||
|
||||
# Cache for embeddings to avoid recomputation
|
||||
self.embedding_cache = {}
|
||||
|
||||
def initialize(self) -> bool:
|
||||
"""Initialize Qdrant client and embedding model"""
|
||||
if not self.is_available:
|
||||
self.logger.error("Semantic search dependencies not available")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Initialize spell checker
|
||||
self.spell_checker = SpellChecker()
|
||||
|
||||
# Initialize Qdrant client
|
||||
if self.qdrant_api_key:
|
||||
self.qdrant_client = QdrantClient(
|
||||
url=self.qdrant_url,
|
||||
api_key=self.qdrant_api_key
|
||||
)
|
||||
else:
|
||||
self.qdrant_client = QdrantClient(url=self.qdrant_url)
|
||||
|
||||
# Test connection
|
||||
self.qdrant_client.get_collections()
|
||||
|
||||
# Initialize embedding model
|
||||
self.logger.info(f"Loading embedding model: {self.model_name}")
|
||||
self.embedding_model = SentenceTransformer(self.model_name)
|
||||
self.embedding_size = self.embedding_model.get_sentence_embedding_dimension()
|
||||
|
||||
# Create collection if it doesn't exist
|
||||
self._create_collection_if_not_exists()
|
||||
|
||||
self.is_initialized = True
|
||||
self.logger.info(f"Semantic music search initialized with model: {self.model_name}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to initialize semantic search: {e}")
|
||||
self.is_initialized = False
|
||||
return False
|
||||
|
||||
def _create_collection_if_not_exists(self):
|
||||
"""Create Qdrant collection if it doesn't exist"""
|
||||
try:
|
||||
self.qdrant_client.get_collection(collection_name=self.collection_name)
|
||||
self.logger.info(f"Collection '{self.collection_name}' already exists")
|
||||
except Exception:
|
||||
self.logger.info(f"Creating collection '{self.collection_name}'")
|
||||
self.qdrant_client.create_collection(
|
||||
collection_name=self.collection_name,
|
||||
vectors_config=models.VectorParams(
|
||||
size=self.embedding_size,
|
||||
distance=models.Distance.COSINE
|
||||
),
|
||||
)
|
||||
|
||||
def correct_spelling(self, query: str) -> str:
|
||||
"""Correct spelling in the user query"""
|
||||
if not self.spell_checker:
|
||||
return query
|
||||
|
||||
words = query.split()
|
||||
corrected_words = []
|
||||
|
||||
for word in words:
|
||||
# Skip very short words and numbers
|
||||
if len(word) <= 2 or word.isdigit():
|
||||
corrected_words.append(word)
|
||||
continue
|
||||
|
||||
corrected_word = self.spell_checker.correction(word)
|
||||
if corrected_word is None:
|
||||
corrected_word = word
|
||||
corrected_words.append(corrected_word)
|
||||
|
||||
corrected_query = " ".join(corrected_words)
|
||||
if corrected_query != query:
|
||||
self.logger.debug(f"Spelling correction: '{query}' -> '{corrected_query}'")
|
||||
|
||||
return corrected_query
|
||||
|
||||
def _get_embedding(self, text: str) -> List[float]:
|
||||
"""Get embedding for text with caching"""
|
||||
if not text or not self.embedding_model:
|
||||
return []
|
||||
|
||||
# Create a hash of the text for caching
|
||||
text_hash = hashlib.md5(text.encode()).hexdigest()
|
||||
|
||||
if text_hash in self.embedding_cache:
|
||||
return self.embedding_cache[text_hash]
|
||||
|
||||
embedding = self.embedding_model.encode(text).tolist()
|
||||
self.embedding_cache[text_hash] = embedding
|
||||
return embedding
|
||||
|
||||
def index_music_metadata(self, music_metadata: Dict[str, Dict]) -> bool:
|
||||
"""
|
||||
Index music metadata into Qdrant
|
||||
music_metadata format: {language: {metadata: {song_title: song_info}}}
|
||||
"""
|
||||
if not self.is_initialized:
|
||||
self.logger.warning("Semantic search not initialized, skipping indexing")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Clear existing collection
|
||||
self.qdrant_client.delete_collection(self.collection_name)
|
||||
self._create_collection_if_not_exists()
|
||||
|
||||
points = []
|
||||
point_id = 0
|
||||
|
||||
for language, lang_data in music_metadata.items():
|
||||
metadata = lang_data.get('metadata', {})
|
||||
|
||||
for song_title, song_info in metadata.items():
|
||||
# Prepare searchable text for embedding
|
||||
searchable_texts = [
|
||||
song_title, # Original title
|
||||
song_info.get('romanized', ''), # Romanized version
|
||||
]
|
||||
|
||||
# Add alternative names
|
||||
alternatives = song_info.get('alternatives', [])
|
||||
if isinstance(alternatives, list):
|
||||
searchable_texts.extend(alternatives)
|
||||
|
||||
# Add keywords
|
||||
keywords = song_info.get('keywords', [])
|
||||
if isinstance(keywords, list):
|
||||
searchable_texts.extend(keywords)
|
||||
|
||||
# Add language for context
|
||||
searchable_texts.append(language)
|
||||
|
||||
# Combine all searchable text
|
||||
combined_text = " ".join(filter(None, searchable_texts)).strip()
|
||||
|
||||
if not combined_text:
|
||||
continue
|
||||
|
||||
# Generate embedding
|
||||
embedding = self._get_embedding(combined_text)
|
||||
if not embedding:
|
||||
continue
|
||||
|
||||
# Prepare payload
|
||||
payload = {
|
||||
'title': song_title,
|
||||
'language': language,
|
||||
'romanized': song_info.get('romanized', song_title),
|
||||
'alternatives': alternatives,
|
||||
'keywords': keywords,
|
||||
'filename': song_info.get('filename', f"{song_title}.mp3"),
|
||||
'file_path': f"{language}/{song_info.get('filename', f'{song_title}.mp3')}",
|
||||
'searchable_text': combined_text,
|
||||
'metadata': song_info
|
||||
}
|
||||
|
||||
points.append(
|
||||
models.PointStruct(
|
||||
id=point_id,
|
||||
vector=embedding,
|
||||
payload=payload
|
||||
)
|
||||
)
|
||||
point_id += 1
|
||||
|
||||
# Upsert points to Qdrant
|
||||
if points:
|
||||
self.qdrant_client.upsert(
|
||||
collection_name=self.collection_name,
|
||||
points=points
|
||||
)
|
||||
self.logger.info(f"Indexed {len(points)} music tracks into Qdrant")
|
||||
return True
|
||||
else:
|
||||
self.logger.warning("No music metadata to index")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to index music metadata: {e}")
|
||||
return False
|
||||
|
||||
def search(self, query: str, limit: Optional[int] = None) -> List[MusicSearchResult]:
|
||||
"""
|
||||
Perform semantic search for music
|
||||
"""
|
||||
if not self.is_initialized:
|
||||
return []
|
||||
|
||||
try:
|
||||
# Check if collection has data
|
||||
collection_info = self.qdrant_client.get_collection(self.collection_name)
|
||||
if collection_info.points_count == 0:
|
||||
self.logger.warning("Music collection is empty. Please index music metadata first.")
|
||||
return []
|
||||
|
||||
# Correct spelling
|
||||
corrected_query = self.correct_spelling(query)
|
||||
|
||||
# Generate query embedding
|
||||
query_embedding = self._get_embedding(corrected_query)
|
||||
if not query_embedding:
|
||||
return []
|
||||
|
||||
# Search in Qdrant
|
||||
search_results = self.qdrant_client.search(
|
||||
collection_name=self.collection_name,
|
||||
query_vector=query_embedding,
|
||||
limit=limit or self.search_limit
|
||||
)
|
||||
|
||||
# Convert to MusicSearchResult objects
|
||||
results = []
|
||||
for hit in search_results:
|
||||
if hit.score >= self.min_score_threshold:
|
||||
result = MusicSearchResult(
|
||||
file_path=hit.payload['file_path'],
|
||||
title=hit.payload['title'],
|
||||
language=hit.payload['language'],
|
||||
romanized=hit.payload['romanized'],
|
||||
alternatives=hit.payload['alternatives'],
|
||||
score=hit.score,
|
||||
metadata=hit.payload['metadata']
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
self.logger.debug(f"Found {len(results)} matching songs for query: '{query}'")
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Search failed: {e}")
|
||||
return []
|
||||
|
||||
def find_best_match(self, query: str) -> Optional[MusicSearchResult]:
|
||||
"""Find the single best matching song"""
|
||||
results = self.search(query, limit=1)
|
||||
return results[0] if results else None
|
||||
|
||||
def is_collection_indexed(self) -> bool:
|
||||
"""Check if the collection has been indexed"""
|
||||
if not self.is_initialized:
|
||||
return False
|
||||
|
||||
try:
|
||||
collection_info = self.qdrant_client.get_collection(self.collection_name)
|
||||
return collection_info.points_count > 0
|
||||
except:
|
||||
return False
|
||||
|
||||
def get_collection_stats(self) -> Dict:
|
||||
"""Get statistics about the indexed collection"""
|
||||
if not self.is_initialized:
|
||||
return {}
|
||||
|
||||
try:
|
||||
collection_info = self.qdrant_client.get_collection(self.collection_name)
|
||||
return {
|
||||
'points_count': collection_info.points_count,
|
||||
'segments_count': collection_info.segments_count,
|
||||
}
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to get collection stats: {e}")
|
||||
return {}
|
||||
|
|
@ -39,4 +39,8 @@ boto3
|
|||
deepgram-sdk==4.8.1
|
||||
fuzzywuzzy
|
||||
Levenshtein
|
||||
amazon_transcribe
|
||||
amazon_transcribe
|
||||
# Semantic search dependencies
|
||||
qdrant-client>=1.7.0
|
||||
sentence-transformers>=2.2.0
|
||||
pyspellchecker>=0.7.0
|
||||
Loading…
Reference in a new issue