|
| 1 | +""" |
| 2 | +Shared primitives for Fractal Latent RAG. |
| 3 | +
|
| 4 | +All embedding, normalization, and chunking logic lives here — ONE copy. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import hashlib |
| 10 | +from typing import Protocol, runtime_checkable |
| 11 | + |
| 12 | +import numpy as np |
| 13 | + |
| 14 | + |
| 15 | +@runtime_checkable |
| 16 | +class EmbeddingBackend(Protocol): |
| 17 | + """Protocol for pluggable embedding backends.""" |
| 18 | + def embed(self, text: str) -> np.ndarray: ... |
| 19 | + @property |
| 20 | + def dim(self) -> int: ... |
| 21 | + |
| 22 | + |
| 23 | +class HashEmbedding: |
| 24 | + """Deterministic MD5-seeded random vectors. For testing and reproducibility only. |
| 25 | + These vectors have NO semantic meaning — cosine similarity is random noise.""" |
| 26 | + |
| 27 | + def __init__(self, dim: int = 64): |
| 28 | + self._dim = dim |
| 29 | + |
| 30 | + def embed(self, text: str) -> np.ndarray: |
| 31 | + seed = int(hashlib.md5(text.encode('utf-8')).hexdigest(), 16) % (2**32) |
| 32 | + rng = np.random.default_rng(seed) |
| 33 | + vec = rng.standard_normal(self._dim).astype(np.float32) |
| 34 | + return vec / np.linalg.norm(vec) |
| 35 | + |
| 36 | + @property |
| 37 | + def dim(self) -> int: |
| 38 | + return self._dim |
| 39 | + |
| 40 | + |
| 41 | +class SentenceTransformerEmbedding: |
| 42 | + """Real semantic embeddings via sentence-transformers. |
| 43 | + Default model: BAAI/bge-m3 (1024 dim, multi-granularity native). |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__(self, model_name: str = "BAAI/bge-m3"): |
| 47 | + from sentence_transformers import SentenceTransformer |
| 48 | + self._model = SentenceTransformer(model_name) |
| 49 | + self._dim = self._model.get_sentence_embedding_dimension() |
| 50 | + |
| 51 | + def embed(self, text: str) -> np.ndarray: |
| 52 | + return self._model.encode(text, normalize_embeddings=True).astype(np.float32) |
| 53 | + |
| 54 | + @property |
| 55 | + def dim(self) -> int: |
| 56 | + return self._dim |
| 57 | + |
| 58 | + |
| 59 | +def normalize(vec: np.ndarray) -> np.ndarray: |
| 60 | + """Safe L2 normalization. Returns zero vector on zero-norm input.""" |
| 61 | + norm = np.linalg.norm(vec) |
| 62 | + return vec / norm if norm > 0 else vec |
| 63 | + |
| 64 | + |
| 65 | +def chunk_fractal(text: str) -> tuple[list[str], list[str], str]: |
| 66 | + """Fractal chunking: sentences (L0) -> paragraphs (L1) -> full doc (L2). |
| 67 | +
|
| 68 | + Sentence splitting uses regex boundaries that handle decimals, percentages, |
| 69 | + abbreviations, and statistical notation common in scientific text. |
| 70 | + Fragments shorter than 30 chars are merged into the preceding sentence. |
| 71 | + """ |
| 72 | + import re |
| 73 | + |
| 74 | + # Split on period/!/? followed by whitespace and an uppercase letter. |
| 75 | + # This avoids splitting on decimals (0.79), abbreviations (e.g.), and |
| 76 | + # statistical notation (P = 0.001). |
| 77 | + raw = re.split(r'(?<=[.!?])\s+(?=[A-Z])', text) |
| 78 | + |
| 79 | + # Clean and filter |
| 80 | + sentences = [s.strip() for s in raw if s.strip()] |
| 81 | + |
| 82 | + # Merge short fragments (< 30 chars) into previous sentence |
| 83 | + if len(sentences) > 1: |
| 84 | + merged = [sentences[0]] |
| 85 | + for s in sentences[1:]: |
| 86 | + if len(s) < 30 and merged: |
| 87 | + merged[-1] = merged[-1] + ' ' + s |
| 88 | + else: |
| 89 | + merged.append(s) |
| 90 | + sentences = merged |
| 91 | + |
| 92 | + # Ensure non-empty |
| 93 | + if not sentences: |
| 94 | + sentences = [text] if text.strip() else [] |
| 95 | + |
| 96 | + paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()] or [text] |
| 97 | + |
| 98 | + # Virtual paragraph chunking for single-paragraph docs |
| 99 | + # When \n\n split produces only 1 paragraph but the doc has 4+ sentences, |
| 100 | + # group sentences into virtual paragraphs of ~3 sentences each. |
| 101 | + # This prevents L1 from being degenerate (identical to L2). |
| 102 | + if len(paragraphs) == 1 and len(sentences) >= 4: |
| 103 | + chunk_size = 3 |
| 104 | + virtual_paras = [] |
| 105 | + for i in range(0, len(sentences), chunk_size): |
| 106 | + group = sentences[i:i + chunk_size] |
| 107 | + virtual_paras.append(' '.join(group)) |
| 108 | + paragraphs = virtual_paras |
| 109 | + |
| 110 | + return sentences, paragraphs, text |
0 commit comments