File size: 11,727 Bytes
9108a9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import re
from typing import List, Dict, Any, Optional
import pickle
from tqdm import tqdm

from sentence_transformers import SentenceTransformer

class DocumentChunker:
    def __init__(self, input_dir: str = "data/raw", 
                 output_dir: str = "data/processed",
                 embedding_dir: str = "data/embeddings",
                 model_name: str = "BAAI/bge-small-en-v1.5"):
        self.input_dir = input_dir
        self.output_dir = output_dir
        self.embedding_dir = embedding_dir
        
        # Create output directories
        os.makedirs(output_dir, exist_ok=True)
        os.makedirs(embedding_dir, exist_ok=True)
        
        # Load embedding model
        self.model = SentenceTransformer(model_name)
    
    def load_documents(self) -> List[Dict[str, Any]]:
        """Load all documents from the input directory."""
        documents = []
        
        for filename in os.listdir(self.input_dir):
            if filename.endswith('.json'):
                filepath = os.path.join(self.input_dir, filename)
                with open(filepath, 'r') as f:
                    document = json.load(f)
                    documents.append(document)
        
        return documents
    
    def chunk_by_headings(self, document: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Split document into chunks based on headings."""
        chunks = []
        
        # If no headings, just create a single chunk
        if not document.get('headings'):
            chunk = {
                'title': document['title'],
                'content': document['content'],
                'url': document['url'],
                'categories': document.get('categories', []),
                'scraped_at': document['scraped_at'],
                'document_type': document.get('document_type', 'webpage')
            }
            chunks.append(chunk)
            return chunks
            
        # Process document based on headings
        headings = sorted(document['headings'], key=lambda h: h.get('level', 6))
        content = document['content']
        
        # Use headings to split content
        current_title = document['title']
        current_content = ""
        content_lines = content.split('\n')
        line_index = 0
        
        for heading in headings:
            heading_text = heading['text']
            
            # Find the heading in the content
            heading_found = False
            for i in range(line_index, len(content_lines)):
                if heading_text in content_lines[i]:
                    # Save the previous chunk
                    if current_content.strip():
                        chunk = {
                            'title': current_title,
                            'content': current_content.strip(),
                            'url': document['url'],
                            'categories': document.get('categories', []),
                            'scraped_at': document['scraped_at'],
                            'document_type': document.get('document_type', 'webpage')
                        }
                        chunks.append(chunk)
                    
                    # Start new chunk
                    current_title = heading_text
                    current_content = ""
                    line_index = i + 1
                    heading_found = True
                    break
            
            if not heading_found:
                current_content += heading_text + "\n"
                
            # Add content until the next heading
            if line_index < len(content_lines):
                for i in range(line_index, len(content_lines)):
                    # Check if line contains any of the upcoming headings
                    if any(h['text'] in content_lines[i] for h in headings if h['text'] != heading_text):
                        break
                    current_content += content_lines[i] + "\n"
                    line_index = i + 1
        
        # Add the last chunk
        if current_content.strip():
            chunk = {
                'title': current_title,
                'content': current_content.strip(),
                'url': document['url'],
                'categories': document.get('categories', []),
                'scraped_at': document['scraped_at'],
                'document_type': document.get('document_type', 'webpage')
            }
            chunks.append(chunk)
        
        return chunks
    
    def chunk_faqs(self, document: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Extract FAQs as individual chunks."""
        chunks = []
        
        if not document.get('faqs'):
            return chunks
        
        for faq in document['faqs']:
            chunk = {
                'title': faq['question'],
                'content': faq['answer'],
                'url': document['url'],
                'categories': document.get('categories', []),
                'scraped_at': document['scraped_at'],
                'document_type': 'faq',
                'question': faq['question']
            }
            chunks.append(chunk)
        
        return chunks
    
    def chunk_semantically(self, document: Dict[str, Any], 
                          max_chunk_size: int = 1000,
                          overlap: int = 100) -> List[Dict[str, Any]]:
        """Split document into fixed-size chunks with overlap."""
        chunks = []
        content = document['content']
        
        # Skip empty content
        if not content.strip():
            return chunks
        
        # Split content by paragraphs
        paragraphs = re.split(r'\n\s*\n', content)
        
        current_chunk = ""
        current_length = 0
        
        for para in paragraphs:
            para = para.strip()
            if not para:
                continue
                
            para_length = len(para)
            
            # If paragraph alone exceeds max size, split by sentences
            if para_length > max_chunk_size:
                sentences = re.split(r'(?<=[.!?])\s+', para)
                for sentence in sentences:
                    sentence = sentence.strip()
                    sentence_length = len(sentence)
                    
                    if current_length + sentence_length <= max_chunk_size:
                        current_chunk += sentence + " "
                        current_length += sentence_length + 1
                    else:
                        # Save current chunk
                        if current_chunk:
                            chunk = {
                                'title': document['title'],
                                'content': current_chunk.strip(),
                                'url': document['url'],
                                'categories': document.get('categories', []),
                                'scraped_at': document['scraped_at'],
                                'document_type': document.get('document_type', 'webpage')
                            }
                            chunks.append(chunk)
                        
                        # Start new chunk
                        current_chunk = sentence + " "
                        current_length = sentence_length + 1
            
            # Paragraph fits within limit
            elif current_length + para_length <= max_chunk_size:
                current_chunk += para + "\n\n"
                current_length += para_length + 2
            
            # Paragraph doesn't fit, create a new chunk
            else:
                # Save current chunk
                if current_chunk:
                    chunk = {
                        'title': document['title'],
                        'content': current_chunk.strip(),
                        'url': document['url'],
                        'categories': document.get('categories', []),
                        'scraped_at': document['scraped_at'],
                        'document_type': document.get('document_type', 'webpage')
                    }
                    chunks.append(chunk)
                
                # Start new chunk
                current_chunk = para + "\n\n"
                current_length = para_length + 2
        
        # Add the last chunk
        if current_chunk:
            chunk = {
                'title': document['title'],
                'content': current_chunk.strip(),
                'url': document['url'],
                'categories': document.get('categories', []),
                'scraped_at': document['scraped_at'],
                'document_type': document.get('document_type', 'webpage')
            }
            chunks.append(chunk)
        
        return chunks
    
    def create_chunks(self) -> List[Dict[str, Any]]:
        """Process all documents and create chunks."""
        all_chunks = []
        
        # Load documents
        documents = self.load_documents()
        print(f"Loaded {len(documents)} documents")
        
        # Process each document
        for document in tqdm(documents, desc="Chunking documents"):
            # FAQ chunks
            faq_chunks = self.chunk_faqs(document)
            all_chunks.extend(faq_chunks)
            
            # Heading-based chunks
            heading_chunks = self.chunk_by_headings(document)
            all_chunks.extend(heading_chunks)
            
            # Semantic chunks as fallback
            if not heading_chunks:
                semantic_chunks = self.chunk_semantically(document)
                all_chunks.extend(semantic_chunks)
        
        # Save chunks to output directory
        with open(os.path.join(self.output_dir, 'chunks.json'), 'w') as f:
            json.dump(all_chunks, f, indent=2)
        
        print(f"Created {len(all_chunks)} chunks")
        return all_chunks
    
    def create_embeddings(self, chunks: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
        """Create embeddings for all chunks."""
        if chunks is None:
            # Load chunks if not provided
            chunks_path = os.path.join(self.output_dir, 'chunks.json')
            if os.path.exists(chunks_path):
                with open(chunks_path, 'r') as f:
                    chunks = json.load(f)
            else:
                chunks = self.create_chunks()
        
        # Prepare texts for embedding
        texts = []
        for chunk in chunks:
            # For FAQs, combine question and answer
            if chunk.get('document_type') == 'faq':
                text = f"{chunk['title']} {chunk['content']}"
            else:
                # For regular chunks, use title and content
                text = f"{chunk['title']} {chunk['content']}"
            texts.append(text)
        
        # Create embeddings
        print("Creating embeddings...")
        embeddings = self.model.encode(texts, show_progress_bar=True)
        
        # Create mapping of chunk ID to embedding
        embedding_map = {}
        for i, chunk in enumerate(chunks):
            chunk_id = f"chunk_{i}"
            embedding_map[chunk_id] = {
                'embedding': embeddings[i],
                'chunk': chunk
            }
        
        # Save embeddings
        with open(os.path.join(self.embedding_dir, 'embeddings.pkl'), 'wb') as f:
            pickle.dump(embedding_map, f)
        
        print(f"Created embeddings for {len(chunks)} chunks")
        return embedding_map

# Example usage
if __name__ == "__main__":
    chunker = DocumentChunker()
    chunks = chunker.create_chunks()
    embedding_map = chunker.create_embeddings(chunks)