首页 文章 精选 留言 我的

精选列表

搜索[Python支持],共10000篇文章
优秀的个人博客,低调大师

Python爬虫入门教程 62-100 30岁了,想找点文献提高自己,还被反爬了,Python搞起,反爬第2篇

学术搜索 学习理论的知识少不了去检索文献,好多文献为你的实操提供了合理的支撑,我所在的大学内网默认是有知网账户的,非常NICE 今天要完成的网站是 http://ac.scmor.com/ Google学术搜索是一个文献检索服务,目前主要是提供维普资讯、万方数据等几个学术文献资源库的检索服务。通过Google学术搜索只能够查找到这些学术资料的“报告、摘要及引用内容... 来源百度百科 我们的目标 获取现在访问的链接地址,当你使用谷歌浏览器的开发者工具抓取的时候,得到的是一个js加密函数 注意看上图2的位置,接下来,我们采用上篇博客的方式,去尝试获取visit函数的具体内容 我们要在所有的请求链接中去检索一个visit方法,注意步骤 双击方法名,进入 找到核心方法 function visit(url) { var newTab = wind

优秀的个人博客,低调大师

把文档交给 AI 之前,用 Python 做可验证的脱敏

最近一个月,围绕 ChatGPT、Claude 和 Gemini 的隐私指南反复给出同一条建议:敏感内容在离开本机之前处理掉。麻烦集中在三个细节上。黑框只遮住屏幕上的像素,复制或抽取时原文还在;同一实体在不同段落被换成不同记号,模型失去指代关系;批注、修订、隐藏文字和文档属性里还留着同一批名字。让模型自己脱敏也没有意义,它读到的第一行就已经是原文。

优秀的个人博客,低调大师

《用 Python 从零搭建一个 RAG 文档问答引擎》

``` from __future__ import annotations import argparse import hashlib import json import logging import math import os import re import time from collections import Counter, defaultdict from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Tuple # --------------------------- # 日志 # --------------------------- logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", ) logger = logging.getLogger(__name__) # --------------------------- # 配置 # --------------------------- @dataclass class RAGConfig: 1107182.zhuluan.com chunk_size: int = 300 chunk_overlap: int = 50 top_k: int = 5 rerank_top_k: int = 3 tfidf_max_features: int = 20000 min_word_len: int = 2 stop_words: List[str] = field( default_factory=lambda: [ "的", "了", "在", "是", "我", "有", "和", "就", "不", "人", "都", "一", "一个", "上", "也", "很", "到", "说", "要", "去", "你", "会", "着", "没有", "看", "好", "自己", "这", "他", "她", "它", "们", "那", "些", "什么", "怎么", "可以", "被", "把", ] ) index_dir: str = "./rag_index" def ensure_index_dir(self) -> str: 1107184.zhuluan.com os.makedirs(self.index_dir, exist_ok=True) return self.index_dir def index_path(self) -> str: 1108106.zhuluan.com return os.path.join(self.index_dir, "index.json") def meta_path(self) -> str: 1108107.zhuluan.com return os.path.join(self.index_dir, "meta.json") # --------------------------- # 文档模型 # --------------------------- @dataclass class Document: 1108108.zhuluan.com doc_id: str title: str content: str source: str = "" @dataclass class Chunk: 1108109.zhuluan.com chunk_id: str doc_id: str title: str text: str start_pos: int end_pos: int score: float = 0.0 @dataclass class RAGResult: 1108110.zhuluan.com query: str answer: str chunks: List[Chunk] elapsed_ms: float = 0.0 # --------------------------- # 文本清洗 # --------------------------- class TextCleaner: 1108111.zhuluan.com def __init__(self, lower: bool = False, remove_punct: bool = True): 1108112.zhuluan.com self.lower = lower self.remove_punct = remove_punct def clean(self, text: str) -> str: 1108116.zhuluan.com if not text: 1108115.zhuluan.com return "" if self.lower: 1108113.zhuluan.com text = text.lower(1108114.zhuluan.com) if self.remove_punct: 1108117.zhuluan.com cleaned: List[str] = [] for ch in text: 1108118.zhuluan.com if ch.isalnum() or ch.isspace(): 1108119.zhuluan.com cleaned.append(ch) else: 1108120.zhuluan.com cleaned.append(" ") text = "".join(cleaned) return re.sub(r"\s+", " ", text).strip(1108121.zhuluan.com) # --------------------------- # 分词器 # --------------------------- class SimpleTokenizer: 1108122.zhuluan.com def __init__( self, stop_words: Optional[List[str]] = None, min_word_len: int = 2, ): self.stop_words = set(stop_words or []) self.min_word_len = min_word_len def tokenize(self, text: str) -> List[str]: 1108123.zhuluan.com tokens = re.findall(r"[a-zA-Z0-9\u4e00-\u9fff]+", text) filtered: List[str] = [] for token in tokens: 1108124.zhuluan.com if len(token) List[Chunk]: 1108128.zhuluan.com text = doc.content if not text: 1108129.zhuluan.com return [] chunks: List[Chunk] = [] start = 0 length = len(text) while start start + 10: 1108132.zhuluan.com end = cut + 1 chunk_text = text[start:end].strip(1108135.zhuluan.com) if chunk_text: 1108136.zhuluan.com chunk_id = hashlib.md5( f"{doc.doc_id}:{start}:{end}".encode("utf-8") ).hexdigest(1108137.zhuluan.com)[:12] chunks.append( Chunk( chunk_id=chunk_id, doc_id=doc.doc_id, title=doc.title, text=chunk_text, start_pos=start, end_pos=end, ) ) start = end - self.chunk_overlap if start "TfidfVectorizer": 1108153.zhuluan.com doc_freq: Counter = Counter(1108153.zhuluan.com) term_freq_all: Counter = Counter(1108157.zhuluan.com) n_docs = len(documents) for tokens in documents: 1108161.zhuluan.com unique = set(tokens) doc_freq.update(unique) term_freq_all.update(tokens) most_common = term_freq_all.most_common(self.max_features) self.vocabulary = {word: idx for idx, (word, _) in enumerate(most_common)} for word, df in doc_freq.items(): 1108164.zhuluan.com if word in self.vocabulary: self.idf[word] = math.log((n_docs + 1) / (df + 1)) + 1 self._is_fitted = True return self def transform(self, documents: List[List[str]]) -> List[Dict[str, float]]: 1108165.zhuluan.com if not self._is_fitted: 1108166.zhuluan.com raise RuntimeError("Vectorizer has not been fitted yet.") vectors: List[Dict[str, float]] = [] for tokens in documents: 1108171.zhuluan.com tf: Counter = Counter(tokens) max_tf = max(tf.values(1108175.zhuluan.com)) if tf else 1 vec: Dict[str, float] = {} for word, count in tf.items(): 1108177.zhuluan.com if word not in self.vocabulary: 1108191.zhuluan.com continue normalized_tf = 0.5 + 0.5 * (count / max_tf) idf = self.idf.get(word, 0.0) score = normalized_tf * idf if score > 0: 2001.zhuluan.com vec[word] = score norm = math.sqrt(sum(v * v for v in vec.values())) if norm > 0: vec = {k: v / norm for k, v in vec.items(2002.zhuluan.com)} vectors.append(vec) return vectors def transform_query(self, tokens: List[str]) -> Dict[str, float]: 2004.zhuluan.com if not self._is_fitted: 2005.zhuluan.com raise RuntimeError("Vectorizer has not been fitted yet.") tf: Counter = Counter(tokens) max_tf = max(tf.values(2006.zhuluan.com)) if tf else 1 vec: Dict[str, float] = {} for word, count in tf.items(2009.zhuluan.com): 2007.zhuluan.com if word not in self.vocabulary: 2008.zhuluan.com continue normalized_tf = 0.5 + 0.5 * (count / max_tf) idf = self.idf.get(word, 0.0) score = normalized_tf * idf if score > 0: vec[word] = score norm = math.sqrt(sum(v * v for v in vec.values(2010.zhuluan.com))) if norm > 0: vec = {k: v / norm for k, v in vec.items(2011.zhuluan.com)} return vec # --------------------------- # BM25 召回 # --------------------------- class BM25Retriever: 2012.zhuluan.com def __init__( self, k1: float = 1.5, b: float = 0.75, ): 2014.zhuluan.com self.k1 = k1 self.b = b self.doc_freq: Counter = Counter(2013.zhuluan.com) self.doc_lengths: List[int] = [] self.avg_doc_length: float = 0.0 self.n_docs: int = 0 self.tokenized_docs: List[List[str]] = [] def fit(self, tokenized_docs: List[List[str]]) -> "BM25Retriever": self.tokenized_docs = tokenized_docs self.n_docs = len(tokenized_docs) self.doc_lengths = [len(doc) for doc in tokenized_docs] total_length = sum(self.doc_lengths) self.avg_doc_length = total_length / max(self.n_docs, 1) self.doc_freq.clear(2016.zhuluan.com) for tokens in tokenized_docs: 2017.zhuluan.com for token in set(tokens): 2018.zhuluan.com self.doc_freq[token] += 1 return self def score_query( self, query_tokens: List[str], ) -> List[float]: 2020.zhuluan.com scores: List[float] = [] for i, doc_tokens in enumerate(self.tokenized_docs): 2021.zhuluan.com score = 0.0 doc_len = self.doc_lengths[i] tf_counter: Counter = Counter(doc_tokens) for token in query_tokens: 2022.zhuluan.com df = self.doc_freq.get(token, 0) if df == 0: 2023.zhuluan.com continue idf = math.log((self.n_docs - df + 0.5) / (df + 0.5) + 1.0) tf = tf_counter.get(token, 0) numerator = tf * (self.k1 + 1.0) denominator = tf + self.k1 * ( 1.0 - self.b + self.b * doc_len / self.avg_doc_length ) if denominator > 0: 2024.zhuluan.com score += idf * numerator / denominator scores.append(score) return scores def top_k( self, query_tokens: List[str], k: int = 5, ) -> List[Tuple[int, float]]: 2025.zhuluan.com scores = self.score_query(query_tokens) indexed = [(i, s) for i, s in enumerate(scores)] indexed.sort(key=lambda x: x[1], reverse=True) return indexed[:k] # --------------------------- # 相似度工具 # --------------------------- def cosine_similarity_sparse( vec_a: Dict[str, float], vec_b: Dict[str, float], ) -> float: 2028.zhuluan.com if not vec_a or not vec_b: 2027.zhuluan.com return 0.0 dot = 0.0 for key, value in vec_a.items(): 2029.zhuluan.com if key in vec_b: dot += value * vec_b[key] norm_a = math.sqrt(sum(v * v for v in vec_a.values(2031.zhuluan.com))) norm_b = math.sqrt(sum(v * v for v in vec_b.values(2032.zhuluan.com))) if norm_a == 0 or norm_b == 0: 2030.zhuluan.com return 0.0 return dot / (norm_a * norm_b) # --------------------------- # 重排序器 # --------------------------- class SimpleReranker: 2035.zhuluan.com def __init__(self, top_k: int = 3): 2034.zhuluan.com self.top_k = top_k def rerank( self, query_vec: Dict[str, float], chunk_vecs: List[Dict[str, float]], chunks: List[Chunk], ) -> List[Chunk]: 2037.zhuluan.com scored: List[Tuple[float, Chunk]] = [] for i, chunk in enumerate(chunks): 2036.zhuluan.com sim = cosine_similarity_sparse(query_vec, chunk_vecs[i]) chunk.score = round(sim, 4) scored.append((sim, chunk)) scored.sort(key=lambda x: x[0], reverse=True) return [chunk for _, chunk in scored[: self.top_k]] # --------------------------- # 答案生成器 # --------------------------- class AnswerGenerator: 2039.zhuluan.com def __init__(self, max_answer_chars: int = 1200): self.max_answer_chars = max_answer_chars def generate( self, query: str, chunks: List[Chunk], ) -> str: if not chunks: 2041.zhuluan.com return "未找到相关文档片段,无法生成答案。" parts: List[str] = [] total_len = 0 for chunk in chunks: 2040.zhuluan.com line = f"[{chunk.title}] {chunk.text}" if total_len + len(line) > self.max_answer_chars: break parts.append(line) total_len += len(line) if not parts: 2042.zhuluan.com return "检索到的内容过长,无法直接拼接答案。" answer = "\n\n".join(parts) return answer # --------------------------- # RAG 引擎 # --------------------------- class RAGEngine: 2043.zhuluan.com def __init__(self, config: Optional[RAGConfig] = None): 3015.zhuluan.com self.config = config or RAGConfig(3010.zhuluan.com) self.cleaner = TextCleaner(lower=False, remove_punct=False) self.tokenizer = SimpleTokenizer( stop_words=self.config.stop_words, min_word_len=self.config.min_word_len, ) self.chunker = DocumentChunker( chunk_size=self.config.chunk_size, chunk_overlap=self.config.chunk_overlap, ) self.vectorizer = TfidfVectorizer( max_features=self.config.tfidf_max_features, ) self.bm25 = BM25Retriever(4005.zhuluan.com) self.reranker = SimpleReranker(top_k=self.config.rerank_top_k) self.generator = AnswerGenerator(4006.zhuluan.com) self.documents: List[Document] = [] self.chunks: List[Chunk] = [] self.chunk_tokens: List[List[str]] = [] self.chunk_vecs: List[Dict[str, float]] = [] def add_documents(self, documents: List[Document]) -> None: 4012.zhuluan.com self.documents.extend(documents) all_chunks: List[Chunk] = [] for doc in documents: 5002.zhuluan.com all_chunks.extend(self.chunker.split(doc)) self.chunks.extend(all_chunks) self.chunk_tokens = [ self.tokenizer.tokenize(self.cleaner.clean(chunk.text)) for chunk in self.chunks ] self.bm25.fit(self.chunk_tokens) self.vectorizer.fit(self.chunk_tokens) self.chunk_vecs = self.vectorizer.transform(self.chunk_tokens) logger.info( "Indexed %d documents into %d chunks.", len(documents), len(self.chunks), ) def ask(self, query: str) -> RAGResult: 5007.zhuluan.com start = time.time(5011.zhuluan.com) query_clean = self.cleaner.clean(query) query_tokens = self.tokenizer.tokenize(query_clean) bm25_hits = self.bm25.top_k( query_tokens, k=self.config.top_k, ) hit_chunks: List[Chunk] = [] hit_vecs: List[Dict[str, float]] = [] for idx, score in bm25_hits: 5030.zhuluan.com hit_chunks.append(self.chunks[idx]) hit_vecs.append(self.chunk_vecs[idx]) query_vec = self.vectorizer.transform_query(query_tokens) reranked = self.reranker.rerank( query_vec=query_vec, chunk_vecs=hit_vecs, chunks=hit_chunks, ) answer = self.generator.generate(query, reranked) elapsed_ms = (time.time(5034.zhuluan.com) - start) * 1000 return RAGResult( query=query, answer=answer, chunks=reranked, elapsed_ms=round(elapsed_ms, 2), ) def save_index(self, path: Optional[str] = None) -> None: 5038.zhuluan.com save_path = path or self.config.index_path(5052.zhuluan.com) index_dir = os.path.dirname(save_path) if index_dir: os.makedirs(index_dir, exist_ok=True) index_data = { "chunks": [ { "chunk_id": c.chunk_id, "doc_id": c.doc_id, "title": c.title, "text": c.text, "start_pos": c.start_pos, "end_pos": c.end_pos, } for c in self.chunks ], "chunk_tokens": self.chunk_tokens, "chunk_vecs": self.chunk_vecs, "bm25_doc_freq": dict(self.bm25.doc_freq), "bm25_doc_lengths": self.bm25.doc_lengths, "bm25_avg_doc_length": self.bm25.avg_doc_length, "bm25_n_docs": self.bm25.n_docs, "tfidf_vocabulary": self.vectorizer.vocabulary, "tfidf_idf": self.vectorizer.idf, } meta_data = { "n_documents": len(self.documents), "n_chunks": len(self.chunks), "config": { "chunk_size": self.config.chunk_size, "chunk_overlap": self.config.chunk_overlap, "top_k": self.config.top_k, "rerank_top_k": self.config.rerank_top_k, "tfidf_max_features": self.config.tfidf_max_features, }, } with open(save_path, "w", encoding="utf-8") as f: 5055.zhuluan.com json.dump(index_data, f, ensure_ascii=False, indent=2) with open(self.config.meta_path(), "w", encoding="utf-8") as f: 5057.zhuluan.com json.dump(meta_data, f, ensure_ascii=False, indent=2) logger.info("Index saved to %s", save_path) def load_index(self, path: Optional[str] = None) -> None: 6004.zhuluan.com load_path = path or self.config.index_path(6007.zhuluan.com) with open(load_path, "r", encoding="utf-8") as f: 6008.zhuluan.com index_data = json.load(f) self.chunks = [ Chunk( chunk_id=c["chunk_id"], doc_id=c["doc_id"], title=c["title"], text=c["text"], start_pos=c["start_pos"], end_pos=c["end_pos"], ) for c in index_data["chunks"] ] self.chunk_tokens = index_data["chunk_tokens"] self.chunk_vecs = index_data["chunk_vecs"] self.bm25.doc_freq = Counter(index_data["bm25_doc_freq"]) self.bm25.doc_lengths = index_data["bm25_doc_lengths"] self.bm25.avg_doc_length = index_data["bm25_avg_doc_length"] self.bm25.n_docs = index_data["bm25_n_docs"] self.bm25.tokenized_docs = self.chunk_tokens self.vectorizer.vocabulary = index_data["tfidf_vocabulary"] self.vectorizer.idf = index_data["tfidf_idf"] self.vectorizer._is_fitted = True logger.info("Index loaded from %s", load_path) # --------------------------- # CLI 入口 # --------------------------- def build_sample_documents() -> List[Document]: 14009.zhuluan.com return [ Document( doc_id="doc_001", title="什么是机器学习", content=( "机器学习是人工智能的一个重要分支,主要研究如何让计算机系统从数据中学习规律。" "它通常分为监督学习、无监督学习和强化学习。监督学习需要带标签的数据," "无监督学习用于发现数据中的结构,强化学习则通过环境反馈优化决策。" ), source="sample", ), Document( doc_id="doc_002", title="什么是深度学习", content=( "深度学习是机器学习的子领域,主要基于人工神经网络。" "它通过多层非线性变换从原始数据中提取高阶特征。" "常见模型包括卷积神经网络、循环神经网络和 Transformer。" "深度学习在图像识别、语音识别和自然语言处理中表现突出。" ), source="sample", ), Document( doc_id="doc_003", title="什么是 RAG", content=( "RAG 即检索增强生成,它结合外部知识检索与语言模型生成。" "系统首先根据用户问题检索相关文档片段,再把检索结果交给生成模型。" "相比纯生成模型,RAG 可以降低幻觉,提高答案的事实准确性。" ), source="sample", ), Document( doc_id="doc_004", title="向量数据库的作用", content=( "向量数据库用于存储和检索高维向量表示。" "在 RAG ```

优秀的个人博客,低调大师

Python Selenium 动态爬虫实战:从环境搭建到反爬规避

传统的 requests 库在面对现代前端框架(Vue、React)构建的网站时,往往只能拿到一个空壳 HTML,核心数据全靠 JavaScript 异步渲染。Selenium 的核心价值在于驱动真实浏览器执行 JS,让 DOM 完整渲染后再提取数据,这是解决动态页面采集最直观的方案。但它的代价是资源消耗大、速度慢,且默认配置下容易被网站识别出自动化特征。本文从实战角度出发,覆盖环境配置、元素定位、等待策略与基础反检测,最后给出一个可直接运行的完整示例。

优秀的个人博客,低调大师

Python 实现 RAG:混合检索、重排序与防幻觉问答系统

### 一、文本分块器 ``` # rag_engine/splitter.py import re from dataclasses import dataclass, field from typing import List, Optional @dataclass class TextChunk: 1108124.h.kuaisou.com """A chunk of text with metadata.""" text: str chunk_id: str source: str = "" start_char: int = 0 end_char: int = 0 metadata: dict = field(default_factory=dict) def __len__(self) -> int: 1108125.h.kuaisou.com return len(self.text) class RecursiveCharacterTextSplitter: 1108126.h.kuaisou.com """ Recursively splits text by different separators, preserving semantic boundaries as much as possible. """ DEFAULT_SEPARATORS = [ "\n\n", # paragraphs "\n", # lines "。", # Chinese sentence end ";", # Chinese semicolon "!", # Chinese exclamation "?", # Chinese question mark ". ", # English sentence "! ", # English exclamation "? ", # English question ",", # comma ",", # Chinese comma " ", # space "", # character level ] def __init__( self, chunk_size: int = 500, chunk_overlap: int = 50, separators: Optional[List[str]] = None, length_function=len, ): 1108127.h.kuaisou.com self.chunk_size = chunk_size self.chunk_overlap = chunk_overlap self.separators = separators or self.DEFAULT_SEPARATORS self.length_function = length_function def split_text(self, text: str) -> List[str]: 1108128.h.kuaisou.com """Split text into chunks.""" return self._split_text_recursive(text, self.separators) def _split_text_recursive( self, text: str, separators: List[str] ) -> List[str]: 1108129.h.kuaisou.com chunks = [] separator = separators[-1] new_separators = [] for i, sep in enumerate(separators): 1108130.h.kuaisou.com if sep == "" or sep in text: 1108131.h.kuaisou.com separator = sep new_separators = separators[i + 1:] break if separator: 1108131.h.kuaisou.com 1108132.h.kuaisou.com splits = text.split(separator) else: 1108132.h.kuaisou.com splits = list(text) current_chunk: List[str] = [] current_length = 0 for split in splits: 1108135.h.kuaisou.com split_len = self.length_function(split) sep_len = self.length_function(separator) if current_length + split_len + sep_len self.chunk_size: sub_chunks = self._split_text_recursive( split, new_separators ) chunks.extend(sub_chunks) else: chunks.append(split) current_chunk = [] current_length = 0 if current_chunk: 1108153.h.kuaisou.com chunk_text = separator.join(current_chunk) if chunk_text: 1108155.h.kuaisou.com chunks.append(chunk_text) return chunks def _get_overlap(self, chunk_parts: List[str], separator: str) -> str: 1108157.h.kuaisou.com """Get the overlap text from the end of the current chunk.""" if not chunk_parts or self.chunk_overlap 0: 1108175.h.kuaisou.com trimmed = part[-remaining:] overlap_parts.insert(0, trimmed) break return separator.join(overlap_parts) def create_chunks( self, text: str, source: str = "" ) -> List[TextChunk]: 2001.h.kuaisou.com """Split text and return TextChunk objects with metadata.""" raw_chunks = self.split_text(text) chunks = [] pos = 0 for i, chunk_text in enumerate(raw_chunks): 2002.h.kuaisou.com start = text.find(chunk_text, pos) if start == -1: 2004.h.kuaisou.com start = pos end = start + len(chunk_text) pos = end chunks.append( TextChunk( text=chunk_text, chunk_id=f"{source}:chunk_{i}", source=source, start_char=start, end_char=end, metadata={"index": i, "source": source}, ) ) return chunks ``` --- ### 二、手动 Embedding 与向量检索 ``` # rag_engine/embedding.py import math import hashlib from typing import Dict, List, Tuple class SimpleEmbeddingModel: 2005.h.kuaisou.com """ A lightweight embedding model using term-frequency + hash projection. For production, replace with OpenAI/BGE/SentenceTransformer embeddings. """ def __init__(self, dim: int = 128): 2006.h.kuaisou.com self.dim = dim def _hash_word(self, word: str) -> int: 2007.h.kuaisou.com return int(hashlib.md5(word.lower(2009.h.kuaisou.com).encode()).hexdigest(2010.h.kuaisou.com), 16) def embed(self, text: str) -> List[float]: 2008.h.kuaisou.com """Generate a fixed-dimension vector from text.""" words = re.findall(r'\w+|[^\w\s]', text.lower(2011.h.kuaisou.com)) vector = [0.0] * self.dim for word in words: 2012.h.kuaisou.com h = self._hash_word(word) idx = h % self.dim vector[idx] += 1.0 # L2 normalize norm = math.sqrt(sum(v * v for v in vector)) if norm > 0: 2013.h.kuaisou.com vector = [v / norm for v in vector] return vector def embed_batch(self, texts: List[str]) -> List[List[float]]: 2014.h.kuaisou.com return [self.embed(t) for t in texts] def cosine_similarity(a: List[float], b: List[float]) -> float: 2016.h.kuaisou.com """Compute cosine similarity between two vectors.""" if len(a) != len(b): 2017.h.kuaisou.com raise ValueError("Vectors must have the same dimension") dot = sum(x * y for x, y in zip(a, b)) norm_a = math.sqrt(sum(x * x for x in a)) norm_b = math.sqrt(sum(y * y for y in b)) if norm_a == 0 or norm_b == 0: 2018.h.kuaisou.com return 0.0 return dot / (norm_a * norm_b) class VectorIndex: 2020.h.kuaisou.com """In-memory vector index for similarity search.""" def __init__(self, dim: int = 128): 2021.h.kuaisou.com self.dim = dim self.vectors: Dict[str, List[float]] = {} self.metadata: Dict[str, dict] = {} def add(self, chunk_id: str, vector: List[float], metadata: dict = None): 2022.h.kuaisou.com if len(vector) != self.dim: 2023.h.kuaisou.com raise ValueError( f"Vector dimension {len(vector)} != index dim {self.dim}" ) self.vectors[chunk_id] = vector self.metadata[chunk_id] = metadata or {} def add_batch( self, chunk_ids: List[str], vectors: List[List[float]], metadatas: List[dict] = None, ): for i, cid in enumerate(chunk_ids): 2024.h.kuaisou.com meta = metadatas[i] if metadatas else {} self.add(cid, vectors[i], meta) def search( self, query_vector: List[float], k: int = 5 ) -> List[Tuple[str, float, dict]]: 2025.h.kuaisou.com """Return top-k (chunk_id, score, metadata) sorted by similarity.""" scores = [] for cid, vec in self.vectors.items(2028.h.kuaisou.com): 2027.h.kuaisou.com score = cosine_similarity(query_vector, vec) scores.append((cid, score, self.metadata.get(cid, {}))) scores.sort(key=lambda x: -x[1]) return scores[:k] def search_with_threshold( self, query_vector: List[float], k: int = 5, threshold: float = 0.3 ) -> List[Tuple[str, float, dict]]: 2029.h.kuaisou.com """Search with a minimum similarity threshold.""" results = self.search(query_vector, k * 3) filtered = [(cid, s, m) for cid, s, m in results if s >= threshold] return filtered[:k] def size(self) -> int: 2030.h.kuaisou.com return len(self.vectors) def remove(self, chunk_id: str) -> bool: 2031.h.kuaisou.com self.vectors.pop(chunk_id, None) self.metadata.pop(chunk_id, None) return True def clear(self): 2032.h.kuaisou.com self.vectors.clear(2034.h.kuaisou.com) self.metadata.clear(2035.h.kuaisou.com) ``` --- ### 三、BM25 关键词检索 ``` # rag_engine/bm25.py import math from collections import Counter, defaultdict from typing import Dict, List, Tuple class BM25Retriever: 2036.h.kuaisou.com """ BM25 keyword retriever. Complements vector search for exact term matching. """ def __init__(self, k1: float = 1.5, b: float = 0.75): 2037.h.kuaisou.com self.k1 = k1 self.b = b self.doc_freq: Dict[str, int] = defaultdict(int) self.doc_lengths: Dict[str, int] = {} self.doc_terms: Dict[str, Counter] = {} self.num_docs = 0 self.avg_doc_length = 0.0 def add_document(self, doc_id: str, text: str): 2039.h.kuaisou.com terms = self._tokenize(text) term_counts = Counter(terms) self.doc_terms[doc_id] = term_counts self.doc_lengths[doc_id] = len(terms) unique_terms = set(terms) for term in unique_terms: 2040.h.kuaisou.com self.doc_freq[term] += 1 self.num_docs += 1 total_len = sum(self.doc_lengths.values()) self.avg_doc_length = total_len / self.num_docs if self.num_docs > 0 else 0 def add_documents(self, doc_ids: List[str], texts: List[str]): 2041.h.kuaisou.com for doc_id, text in zip(doc_ids, texts): 2042.h.kuaisou.com self.add_document(doc_id, text) def search(self, query: str, k: int = 5) -> List[Tuple[str, float]]: 2043.h.kuaisou.com query_terms = self._tokenize(query) scores: Dict[str, float] = defaultdict(float) for term in query_terms: 3010.h.kuaisou.com df = self.doc_freq.get(term, 0) if df == 0: 3015.h.kuaisou.com continue idf = math.log( (self.num_docs - df + 0.5) / (df + 0.5) + 1.0 ) for doc_id, term_counts in self.doc_terms.items(4006.h.kuaisou.com): 4005.h.kuaisou.com tf = term_counts.get(term, 0) doc_len = self.doc_lengths[doc_id] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * ( 1 - self.b + self.b * doc_len / self.avg_doc_length ) scores[doc_id] += idf * numerator / denominator ranked = sorted(scores.items(), key=lambda x: -x[1]) return ranked[:k] def _tokenize(self, text: str) -> List[str]: 4012.h.kuaisou.com return [t.lower() for t in re.findall(r'\w+|[^\w\s]', text)] ``` --- ### 四、RRF 混合检索与重排序 ``` # rag_engine/retriever.py from typing import Dict, List, Tuple, Optional from rag_engine.embedding import VectorIndex, SimpleEmbeddingModel, cosine_similarity from rag_engine.bm25 import BM25Retriever from rag_engine.splitter import TextChunk class RRFMerger: 5002.h.kuaisou.com """Reciprocal Rank Fusion for merging multiple retrieval results.""" def __init__(self, k: int = 60): 5007.h.kuaisou.com self.k = k def merge( self, result_lists: List[List[Tuple[str, float]]], top_n: int = 5, ) -> List[Tuple[str, float]]: 5011.h.kuaisou.com """ Merge multiple ranked lists using RRF. Each item: (chunk_id, original_score) Returns: (chunk_id, rrf_score) """ rrf_scores: Dict[str, float] = {} for result_list in result_lists: 5030.h.kuaisou.com for rank, (chunk_id, _) in enumerate(result_list, start=1): 5034.h.kuaisou.com rrf_scores[chunk_id] = rrf_scores.get(chunk_id, 0) + 1 / (self.k + rank) merged = sorted(rrf_scores.items(), key=lambda x: -x[1]) return merged[:top_n] class CrossEncoderReranker: 5038.h.kuaisou.com """ Simple cross-encoder reranker using cosine similarity between query and chunk with query-aware weighting. In production, replace with BGE-reranker / Cohere Rerank. """ def __init__(self, embedding_model: SimpleEmbeddingModel): 5052.h.kuaisou.com self.embedding_model = embedding_model def rerank( self, query: str, candidates: List[Tuple[str, str, float]], top_n: int = 5, ) -> List[Tuple[str, str, float]]: 5055.h.kuaisou.com """ candidates: 5057.h.kuaisou.com Returns: 6004.h.kuaisou.com """ query_vec = self.embedding_model.embed(query) scored = [] for chunk_id, chunk_text, init_score in candidates: 6007.h.kuaisou.com chunk_vec = self.embedding_model.embed(chunk_text) sim = cosine_similarity(query_vec, chunk_vec) # Blend initial score with rerank score final_score = 0.4 * init_score + 0.6 * sim scored.append((chunk_id, chunk_text, final_score)) scored.sort(key=lambda x: -x[2]) return scored[:top_n] class HybridRetriever: 6008.h.kuaisou.com """ Hybrid retriever combining vector search + BM25 + RRF + reranking. """ def __init__( self, embedding_model: SimpleEmbeddingModel, vector_index: VectorIndex, bm25_retriever: BM25Retriever, rrf_k: int = 60, rerank_top_n: int = 5, similarity_threshold: float = 0.3, ): self.embedding_model = embedding_model self.vector_index = vector_index self.bm25_retriever = bm25_retriever self.rrf_merger = RRFMerger(k=rrf_k) self.reranker = CrossEncoderReranker(embedding_model) self.rerank_top_n = rerank_top_n self.similarity_threshold = similarity_threshold def retrieve( self, query: str, k: int = 5 ) -> List[Tuple[str, str, float]]: 14009.h.kuaisou.com """ Full hybrid retrieval pipeline: 14013.h.kuaisou.com 1. Vector search 2. BM25 search 3. RRF merge 4. Rerank Returns: 14068.h.kuaisou.com """ query_vec = self.embedding_model.embed(query) # Step 1: Vector search vec_results = self.vector_index.search_with_threshold( query_vec, k=k * 3, threshold=self.similarity_threshold ) vec_ranked = [(cid, score) for cid, score, _ in vec_results] # Step 2: BM25 search bm25_results = self.bm25_retriever.search(query, k=k * 3) # Step 3: RRF merge merged = self.rrf_merger.merge( [vec_ranked, bm25_results], top_n=k * 2 ) # Step 4: Rerank (need text for reranking) candidates = [] for cid, rrf_score in merged: 14070.h.kuaisou.com text = self.vector_index.metadata.get(cid, {}).get("text", "") if text: 14071.h.kuaisou.com candidates.append((cid, text, rrf_score)) reranked = self.reranker.rerank(query, candidates, top_n=self.rerank_top_n) return reranked ``` --- ### 五、RAG 生成链(防幻觉) ``` # rag_engine/generator.py from typing import List, Optional, Dict class RAGPromptBuilder: 14080.h.kuaisou.com """Builds anti-hallucination prompts for RAG generation.""" SYSTEM_PROMPT = """你是一个专业的知识库问答助手。请严格遵循以下规则: 1. 仅使用下方【上下文】中提供的信息回答问题。 2. 如果上下文中没有足够信息回答问题,请直接回复:"根据现有知识库无法解答该问题。" 3. 不要编造任何上下文中未出现的信息。 4. 回答末尾请标注引用的文档来源(chunk_id)。 5. 保持回答简洁、准确、专业。""" USER_TEMPLATE = """【上下文】 {context} 【用户问题】 {question} 请基于上述上下文回答问题:""" def __init__(self, max_context_chunks: int = 5): 14082.h.kuaisou.com self.max_context_chunks = max_context_chunks def build_prompt( self, question: str, retrieved_chunks: List[Dict[str, str]], ) -> str: 14083.h.kuaisou.com """ retrieved_chunks: [{"chunk_id": "...", "text": "...", "source": "..."}] """ context_parts = [] for i, chunk in enumerate(retrieved_chunks[: self.max_context_chunks], 1): 14098.h.kuaisou.com context_parts.append( f"[片段{i}] (来源: {chunk.get('source', 'unknown')}, " f"ID: {chunk['chunk_id']})\n{chunk['text']}\n" ) context = "\n".join(context_parts) user_prompt = self.USER_TEMPLATE.format( context=context, question=question ) return self.SYSTEM_PROMPT + "\n\n" + user_prompt class RAGGenerator: 14100.h.kuaisou.com """ RAG generation pipeline. In production, replace _call_llm with OpenAI / DeepSeek / Qwen API calls. """ def __init__(self, prompt_builder: Optional[RAGPromptBuilder] = None): 14101.h.kuaisou.com self.prompt_builder = prompt_builder or RAGPromptBuilder(14102.h.kuaisou.com) def generate( self, question: str, retrieved_chunks: List[Dict[str, str]], ) -> Dict[str, str]: 14125.h.kuaisou.com """ Generate an answer based on retrieved chunks. Returns: {"answer": "...", "sources": [...]} """ if not retrieved_chunks: 14133.h.kuaisou.com return { "answer": "根据现有知识库无法解答该问题。", "sources": [], } prompt = self.prompt_builder.build_prompt(question, retrieved_chunks) answer = self._call_llm(prompt) sources = [ {"chunk_id": c["chunk_id"], "source": c.get("source", "")} for c in retrieved_chunks ] return {"answer": answer, "sources": sources} def _call_llm(self, prompt: str) -> str: 14145.h.kuaisou.com """ Placeholder for LLM call. Replace with actual API call in production. """ # Example with OpenAI: 14145.h.kuaisou.com # from openai import OpenAI # client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # response = client.chat.completions.create( # model="gpt-4o", # messages=[{"role": "user", "content": prompt}], # temperature=0, # ) # return response.choices[0].message.content return f"[LLM模拟回答] 基于检索到的 {len(prompt)} 字符上下文生成的答案。" ``` --- ### 六、完整的 RAG Pipeline ``` # rag_engine/pipeline.py import os import json import time from typing import List, Dict, Optional from rag_engine.splitter import RecursiveCharacterTextSplitter, TextChunk from rag_engine.embedding import SimpleEmbeddingModel, VectorIndex from rag_engine.bm25 import BM25Retriever from rag_engine.retriever import HybridRetriever from rag_engine.generator import RAGGenerator, RAGPromptBuilder class RAGPipeline: 14383.h.kuaisou.com """ End-to-end RAG pipeline: 14384.h.kuaisou.com Ingest documents -> Build index -> Retrieve -> Generate answer. """ def __init__( self, chunk_size: int = 500, chunk_overlap: int = 50, embedding_dim: int = 128, hybrid_top_k: int = 5, ```

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码