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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
"""
Advanced Vector Database for Document Storage and Retrieval
Handles document embeddings, similarity search, and metadata management
"""

import os
import json
import logging
import hashlib
import uuid
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass, asdict
from pathlib import Path
import numpy as np

# Vector database and embedding libraries
import chromadb
from chromadb.config import Settings
from sentence_transformers import SentenceTransformer

# Optional LangChain imports with error handling
try:
    from langchain_huggingface import HuggingFaceEmbeddings
    from langchain_chroma import Chroma
    from langchain.retrievers import ContextualCompressionRetriever
    from langchain.retrievers.document_compressors import LLMChainExtractor
    LANGCHAIN_AVAILABLE = True
except ImportError as e:
    print(f"⚠️  LangChain components not available: {e}")
    print("   Basic functionality will work without LangChain features")
    LANGCHAIN_AVAILABLE = False

# Disable ChromaDB telemetry
os.environ["ANONYMIZED_TELEMETRY"] = "False"

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class SearchResult:
    """Represents a search result with metadata"""
    chunk_id: str
    content: str
    source_file: str
    similarity_score: float
    metadata: Dict[str, Any]
    section_type: Optional[str] = None
    table_data: Optional[Dict[str, Any]] = None

class VectorDatabase:
    """Advanced vector database with GPU optimization and hybrid search"""
    
    def __init__(self, 
                 embedding_model: str = "all-MiniLM-L6-v2",
                 collection_name: str = "documents",
                 persist_directory: str = "./vector_db",
                 use_gpu: bool = True):
        
        self.embedding_model = embedding_model
        self.collection_name = collection_name
        self.persist_directory = persist_directory
        self.use_gpu = use_gpu
        
        # Initialize embedding model
        self._initialize_embeddings()
        
        # Initialize ChromaDB
        self._initialize_chromadb()
        
        # Initialize LangChain components
        self._initialize_langchain()
        
        logger.info(f"Vector database initialized with model: {embedding_model}")
    
    def _initialize_embeddings(self):
        """Initialize the embedding model"""
        try:
            # Use GPU if available and requested
            device = "cuda" if self.use_gpu and self._check_gpu_availability() else "cpu"
            
            self.embedder = SentenceTransformer(self.embedding_model, device=device)
            
            # Initialize LangChain embeddings if available
            if LANGCHAIN_AVAILABLE:
                self.langchain_embeddings = HuggingFaceEmbeddings(
                    model_name=self.embedding_model,
                    model_kwargs={'device': device}
                )
            else:
                self.langchain_embeddings = None
            
            logger.info(f"Embedding model loaded on device: {device}")
            
        except Exception as e:
            logger.error(f"Error initializing embedding model: {e}")
            raise
    
    def _check_gpu_availability(self) -> bool:
        """Check if GPU is available"""
        try:
            import torch
            return torch.cuda.is_available()
        except ImportError:
            return False
    
    def _initialize_chromadb(self):
        """Initialize ChromaDB client and collection"""
        try:
            # Create persist directory
            os.makedirs(self.persist_directory, exist_ok=True)
            
            # Initialize ChromaDB client
            self.chroma_client = chromadb.PersistentClient(
                path=self.persist_directory,
                settings=Settings(
                    anonymized_telemetry=False,
                    allow_reset=True
                )
            )
            
            # Get or create collection
            self.collection = self.chroma_client.get_or_create_collection(
                name=self.collection_name,
                metadata={"hnsw:space": "cosine"}
            )
            
            logger.info(f"ChromaDB collection '{self.collection_name}' initialized")
            
        except Exception as e:
            logger.error(f"Error initializing ChromaDB: {e}")
            raise
    
    def _initialize_langchain(self):
        """Initialize LangChain components for advanced retrieval"""
        if not LANGCHAIN_AVAILABLE:
            logger.warning("LangChain components not available - advanced features disabled")
            self.langchain_chroma = None
            self.contextual_retriever = None
            return
        
        try:
            # Initialize LangChain Chroma
            self.langchain_chroma = Chroma(
                client=self.chroma_client,
                collection_name=self.collection_name,
                embedding_function=self.langchain_embeddings
            )
            
            # Initialize contextual compression retriever
            self.contextual_retriever = ContextualCompressionRetriever(
                base_retriever=self.langchain_chroma.as_retriever(
                    search_type="similarity",
                    search_kwargs={"k": 10}
                ),
                base_compressor=LLMChainExtractor.from_llm(
                    llm=None,  # Will be set later
                    prompt_template="Extract the most relevant information from the following text: {text}"
                )
            )
            
            logger.info("LangChain components initialized")
            
        except Exception as e:
            logger.error(f"Error initializing LangChain components: {e}")
            # Continue without LangChain components if they fail
            self.langchain_chroma = None
            self.contextual_retriever = None
    
    def add_documents(self, chunks: List[Any]) -> bool:
        """Add document chunks to the vector database"""
        try:
            if not chunks:
                logger.warning("No chunks to add")
                return False
            
            # Prepare data for ChromaDB
            ids = []
            texts = []
            metadatas = []
            embeddings = []
            
            for chunk in chunks:
                # Generate unique ID
                chunk_id = chunk.chunk_id if hasattr(chunk, 'chunk_id') else str(uuid.uuid4())
                
                # Get content
                content = chunk.content if hasattr(chunk, 'content') else str(chunk)
                
                # Create metadata (filter out None values)
                metadata = {
                    'source_file': getattr(chunk, 'source_file', 'unknown'),
                    'file_type': getattr(chunk, 'file_type', 'unknown'),
                    'section_type': getattr(chunk, 'section_type', 'text'),
                    'chunk_index': getattr(chunk, 'chunk_index', 0),
                    'confidence_score': getattr(chunk, 'confidence_score', 1.0),
                    'timestamp': datetime.now().isoformat()
                }
                
                # Add page_number only if it's not None
                page_number = getattr(chunk, 'page_number', None)
                if page_number is not None:
                    metadata['page_number'] = page_number
                
                # Add table data if present
                if hasattr(chunk, 'table_data') and chunk.table_data:
                    metadata['table_data'] = json.dumps(chunk.table_data)
                
                # Generate embedding
                embedding = self.embedder.encode(content, convert_to_tensor=False)
                
                ids.append(chunk_id)
                texts.append(content)
                metadatas.append(metadata)
                embeddings.append(embedding.tolist())
            
            # Add to ChromaDB
            self.collection.add(
                ids=ids,
                documents=texts,
                metadatas=metadatas,
                embeddings=embeddings
            )
            
            logger.info(f"Successfully added {len(chunks)} chunks to vector database")
            return True
            
        except Exception as e:
            logger.error(f"Error adding documents to vector database: {e}")
            return False
    
    def add_document(self, content: str, metadata: Dict[str, Any]) -> bool:
        """Add a single document to the vector database"""
        try:
            # Generate unique ID
            chunk_id = str(uuid.uuid4())
            
            # Create metadata with defaults
            doc_metadata = {
                'source_file': metadata.get('source_file', 'unknown'),
                'file_type': metadata.get('file_type', 'unknown'),
                'section_type': metadata.get('section_type', 'text'),
                'chunk_index': metadata.get('chunk_index', 0),
                'confidence_score': metadata.get('confidence_score', 1.0),
                'timestamp': datetime.now().isoformat()
            }
            
            # Add additional metadata
            for key, value in metadata.items():
                if key not in doc_metadata and value is not None:
                    doc_metadata[key] = value
            
            # Generate embedding
            embedding = self.embedder.encode(content, convert_to_tensor=False)
            
            # Add to ChromaDB
            self.collection.add(
                ids=[chunk_id],
                documents=[content],
                metadatas=[doc_metadata],
                embeddings=[embedding.tolist()]
            )
            
            logger.info(f"Successfully added document to vector database")
            return True
            
        except Exception as e:
            logger.error(f"Error adding document to vector database: {e}")
            return False
    
    def search_documents(self, query: str, n_results: int = 5, similarity_threshold: float = 0.7) -> List[Dict[str, Any]]:
        """Search for documents and return as dictionary format for compatibility"""
        try:
            search_results = self.search_similar(query, n_results, similarity_threshold)
            
            # Convert to dictionary format
            results = []
            for result in search_results:
                results.append({
                    'content': result.content,
                    'source_file': result.source_file,
                    'similarity_score': result.similarity_score,
                    'metadata': result.metadata,
                    'section_type': result.section_type,
                    'table_data': result.table_data
                })
            
            return results
            
        except Exception as e:
            logger.error(f"Error searching documents: {e}")
            return []
    
    def search_similar(self, 
                      query: str, 
                      n_results: int = 5, 
                      similarity_threshold: float = 0.7,
                      filter_metadata: Optional[Dict[str, Any]] = None) -> List[SearchResult]:
        """Search for similar documents using semantic similarity"""
        try:
            # Generate query embedding
            query_embedding = self.embedder.encode(query, convert_to_tensor=False)
            
            # Prepare where clause for filtering
            where_clause = None
            if filter_metadata:
                where_clause = filter_metadata
            
            # Search in ChromaDB
            results = self.collection.query(
                query_embeddings=[query_embedding.tolist()],
                n_results=n_results,
                where=where_clause,
                include=['documents', 'metadatas', 'distances']
            )
            
            # Process results
            search_results = []
            for i in range(len(results['ids'][0])):
                chunk_id = results['ids'][0][i]
                content = results['documents'][0][i]
                metadata = results['metadatas'][0][i]
                distance = results['distances'][0][i]
                
                # Convert distance to similarity score
                similarity_score = 1 - distance
                
                # Filter by similarity threshold
                if similarity_score >= similarity_threshold:
                    # Parse table data if present
                    table_data = None
                    if 'table_data' in metadata and metadata['table_data']:
                        try:
                            table_data = json.loads(metadata['table_data'])
                        except:
                            pass
                    
                    result = SearchResult(
                        chunk_id=chunk_id,
                        content=content,
                        source_file=metadata.get('source_file', 'unknown'),
                        similarity_score=similarity_score,
                        metadata=metadata,
                        section_type=metadata.get('section_type', 'text'),
                        table_data=table_data
                    )
                    search_results.append(result)
            
            # Sort by similarity score
            search_results.sort(key=lambda x: x.similarity_score, reverse=True)
            
            logger.info(f"Found {len(search_results)} similar documents for query")
            return search_results
            
        except Exception as e:
            logger.error(f"Error searching vector database: {e}")
            return []
    
    def hybrid_search(self, 
                     query: str, 
                     n_results: int = 5,
                     semantic_weight: float = 0.7,
                     keyword_weight: float = 0.3) -> List[SearchResult]:
        """Perform hybrid search combining semantic and keyword matching"""
        try:
            # Semantic search
            semantic_results = self.search_similar(query, n_results=n_results*2)
            
            # Keyword search (simple implementation)
            keyword_results = self._keyword_search(query, n_results=n_results*2)
            
            # Combine and rank results
            combined_results = self._combine_search_results(
                semantic_results, 
                keyword_results, 
                semantic_weight, 
                keyword_weight
            )
            
            # Return top results
            return combined_results[:n_results]
            
        except Exception as e:
            logger.error(f"Error in hybrid search: {e}")
            return self.search_similar(query, n_results)
    
    def _keyword_search(self, query: str, n_results: int = 5) -> List[SearchResult]:
        """Simple keyword-based search"""
        try:
            # Get all documents
            all_results = self.collection.get()
            
            keyword_results = []
            query_terms = query.lower().split()
            
            for i, content in enumerate(all_results['documents']):
                content_lower = content.lower()
                
                # Calculate keyword match score
                matches = sum(1 for term in query_terms if term in content_lower)
                if matches > 0:
                    score = matches / len(query_terms)
                    
                    result = SearchResult(
                        chunk_id=all_results['ids'][i],
                        content=content,
                        source_file=all_results['metadatas'][i].get('source_file', 'unknown'),
                        similarity_score=score,
                        metadata=all_results['metadatas'][i],
                        section_type=all_results['metadatas'][i].get('section_type', 'text')
                    )
                    keyword_results.append(result)
            
            # Sort by score
            keyword_results.sort(key=lambda x: x.similarity_score, reverse=True)
            return keyword_results[:n_results]
            
        except Exception as e:
            logger.error(f"Error in keyword search: {e}")
            return []
    
    def _combine_search_results(self, 
                              semantic_results: List[SearchResult],
                              keyword_results: List[SearchResult],
                              semantic_weight: float,
                              keyword_weight: float) -> List[SearchResult]:
        """Combine semantic and keyword search results"""
        try:
            # Create a dictionary to store combined scores
            combined_scores = {}
            
            # Add semantic results
            for result in semantic_results:
                combined_scores[result.chunk_id] = {
                    'result': result,
                    'semantic_score': result.similarity_score,
                    'keyword_score': 0.0
                }
            
            # Add keyword results
            for result in keyword_results:
                if result.chunk_id in combined_scores:
                    combined_scores[result.chunk_id]['keyword_score'] = result.similarity_score
                else:
                    combined_scores[result.chunk_id] = {
                        'result': result,
                        'semantic_score': 0.0,
                        'keyword_score': result.similarity_score
                    }
            
            # Calculate combined scores
            combined_results = []
            for chunk_id, scores in combined_scores.items():
                combined_score = (scores['semantic_score'] * semantic_weight + 
                               scores['keyword_score'] * keyword_weight)
                
                # Update the result with combined score
                result = scores['result']
                result.similarity_score = combined_score
                combined_results.append(result)
            
            # Sort by combined score
            combined_results.sort(key=lambda x: x.similarity_score, reverse=True)
            return combined_results
            
        except Exception as e:
            logger.error(f"Error combining search results: {e}")
            return semantic_results
    
    def get_document_statistics(self) -> Dict[str, Any]:
        """Get statistics about the vector database"""
        try:
            # Get collection info
            count = self.collection.count()
            
            # Get unique sources
            all_results = self.collection.get()
            sources = set()
            file_types = set()
            section_types = set()
            
            for metadata in all_results['metadatas']:
                sources.add(metadata.get('source_file', 'unknown'))
                file_types.add(metadata.get('file_type', 'unknown'))
                section_types.add(metadata.get('section_type', 'text'))
            
            stats = {
                'total_chunks': count,
                'unique_sources': len(sources),
                'file_types': list(file_types),
                'section_types': list(section_types),
                'sources': list(sources),
                'embedding_model': self.embedding_model,
                'collection_name': self.collection_name
            }
            
            return stats
            
        except Exception as e:
            logger.error(f"Error getting document statistics: {e}")
            return {}
    
    def delete_documents(self, source_file: str) -> bool:
        """Delete all documents from a specific source file"""
        try:
            # Get documents from the source
            results = self.collection.get(
                where={"source_file": source_file}
            )
            
            if results['ids']:
                # Delete the documents
                self.collection.delete(ids=results['ids'])
                logger.info(f"Deleted {len(results['ids'])} chunks from {source_file}")
                return True
            else:
                logger.warning(f"No documents found for source: {source_file}")
                return False
                
        except Exception as e:
            logger.error(f"Error deleting documents: {e}")
            return False
    
    def clear_database(self) -> bool:
        """Clear all documents from the database"""
        try:
            self.collection.delete(where={})
            logger.info("Cleared all documents from vector database")
            return True
        except Exception as e:
            logger.error(f"Error clearing database: {e}")
            return False
    
    def export_database(self, export_path: str) -> bool:
        """Export database statistics and metadata"""
        try:
            stats = self.get_document_statistics()
            
            with open(export_path, 'w') as f:
                json.dump(stats, f, indent=2)
            
            logger.info(f"Database exported to: {export_path}")
            return True
            
        except Exception as e:
            logger.error(f"Error exporting database: {e}")
            return False

# Example usage
if __name__ == "__main__":
    # Initialize vector database
    vector_db = VectorDatabase(use_gpu=True)
    
    # Test search
    results = vector_db.search_similar("insurance policy coverage", n_results=3)
    
    print(f"Found {len(results)} results:")
    for i, result in enumerate(results):
        print(f"\nResult {i+1}:")
        print(f"Score: {result.similarity_score:.3f}")
        print(f"Source: {result.source_file}")
        print(f"Content: {result.content[:100]}...")
    
    # Get statistics
    stats = vector_db.get_document_statistics()
    print(f"\nDatabase statistics: {stats}")