File size: 6,861 Bytes
8f0efdf
 
f68e1d5
 
8f0efdf
 
 
f68e1d5
0be316d
8f0efdf
 
 
0be316d
f68e1d5
 
7540753
 
0be316d
7540753
 
0be316d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540753
 
 
 
 
 
 
 
 
 
8f0efdf
7540753
 
 
f68e1d5
7540753
 
f68e1d5
7540753
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f0efdf
 
0be316d
 
 
 
 
7540753
 
0be316d
 
 
 
 
 
8f0efdf
7540753
 
 
 
 
8f0efdf
7540753
 
 
 
 
 
 
8f0efdf
 
 
0be316d
 
7540753
8f0efdf
0be316d
 
 
8f0efdf
 
0be316d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540753
f68e1d5
8f0efdf
0be316d
 
 
 
 
 
 
7540753
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0be316d
7540753
 
0be316d
 
 
 
 
 
7540753
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
import os
from PyPDF2 import PdfReader
from transformers import AutoTokenizer, AutoModel
import torch
import chromadb
from typing import List, Dict
import re
import numpy as np
from pathlib import Path

class LegalDocumentProcessor:
    def __init__(self):
        print("Initializing Legal Document Processor...")
        self.tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
        self.model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
        self.max_chunk_size = 500  # Reduced chunk size
        self.max_context_length = 4000  # Maximum context length for response
        
        # Initialize ChromaDB
        self.pdf_dir = "/home/user/app"
        db_dir = os.path.join(self.pdf_dir, "chroma_db")
        os.makedirs(db_dir, exist_ok=True)
        
        print(f"Initializing ChromaDB at {db_dir}")
        self.chroma_client = chromadb.PersistentClient(path=db_dir)
        
        try:
            self.collection = self.chroma_client.get_collection("indian_legal_docs")
            print("Found existing collection")
        except:
            print("Creating new collection")
            self.collection = self.chroma_client.create_collection(
                name="indian_legal_docs",
                metadata={"description": "Indian Criminal Law Documents"}
            )
    
    def _split_into_chunks(self, text: str) -> List[str]:
        """Split text into smaller chunks while preserving context"""
        # Split on meaningful boundaries
        patterns = [
            r'(?=Chapter \d+)',
            r'(?=Section \d+)',
            r'(?=\n\d+\.\s)',  # Numbered paragraphs
            r'\n\n'
        ]
        
        # Combine patterns
        split_pattern = '|'.join(patterns)
        sections = re.split(split_pattern, text)
        
        chunks = []
        current_chunk = ""
        
        for section in sections:
            section = section.strip()
            if not section:
                continue
                
            # If section is small enough, add to current chunk
            if len(current_chunk) + len(section) < self.max_chunk_size:
                current_chunk += " " + section
            else:
                # If current chunk is not empty, add it to chunks
                if current_chunk:
                    chunks.append(current_chunk.strip())
                # Start new chunk with current section
                current_chunk = section
        
        # Add the last chunk if not empty
        if current_chunk:
            chunks.append(current_chunk.strip())
        
        return chunks
    
    def process_pdf(self, pdf_path: str) -> List[str]:
        """Extract text from PDF and split into chunks"""
        print(f"Processing PDF: {pdf_path}")
        try:
            reader = PdfReader(pdf_path)
            text = ""
            for page in reader.pages:
                text += page.extract_text() + "\n\n"
            
            chunks = self._split_into_chunks(text)
            print(f"Created {len(chunks)} chunks from {pdf_path}")
            return chunks
        except Exception as e:
            print(f"Error processing PDF {pdf_path}: {str(e)}")
            return []
    
    def get_embedding(self, text: str) -> List[float]:
        """Generate embedding for text"""
        inputs = self.tokenizer(text, padding=True, truncation=True, max_length=512, return_tensors='pt')
        with torch.no_grad():
            model_output = self.model(**inputs)
        
        # Mean pooling
        token_embeddings = model_output[0]
        attention_mask = inputs['attention_mask']
        mask = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
        sum_embeddings = torch.sum(token_embeddings * mask, 1)
        sum_mask = torch.clamp(mask.sum(1), min=1e-9)
        return (sum_embeddings / sum_mask).squeeze().tolist()
    
    def process_and_store_documents(self):
        """Process all legal documents and store in ChromaDB"""
        print("Starting document processing...")
        
        # Define the expected PDF paths
        pdf_files = {
            'BNS': os.path.join(self.pdf_dir, 'BNS.pdf'),
            'BNSS': os.path.join(self.pdf_dir, 'BNSS.pdf'),
            'BSA': os.path.join(self.pdf_dir, 'BSA.pdf')
        }
        
        for law_code, pdf_path in pdf_files.items():
            if os.path.exists(pdf_path):
                print(f"Processing {law_code} from {pdf_path}")
                chunks = self.process_pdf(pdf_path)
                
                if not chunks:
                    print(f"No chunks extracted from {pdf_path}")
                    continue
                
                for i, chunk in enumerate(chunks):
                    try:
                        embedding = self.get_embedding(chunk)
                        
                        self.collection.add(
                            documents=[chunk],
                            embeddings=[embedding],
                            metadatas=[{
                                "law_code": law_code,
                                "chunk_id": f"{law_code}_chunk_{i}",
                                "source": os.path.basename(pdf_path)
                            }],
                            ids=[f"{law_code}_chunk_{i}"]
                        )
                    except Exception as e:
                        print(f"Error processing chunk {i} from {law_code}: {str(e)}")
    
    def search_documents(self, query: str, n_results: int = 3) -> Dict:
        """Search for relevant legal information"""
        try:
            query_embedding = self.get_embedding(query)
            results = self.collection.query(
                query_embeddings=[query_embedding],
                n_results=n_results
            )
            
            # Limit context size
            documents = results["documents"][0]
            total_length = 0
            filtered_documents = []
            filtered_metadatas = []
            
            for doc, metadata in zip(documents, results["metadatas"][0]):
                doc_length = len(doc)
                if total_length + doc_length <= self.max_context_length:
                    filtered_documents.append(doc)
                    filtered_metadatas.append(metadata)
                    total_length += doc_length
                else:
                    break
            
            return {
                "documents": filtered_documents,
                "metadatas": filtered_metadatas
            }
        except Exception as e:
            print(f"Error during search: {str(e)}")
            return {
                "documents": ["Sorry, I couldn't search the documents effectively."],
                "metadatas": [{"law_code": "ERROR", "source": "error"}]
            }