1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
| import numpy as np import faiss from sentence_transformers import SentenceTransformer from transformers import AutoTokenizer, AutoModel import torch import asyncio from typing import List, Dict, Optional, Tuple import hashlib from dataclasses import dataclass from enum import Enum
class SearchStrategy(Enum): SEMANTIC = "semantic" HYBRID = "hybrid" KEYWORD = "keyword" MULTI_MODAL = "multi_modal"
@dataclass class DocumentChunk: """文档块数据结构""" id: str content: str embedding: Optional[np.ndarray] = None metadata: Dict[str, any] = None score: float = 0.0
class SemanticSearchEngine: """语义搜索引擎""" def __init__(self, model_name: str = "sentence-transformers/all-MiniLM-L6-v2"): self.model_name = model_name self.encoder = SentenceTransformer(model_name) self.dimension = self.encoder.get_sentence_embedding_dimension()
self.index = faiss.IndexFlatIP(self.dimension) self.doc_chunks = {}
self.text_cleaner = TextCleaner()
def encode_texts(self, texts: List[str]) -> np.ndarray: """编码文本为向量""" embeddings = self.encoder.encode(texts, convert_to_numpy=True, normalize_embeddings=True) return embeddings.astype('float32')
def add_documents(self, chunks: List[DocumentChunk]): """添加文档块到索引""" texts = [chunk.content for chunk in chunks] embeddings = self.encode_texts(texts)
self.index.add(embeddings)
for i, chunk in enumerate(chunks): chunk.embedding = embeddings[i] self.doc_chunks[len(self.doc_chunks)] = chunk
def search(self, query: str, top_k: int = 10) -> List[DocumentChunk]: """语义搜索""" query_embedding = self.encode_texts([query])[0]
scores, indices = self.index.search(np.array([query_embedding]), top_k)
results = [] for score, idx in zip(scores[0], indices[0]): if idx != -1 and idx in self.doc_chunks: chunk = self.doc_chunks[idx] chunk.score = float(score) results.append(chunk)
return results
def batch_search(self, queries: List[str], top_k: int = 10) -> List[List[DocumentChunk]]: """批量搜索""" query_embeddings = self.encode_texts(queries) scores, indices = self.index.search(query_embeddings, top_k)
results_batch = [] for i, (query_scores, query_indices) in enumerate(zip(scores, indices)): results = [] for score, idx in zip(query_scores, query_indices): if idx != -1 and idx in self.doc_chunks: chunk = self.doc_chunks[idx] chunk.score = float(score) results.append(chunk) results_batch.append(results)
return results_batch
class HybridSearchEngine: """混合搜索引擎""" def __init__(self, semantic_engine: SemanticSearchEngine, alpha: float = 0.7): self.semantic_engine = semantic_engine self.alpha = alpha self.keyword_engine = KeywordSearchEngine()
def search(self, query: str, top_k: int = 10) -> List[DocumentChunk]: """混合搜索:结合语义和关键词""" semantic_results = self.semantic_engine.search(query, top_k * 2)
keyword_results = self.keyword_engine.search(query, top_k * 2)
combined_results = self.combine_search_results( semantic_results, keyword_results, self.alpha )
return combined_results[:top_k]
def combine_search_results( self, semantic_results: List[DocumentChunk], keyword_results: List[DocumentChunk], alpha: float ) -> List[DocumentChunk]: """融合搜索结果""" semantic_scores = {chunk.id: chunk.score for chunk in semantic_results} keyword_scores = {chunk.id: chunk.score for chunk in keyword_results}
all_ids = set(semantic_scores.keys()) | set(keyword_scores.keys()) combined_chunks = []
for doc_id in all_ids: sem_score = semantic_scores.get(doc_id, 0.0) kw_score = keyword_scores.get(doc_id, 0.0)
normalized_sem = sem_score / (max(semantic_scores.values()) if semantic_scores else 1.0) normalized_kw = kw_score / (max(keyword_scores.values()) if keyword_scores else 1.0)
combined_score = alpha * normalized_sem + (1 - alpha) * normalized_kw
if doc_id in self.semantic_engine.doc_chunks: chunk = self.semantic_engine.doc_chunks[doc_id] else: chunk = DocumentChunk(id=doc_id, content="", score=combined_score)
chunk.score = combined_score combined_chunks.append(chunk)
combined_chunks.sort(key=lambda x: x.score, reverse=True) return combined_chunks
class KeywordSearchEngine: """关键词搜索引擎""" def __init__(self): self.inverted_index = {} self.doc_lengths = {} self.avg_doc_length = 0 self.vocab = set()
def add_documents(self, chunks: List[DocumentChunk]): """添加文档到倒排索引""" total_length = 0
for chunk in chunks: doc_id = chunk.id tokens = self.tokenize(chunk.content)
self.doc_lengths[doc_id] = len(tokens) total_length += len(tokens)
term_freq = {} for token in tokens: self.vocab.add(token) term_freq[token] = term_freq.get(token, 0) + 1
for term, freq in term_freq.items(): if term not in self.inverted_index: self.inverted_index[term] = {} self.inverted_index[term][doc_id] = freq
if len(self.doc_lengths) > 0: self.avg_doc_length = total_length / len(self.doc_lengths)
def search(self, query: str, top_k: int = 10) -> List[DocumentChunk]: """关键词搜索(使用BM25算法)""" query_tokens = self.tokenize(query) doc_scores = {}
k1 = 1.5 b = 0.75
for term in query_tokens: if term in self.inverted_index: n_qi = len(self.inverted_index[term]) idf = np.log((len(self.doc_lengths) - n_qi + 0.5) / (n_qi + 0.5) + 1)
for doc_id, tf in self.inverted_index[term].items(): doc_len = self.doc_lengths.get(doc_id, 0) numerator = tf * (k1 + 1) denominator = tf + k1 * (1 - b + b * doc_len / self.avg_doc_length) score = idf * (numerator / denominator)
doc_scores[doc_id] = doc_scores.get(doc_id, 0) + score
results = [] for doc_id, score in sorted(doc_scores.items(), key=lambda x: x[1], reverse=True)[:top_k]: chunk = DocumentChunk(id=doc_id, content="", score=score) results.append(chunk)
return results
def tokenize(self, text: str) -> List[str]: """简单的标记化""" import re tokens = re.findall(r'\b\w+\b', text.lower()) return tokens
class TextCleaner: """文本清洗器""" def __init__(self): self.stop_words = set([ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that', 'these', 'those' ])
def clean(self, text: str) -> str: """清洗文本""" import re
text = re.sub(r'[^\w\s\u4e00-\u9fff.,!?;:]', ' ', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
|