|
| 1 | +"""Abstract base class for code indexing implementations.""" |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from pathlib import Path |
| 5 | +from typing import Optional, TypeVar |
| 6 | + |
| 7 | +import numpy as np |
| 8 | + |
| 9 | +from codegen import Codebase |
| 10 | + |
| 11 | +T = TypeVar("T") # Type of the items being indexed (e.g., File, Symbol) |
| 12 | + |
| 13 | + |
| 14 | +class CodeIndex(ABC): |
| 15 | + """Abstract base class for semantic code search indices. |
| 16 | +
|
| 17 | + This class defines the interface for different code indexing implementations. |
| 18 | + Implementations can index at different granularities (files, symbols, etc.) |
| 19 | + and use different embedding strategies. |
| 20 | +
|
| 21 | + Attributes: |
| 22 | + codebase (Codebase): The codebase being indexed |
| 23 | + E (Optional[np.ndarray]): The embeddings matrix |
| 24 | + items (Optional[np.ndarray]): Array of items corresponding to embeddings |
| 25 | + commit_hash (Optional[str]): Git commit hash when index was last updated |
| 26 | + """ |
| 27 | + |
| 28 | + DEFAULT_SAVE_DIR = ".codegen" |
| 29 | + |
| 30 | + def __init__(self, codebase: Codebase): |
| 31 | + """Initialize the code index. |
| 32 | +
|
| 33 | + Args: |
| 34 | + codebase: The codebase to index |
| 35 | + """ |
| 36 | + self.codebase = codebase |
| 37 | + self.E: Optional[np.ndarray] = None |
| 38 | + self.items: Optional[np.ndarray] = None |
| 39 | + self.commit_hash: Optional[str] = None |
| 40 | + |
| 41 | + @property |
| 42 | + @abstractmethod |
| 43 | + def save_file_name(self) -> str: |
| 44 | + """The filename template for saving the index.""" |
| 45 | + pass |
| 46 | + |
| 47 | + @abstractmethod |
| 48 | + def _get_embeddings(self, items: list[T]) -> list[list[float]]: |
| 49 | + """Get embeddings for a list of items. |
| 50 | +
|
| 51 | + Args: |
| 52 | + items: List of items to get embeddings for |
| 53 | +
|
| 54 | + Returns: |
| 55 | + List of embedding vectors |
| 56 | + """ |
| 57 | + pass |
| 58 | + |
| 59 | + @abstractmethod |
| 60 | + def _get_items_to_index(self) -> list[tuple[T, str]]: |
| 61 | + """Get all items that should be indexed and their content. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + List of tuples (item, content_to_embed) |
| 65 | + """ |
| 66 | + pass |
| 67 | + |
| 68 | + @abstractmethod |
| 69 | + def _get_changed_items(self) -> set[T]: |
| 70 | + """Get set of items that have changed since last index update. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + Set of changed items |
| 74 | + """ |
| 75 | + pass |
| 76 | + |
| 77 | + def _get_current_commit(self) -> str: |
| 78 | + """Get the current git commit hash.""" |
| 79 | + current = self.codebase.current_commit |
| 80 | + if current is None: |
| 81 | + msg = "No current commit found. Repository may be empty or in a detached HEAD state." |
| 82 | + raise ValueError(msg) |
| 83 | + return current.hexsha |
| 84 | + |
| 85 | + def _get_default_save_path(self) -> Path: |
| 86 | + """Get the default save path for the index.""" |
| 87 | + save_dir = Path(self.codebase.repo_path) / self.DEFAULT_SAVE_DIR |
| 88 | + save_dir.mkdir(exist_ok=True) |
| 89 | + |
| 90 | + if self.commit_hash is None: |
| 91 | + self.commit_hash = self._get_current_commit() |
| 92 | + |
| 93 | + filename = self.save_file_name.format(commit=self.commit_hash[:8]) |
| 94 | + return save_dir / filename |
| 95 | + |
| 96 | + def create(self) -> None: |
| 97 | + """Create embeddings for all indexed items.""" |
| 98 | + self.commit_hash = self._get_current_commit() |
| 99 | + |
| 100 | + # Get items and their content |
| 101 | + items_with_content = self._get_items_to_index() |
| 102 | + if not items_with_content: |
| 103 | + self.E = np.array([]) |
| 104 | + self.items = np.array([]) |
| 105 | + return |
| 106 | + |
| 107 | + # Split into separate lists |
| 108 | + items, contents = zip(*items_with_content) |
| 109 | + |
| 110 | + # Get embeddings |
| 111 | + embeddings = self._get_embeddings(contents) |
| 112 | + |
| 113 | + # Store embeddings and item identifiers |
| 114 | + self.E = np.array(embeddings) |
| 115 | + self.items = np.array([str(item) for item in items]) # Store string identifiers |
| 116 | + |
| 117 | + def update(self) -> None: |
| 118 | + """Update embeddings for changed items only.""" |
| 119 | + if self.E is None or self.items is None or self.commit_hash is None: |
| 120 | + msg = "No index to update. Call create() or load() first." |
| 121 | + raise ValueError(msg) |
| 122 | + |
| 123 | + # Get changed items |
| 124 | + changed_items = self._get_changed_items() |
| 125 | + if not changed_items: |
| 126 | + return |
| 127 | + |
| 128 | + # Get content for changed items |
| 129 | + items_with_content = [(item, content) for item, content in self._get_items_to_index() if item in changed_items] |
| 130 | + |
| 131 | + if not items_with_content: |
| 132 | + return |
| 133 | + |
| 134 | + items, contents = zip(*items_with_content) |
| 135 | + new_embeddings = self._get_embeddings(contents) |
| 136 | + |
| 137 | + # Create mapping of items to their indices |
| 138 | + item_to_idx = {str(item): idx for idx, item in enumerate(self.items)} |
| 139 | + |
| 140 | + # Update embeddings |
| 141 | + for item, embedding in zip(items, new_embeddings): |
| 142 | + item_key = str(item) |
| 143 | + if item_key in item_to_idx: |
| 144 | + # Update existing embedding |
| 145 | + self.E[item_to_idx[item_key]] = embedding |
| 146 | + else: |
| 147 | + # Add new embedding |
| 148 | + self.E = np.vstack([self.E, embedding]) |
| 149 | + self.items = np.append(self.items, item) |
| 150 | + |
| 151 | + # Update commit hash |
| 152 | + self.commit_hash = self._get_current_commit() |
| 153 | + |
| 154 | + def save(self, save_path: Optional[str] = None) -> None: |
| 155 | + """Save the index to disk.""" |
| 156 | + if self.E is None or self.items is None: |
| 157 | + msg = "No embeddings to save. Call create() first." |
| 158 | + raise ValueError(msg) |
| 159 | + |
| 160 | + save_path = Path(save_path) if save_path else self._get_default_save_path() |
| 161 | + save_path.parent.mkdir(parents=True, exist_ok=True) |
| 162 | + |
| 163 | + self._save_index(save_path) |
| 164 | + |
| 165 | + def load(self, load_path: Optional[str] = None) -> None: |
| 166 | + """Load the index from disk.""" |
| 167 | + load_path = Path(load_path) if load_path else self._get_default_save_path() |
| 168 | + |
| 169 | + if not load_path.exists(): |
| 170 | + msg = f"No index found at {load_path}" |
| 171 | + raise FileNotFoundError(msg) |
| 172 | + |
| 173 | + self._load_index(load_path) |
| 174 | + |
| 175 | + @abstractmethod |
| 176 | + def _save_index(self, path: Path) -> None: |
| 177 | + """Save index data to disk.""" |
| 178 | + pass |
| 179 | + |
| 180 | + @abstractmethod |
| 181 | + def _load_index(self, path: Path) -> None: |
| 182 | + """Load index data from disk.""" |
| 183 | + pass |
| 184 | + |
| 185 | + def _similarity_search_raw(self, query: str, k: int = 5) -> list[tuple[str, float]]: |
| 186 | + """Internal method to find the k most similar items by their string identifiers. |
| 187 | +
|
| 188 | + Args: |
| 189 | + query: The text to search for |
| 190 | + k: Number of results to return |
| 191 | +
|
| 192 | + Returns: |
| 193 | + List of tuples (item_identifier, similarity_score) sorted by similarity |
| 194 | + """ |
| 195 | + if self.E is None or self.items is None: |
| 196 | + msg = "No embeddings available. Call create() or load() first." |
| 197 | + raise ValueError(msg) |
| 198 | + |
| 199 | + # Get query embedding |
| 200 | + query_embeddings = self._get_embeddings([query]) |
| 201 | + query_embedding = query_embeddings[0] |
| 202 | + |
| 203 | + # Compute cosine similarity |
| 204 | + query_norm = query_embedding / np.linalg.norm(query_embedding) |
| 205 | + E_norm = self.E / np.linalg.norm(self.E, axis=1)[:, np.newaxis] |
| 206 | + similarities = np.dot(E_norm, query_norm) |
| 207 | + |
| 208 | + # Get top k indices |
| 209 | + top_indices = np.argsort(similarities)[-k:][::-1] |
| 210 | + |
| 211 | + # Return items and similarity scores |
| 212 | + return [(str(self.items[idx]), float(similarities[idx])) for idx in top_indices] |
| 213 | + |
| 214 | + @abstractmethod |
| 215 | + def similarity_search(self, query: str, k: int = 5) -> list[tuple[T, float]]: |
| 216 | + """Find the k most similar items to a query. |
| 217 | +
|
| 218 | + Args: |
| 219 | + query: The text to search for |
| 220 | + k: Number of results to return |
| 221 | +
|
| 222 | + Returns: |
| 223 | + List of tuples (item, similarity_score) sorted by similarity |
| 224 | + """ |
| 225 | + pass |
0 commit comments