Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /topoteretes_cognee /cognee /modules /retrieval /jaccard_retrival.py
| from cognee.modules.retrieval.lexical_retriever import LexicalRetriever, tokenize_words | |
| from collections import Counter | |
| from typing import Optional | |
| class JaccardChunksRetriever(LexicalRetriever): | |
| """ | |
| Retriever that specializes LexicalRetriever to use Jaccard similarity. | |
| """ | |
| def __init__( | |
| self, | |
| top_k: int = 15, | |
| with_scores: bool = False, | |
| stop_words: Optional[list[str]] = None, | |
| multiset_jaccard: bool = False, | |
| ): | |
| """ | |
| Parameters | |
| ---------- | |
| top_k : int | |
| Number of top results to return. | |
| with_scores : bool | |
| If True, return (payload, score) pairs. Otherwise, only payloads. | |
| stop_words : list[str], optional | |
| List of tokens to filter out. | |
| multiset_jaccard : bool | |
| If True, use multiset Jaccard (frequency aware). | |
| """ | |
| self.stop_words = {t.lower() for t in stop_words} if stop_words else set() | |
| self.multiset_jaccard = multiset_jaccard | |
| super().__init__( | |
| tokenizer=self._tokenizer, scorer=self._scorer, top_k=top_k, with_scores=with_scores | |
| ) | |
| def _tokenizer(self, text: str) -> list[str]: | |
| """Tokenizer: lowercases, splits on word characters (w+), filters stopwords.""" | |
| return tokenize_words(text, self.stop_words) | |
| def _scorer(self, query_tokens: list[str], chunk_tokens: list[str]) -> float: | |
| """ | |
| Jaccard similarity scorer. | |
| - If multiset_jaccard=True, uses frequency-aware Jaccard. | |
| - Otherwise, normal set Jaccard. | |
| """ | |
| if self.multiset_jaccard: | |
| q_counts, c_counts = Counter(query_tokens), Counter(chunk_tokens) | |
| numerator = sum(min(q_counts[t], c_counts[t]) for t in set(q_counts) | set(c_counts)) | |
| denominator = sum(max(q_counts[t], c_counts[t]) for t in set(q_counts) | set(c_counts)) | |
| return numerator / denominator if denominator else 0.0 | |
| else: | |
| q_set, c_set = set(query_tokens), set(chunk_tokens) | |
| if not q_set or not c_set: | |
| return 0.0 | |
| return len(q_set & c_set) / len(q_set | c_set) | |
Xet Storage Details
- Size:
- 2.17 kB
- Xet hash:
- cb25c7d3315e16e5de59567d8a6199279fae527d560147dc426581588d2be744
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.