File size: 9,773 Bytes
e884643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""
Embedding & Vector Index Service
Handles embedding generation and FAISS vector store management
"""
# Import SentenceTransformer lazily to avoid hanging on startup
import faiss
import numpy as np
from typing import List, Dict, Any, Tuple, Optional
from loguru import logger
import pickle
import os
from models import Chunk, EmbeddingEntry
from config import settings
import json


class EmbeddingService:
    """
    Service for creating embeddings and managing FAISS vector index
    Uses lazy loading for the embedding model (loads on first use)
    """

    def __init__(self):
        logger.info(f"EmbeddingService initialized (model will load on first use)")
        self._model = None  # Lazy-loaded
        self.dimension = settings.embedding_dimension
        self.index: Optional[faiss.Index] = None
        self.chunk_metadata: Dict[int, Dict[str, Any]] = {}  # index_id -> metadata
        self._initialize_index()

    @property
    def model(self):
        """Lazy-load the embedding model on first access"""
        if self._model is None:
            logger.info(f"Loading embedding model: {settings.embedding_model}")
            # Import only when needed to avoid hanging on startup
            from sentence_transformers import SentenceTransformer
            self._model = SentenceTransformer(settings.embedding_model)
            logger.info(f"✓ Embedding model loaded successfully")
        return self._model

    def _initialize_index(self):
        """Initialize or load FAISS index"""
        index_path = os.path.join(settings.faiss_index_path, "index.faiss")
        metadata_path = os.path.join(settings.faiss_index_path, "metadata.pkl")

        if os.path.exists(index_path) and os.path.exists(metadata_path):
            logger.info("Loading existing FAISS index")
            self.index = faiss.read_index(index_path)
            with open(metadata_path, 'rb') as f:
                self.chunk_metadata = pickle.load(f)
            logger.info(f"Loaded index with {self.index.ntotal} vectors")
        else:
            logger.info("Creating new FAISS index (optimized)")
            # Use HNSW for better performance on larger datasets
            # HNSW is ~10x faster than flat index with 99%+ accuracy
            # M=32 is good balance (higher M = more accurate but slower)
            self.index = faiss.IndexHNSWFlat(self.dimension, 32)
            # Set ef construction (higher = better quality, slower build)
            self.index.hnsw.efConstruction = 40
            # Set ef search (higher = better recall, slower search)
            self.index.hnsw.efSearch = 16
            self.chunk_metadata = {}
            logger.info("Using HNSW index for faster approximate search")

    def create_embeddings(self, chunks: List[Chunk]) -> List[EmbeddingEntry]:
        """
        ⚡ OPTIMIZED: Create embeddings with larger batches and parallel processing

        Args:
            chunks: List of Chunk objects

        Returns:
            List of EmbeddingEntry objects
        """
        texts = [chunk.text for chunk in chunks]
        logger.info(f"⚡ Creating embeddings for {len(texts)} chunks (batch_size={settings.embedding_batch_size})")

        import time
        start = time.time()

        # Batch encode with optimized settings
        embeddings = self.model.encode(
            texts,
            batch_size=settings.embedding_batch_size,
            show_progress_bar=False,  # Disable for less overhead
            convert_to_numpy=True,
            normalize_embeddings=True  # Built-in normalization is faster
        )

        elapsed = time.time() - start
        logger.info(f"✓ Created {len(embeddings)} embeddings in {elapsed:.2f}s ({len(embeddings)/elapsed:.1f} chunks/sec)")

        # Create embedding entries
        embedding_entries = []
        for chunk, embedding in zip(chunks, embeddings):
            entry = EmbeddingEntry(
                chunk_id=chunk.chunk_id,
                embedding=embedding.tolist(),
                metadata={
                    "pdf_id": chunk.pdf_id,
                    "page_number": chunk.page_number,
                    "type": chunk.type.value,
                    "char_range": chunk.char_range
                }
            )
            embedding_entries.append(entry)

        return embedding_entries

    def add_to_index(self, chunks: List[Chunk], embeddings: List[EmbeddingEntry]):
        """
        Add chunks and their embeddings to FAISS index

        Args:
            chunks: List of chunks
            embeddings: Corresponding embeddings
        """
        if len(chunks) != len(embeddings):
            raise ValueError("Chunks and embeddings must have same length")

        # Convert embeddings to numpy array
        embedding_array = np.array([e.embedding for e in embeddings]).astype('float32')

        # Get current index size (starting ID for new chunks)
        start_id = self.index.ntotal

        # Add to FAISS index
        self.index.add(embedding_array)

        # Store metadata mapping
        for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
            idx = start_id + i
            self.chunk_metadata[idx] = {
                "chunk_id": chunk.chunk_id,
                "pdf_id": chunk.pdf_id,
                "page_number": chunk.page_number,
                "type": chunk.type.value,
                "text": chunk.text,
                "char_range": chunk.char_range,
                "metadata": chunk.metadata
            }

        logger.info(f"Added {len(chunks)} chunks to index. Total: {self.index.ntotal}")

    def search(
        self,
        query: str,
        top_k: int = 10,
        filter_pdf_id: Optional[str] = None
    ) -> List[Tuple[Dict[str, Any], float]]:
        """
        Search for similar chunks

        Args:
            query: Query string
            top_k: Number of results to return
            filter_pdf_id: Optional PDF ID to filter results

        Returns:
            List of (chunk_metadata, score) tuples
        """
        # Encode and normalize query
        query_embedding = self.model.encode([query], convert_to_numpy=True)
        faiss.normalize_L2(query_embedding)

        # Search
        # Fetch more if we need to filter
        k = top_k * 10 if filter_pdf_id else top_k
        scores, indices = self.index.search(query_embedding, k)

        # Retrieve metadata
        results = []
        for score, idx in zip(scores[0], indices[0]):
            if idx == -1:  # FAISS returns -1 for empty results
                continue

            metadata = self.chunk_metadata.get(idx)
            if metadata is None:
                continue

            # Apply filter if specified
            if filter_pdf_id and metadata.get("pdf_id") != filter_pdf_id:
                continue

            results.append((metadata, float(score)))

            if len(results) >= top_k:
                break

        return results

    def search_by_chunk_ids(self, chunk_ids: List[str], top_k: int = 5) -> List[Tuple[Dict[str, Any], float]]:
        """
        Find similar chunks to a set of chunk IDs (for node expansion)

        Args:
            chunk_ids: List of chunk IDs
            top_k: Number of similar chunks per input chunk

        Returns:
            List of (chunk_metadata, score) tuples
        """
        # Find the chunks in metadata
        chunk_indices = []
        for idx, meta in self.chunk_metadata.items():
            if meta["chunk_id"] in chunk_ids:
                chunk_indices.append(idx)

        if not chunk_indices:
            return []

        # Get embeddings for these chunks
        # Note: FAISS doesn't have a direct "get vector" API for IndexFlatIP
        # We'll search from the index using reconstruct (if supported)
        results = []
        for idx in chunk_indices:
            # Reconstruct vector (works for Flat indices)
            try:
                vector = self.index.reconstruct(idx)
                vector = vector.reshape(1, -1)
                scores, indices = self.index.search(vector, top_k + 1)  # +1 to exclude self

                for score, res_idx in zip(scores[0], indices[0]):
                    if res_idx == idx:  # Skip self
                        continue
                    if res_idx == -1:
                        continue

                    metadata = self.chunk_metadata.get(res_idx)
                    if metadata:
                        results.append((metadata, float(score)))
            except Exception as e:
                logger.warning(f"Could not reconstruct vector for index {idx}: {e}")

        # Sort by score and return top
        results.sort(key=lambda x: x[1], reverse=True)
        return results[:top_k]

    def save(self):
        """Save FAISS index and metadata to disk"""
        os.makedirs(settings.faiss_index_path, exist_ok=True)

        index_path = os.path.join(settings.faiss_index_path, "index.faiss")
        metadata_path = os.path.join(settings.faiss_index_path, "metadata.pkl")

        faiss.write_index(self.index, index_path)
        with open(metadata_path, 'wb') as f:
            pickle.dump(self.chunk_metadata, f)

        logger.info(f"Saved FAISS index with {self.index.ntotal} vectors")

    def clear(self):
        """Clear the index and metadata"""
        self.index = faiss.IndexFlatIP(self.dimension)
        self.chunk_metadata = {}
        logger.info("Cleared FAISS index")

    def get_stats(self) -> Dict[str, Any]:
        """Get index statistics"""
        return {
            "total_vectors": self.index.ntotal,
            "dimension": self.dimension,
            "index_type": type(self.index).__name__,
            "num_chunks": len(self.chunk_metadata)
        }