File size: 15,250 Bytes
0a4529c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# DEPENDENCIES
import re
from typing import List
from typing import Optional
from config.models import DocumentChunk
from config.settings import get_settings
from config.models import DocumentMetadata
from config.models import ChunkingStrategy
from config.logging_config import get_logger
from chunking.base_chunker import BaseChunker
from chunking.base_chunker import ChunkerConfig
from chunking.token_counter import TokenCounter
from chunking.overlap_manager import OverlapManager


# Setup Settings and Logging
logger   = get_logger(__name__)
settings = get_settings()


class FixedChunker(BaseChunker):
    """
    Fixed-size chunking strategy : Splits text into chunks of approximately equal token count with overlap
    
    Best for:
    - Small to medium documents (<50K tokens)
    - Homogeneous content
    - When simplicity is preferred
    """
    def __init__(self, chunk_size: int = None, overlap: int = None, respect_sentence_boundaries: bool = True, min_chunk_size: int = 100):
        """
        Initialize fixed chunker
        
        Arguments:
        ----------
            chunk_size                  { int }  : Target tokens per chunk (default from settings)
            
            overlap                     { int }  : Overlap tokens between chunks (default from settings)
            
            respect_sentence_boundaries { bool } : Try to break at sentence boundaries
            
            min_chunk_size              { int }  : Minimum chunk size in tokens
        """
        super().__init__(ChunkingStrategy.FIXED)
        
        self.chunk_size                  = chunk_size or settings.FIXED_CHUNK_SIZE
        self.overlap                     = overlap or settings.FIXED_CHUNK_OVERLAP
        self.respect_sentence_boundaries = respect_sentence_boundaries
        self.min_chunk_size              = min_chunk_size
        
        # Initialize token counter and overlap manager
        self.token_counter               = TokenCounter()
        self.overlap_manager             = OverlapManager(overlap_tokens = self.overlap)
        
        # Validate parameters
        if (self.overlap >= self.chunk_size):
            raise ValueError(f"Overlap ({self.overlap}) must be less than chunk_size ({self.chunk_size})")
        
        self.logger.info(f"Initialized FixedChunker: chunk_size={self.chunk_size}, overlap={self.overlap}, respect_boundaries={self.respect_sentence_boundaries}")
    

    def chunk_text(self, text: str, metadata: Optional[DocumentMetadata] = None) -> List[DocumentChunk]:
        """
        Chunk text into fixed-size pieces
        
        Arguments:
        ----------
            text            { str }       : Input text

            metadata { DocumentMetaData } : Document metadata
        
        Returns:
        --------
                     { list }             : List of DocumentChunk objects
        """
        if not text or not text.strip():
            return []
        
        document_id = metadata.document_id if metadata else "unknown"
        
        # Split into sentences if respecting boundaries
        if self.respect_sentence_boundaries:
            chunks = self._chunk_with_sentence_boundaries(text        = text, 
                                                          document_id = document_id,
                                                         )
        
        else:
            chunks = self._chunk_without_boundaries(text        = text, 
                                                    document_id = document_id,
                                                   )
        
        # Clean and validate
        chunks = [c for c in chunks if (c.token_count >= self.min_chunk_size)]
        
        # Use OverlapManager to add proper overlap
        if ((len(chunks) > 1) and (self.overlap > 0)):
            chunks = self.overlap_manager.add_overlap(chunks         = chunks, 
                                                      overlap_tokens = self.overlap,
                                                     )
        
        self.logger.debug(f"Created {len(chunks)} fixed-size chunks")
        
        return chunks
    

    def _chunk_with_sentence_boundaries(self, text: str, document_id: str) -> List[DocumentChunk]:
        """
        Chunk text respecting sentence boundaries
        
        Arguments:
        ----------
            text        { str } : Input text

            document_id { str } : Document ID
        
        Returns:
        --------
                { list }        : List of chunks without overlap (overlap added later)
        """
        # Split into sentences
        sentences         = self._split_sentences(text = text)
        
        chunks            = list()
        current_sentences = list()
        current_tokens    = 0
        start_char        = 0
        
        for sentence in sentences:
            sentence_tokens = self.token_counter.count_tokens(text = sentence)
            
            # If single sentence exceeds chunk_size, split it
            if (sentence_tokens > self.chunk_size):
                # Save current chunk if any
                if current_sentences:
                    chunk_text        = " ".join(current_sentences)
                    chunk             = self._create_chunk(text        = self._clean_chunk_text(chunk_text),
                                                           chunk_index = len(chunks),
                                                           document_id = document_id,
                                                           start_char  = start_char,
                                                           end_char    = start_char + len(chunk_text),
                                                          )
                    chunks.append(chunk)

                    current_sentences = list()
                    current_tokens    = 0
                    start_char       += len(chunk_text)
                
                # Split long sentence and add as separate chunks
                long_sentence_chunks = self._split_long_sentence(sentence    = sentence,
                                                                 document_id = document_id,
                                                                 start_index = len(chunks),
                                                                 start_char  = start_char,
                                                                )
                chunks.extend(long_sentence_chunks)
                start_char          += len(sentence)
                
                continue
            
            # Check if adding this sentence exceeds chunk_size
            if (((current_tokens + sentence_tokens) > self.chunk_size) and current_sentences):
                # Save current chunk WITHOUT overlap (overlap added later)
                chunk_text = " ".join(current_sentences)
                chunk      = self._create_chunk(text        = self._clean_chunk_text(chunk_text),
                                                chunk_index = len(chunks),
                                                document_id = document_id,
                                                start_char  = start_char,
                                                end_char    = start_char + len(chunk_text),
                                               )
                chunks.append(chunk)
                
                # OverlapManager will handle the overlap here
                current_sentences = [sentence]
                current_tokens    = sentence_tokens
                start_char       += len(chunk_text)

            else:
                # Add sentence to current chunk
                current_sentences.append(sentence)
                current_tokens += sentence_tokens
        
        # Add final chunk
        if current_sentences:
            chunk_text = " ".join(current_sentences)
            chunk      = self._create_chunk(text        = self._clean_chunk_text(chunk_text),
                                            chunk_index = len(chunks),
                                            document_id = document_id,
                                            start_char  = start_char,
                                            end_char    = start_char + len(chunk_text),
                                           )
            chunks.append(chunk)
        
        return chunks
    

    def _chunk_without_boundaries(self, text: str, document_id: str) -> List[DocumentChunk]:
        """
        Chunk text without respecting boundaries (pure token-based)
        
        Arguments:
        ----------
            text        { str } : Input text

            document_id { str } : Document ID
        
        Returns:
        --------
                  { list }      : List of chunks WITHOUT overlap
        """
        # Use token counter's split method
        chunk_texts = self.token_counter.split_into_token_chunks(text,
                                                                 chunk_size = self.chunk_size,
                                                                 overlap    = 0,
                                                                )
        
        chunks      = list()
        current_pos = 0
        
        for i, chunk_text in enumerate(chunk_texts):
            chunk        = self._create_chunk(text        = self._clean_chunk_text(chunk_text),
                                              chunk_index = i,
                                              document_id = document_id,
                                              start_char  = current_pos,
                                              end_char    = current_pos + len(chunk_text),
                                             )

            chunks.append(chunk)
            current_pos += len(chunk_text)
        
        return chunks
    

    def _split_sentences(self, text: str) -> List[str]:
        """
        Split text into sentences
        
        Arguments:
        ----------
            text { str } : Input text
        
        Returns:
        --------
            { list }     : List of sentences
        """
        # Handle common abbreviations: Protect them temporarily
        protected     = text
        abbreviations = ['Dr.', 'Mr.', 'Mrs.', 'Ms.', 'Jr.', 'Sr.', 'Prof.', 'Inc.', 'Ltd.', 'Corp.', 'Co.', 'vs.', 'etc.', 'e.g.', 'i.e.', 'Ph.D.', 'M.D.', 'B.A.', 'M.A.', 'U.S.', 'U.K.']
        
        for abbr in abbreviations:
            protected = protected.replace(abbr, abbr.replace('.', '<DOT>'))
        
        # Split on sentence boundaries
        # - Pattern: period/question/exclamation followed by space and capital letter
        sentence_pattern = r'(?<=[.!?])\s+(?=[A-Z])'
        sentences        = re.split(sentence_pattern, protected)
        
        # Restore abbreviations
        sentences        = [s.replace('<DOT>', '.').strip() for s in sentences]
        
        # Filter empty
        sentences        = [s for s in sentences if s]
        
        return sentences

    
    def _split_long_sentence(self, sentence: str, document_id: str, start_index: int, start_char: int) -> List[DocumentChunk]:
        """
        Split a sentence that's longer than chunk_size
        
        Arguments:
        ----------
            sentence    { str } : Long sentence
            
            document_id { str } : Document ID
            
            start_index { str } : Starting chunk index
            
            start_char  { int } : Starting character position
        
        Returns:
        --------
                { list }        : List of chunks
        """
        # Split by commas, semicolons, or just by tokens
        parts          = re.split(r'[,;]', sentence)
        
        chunks         = list()
        current_text   = list()
        current_tokens = 0
        
        for part in parts:
            part = part.strip()
            if not part:
                continue
            
            part_tokens = self.token_counter.count_tokens(part)
            
            if (((current_tokens + part_tokens) > self.chunk_size) and current_text):
                # Save current chunk
                chunk_text     = " ".join(current_text)
                chunk          = self._create_chunk(text        = self._clean_chunk_text(chunk_text),
                                                    chunk_index = start_index + len(chunks),
                                                    document_id = document_id,
                                                    start_char  = start_char,
                                                    end_char    = start_char + len(chunk_text),
                                                   )
                chunks.append(chunk)
                start_char    += len(chunk_text)
                current_text   = []
                current_tokens = 0
            
            current_text.append(part)
            current_tokens += part_tokens
        
        # Add final part
        if current_text:
            chunk_text = " ".join(current_text)
            chunk      = self._create_chunk(text        = self._clean_chunk_text(chunk_text),
                                            chunk_index = start_index + len(chunks),
                                            document_id = document_id,
                                            start_char  = start_char,
                                            end_char    = start_char + len(chunk_text),
                                           )
            chunks.append(chunk)
        
        return chunks
    

    def _get_overlap_sentences(self, sentences: List[str], overlap_tokens: int) -> List[str]:
        """
        Get last few sentences that fit in overlap window
        
        Arguments:
        ----------
            sentences      { list } : List of sentences

            overlap_tokens { int }  : Target overlap tokens
        
        Returns:
        --------
                  { list }          : List of overlap sentences
        """
        overlap = list()
        tokens  = 0
        
        # Add sentences from the end until we reach overlap size
        for sentence in reversed(sentences):
            sentence_tokens = self.token_counter.count_tokens(sentence)
            
            if ((tokens + sentence_tokens) <= overlap_tokens):
                overlap.insert(0, sentence)
                tokens += sentence_tokens
            
            else:
                break
        
        return overlap

    
    @classmethod
    def from_config(cls, config: ChunkerConfig) -> 'FixedChunker':
        """
        Create FixedChunker from configuration
        
        Arguments:
        ----------
            config { ChunkerConfig } : ChunkerConfig object
        
        Returns:
        --------
            FixedChunker instance
        """
        return cls(chunk_size                  = config.chunk_size,
                   overlap                     = config.overlap,
                   respect_sentence_boundaries = config.respect_boundaries,
                   min_chunk_size              = config.min_chunk_size,
                  )