|
| 1 | +""" |
| 2 | +Text chunking utilities for memory |
| 3 | +
|
| 4 | +Splits text into chunks with token limits and overlap |
| 5 | +""" |
| 6 | + |
| 7 | +from typing import List, Tuple |
| 8 | +from dataclasses import dataclass |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class TextChunk: |
| 13 | + """Represents a text chunk with line numbers""" |
| 14 | + text: str |
| 15 | + start_line: int |
| 16 | + end_line: int |
| 17 | + |
| 18 | + |
| 19 | +class TextChunker: |
| 20 | + """Chunks text by line count with token estimation""" |
| 21 | + |
| 22 | + def __init__(self, max_tokens: int = 500, overlap_tokens: int = 50): |
| 23 | + """ |
| 24 | + Initialize chunker |
| 25 | + |
| 26 | + Args: |
| 27 | + max_tokens: Maximum tokens per chunk |
| 28 | + overlap_tokens: Overlap tokens between chunks |
| 29 | + """ |
| 30 | + self.max_tokens = max_tokens |
| 31 | + self.overlap_tokens = overlap_tokens |
| 32 | + # Rough estimation: ~4 chars per token for English/Chinese mixed |
| 33 | + self.chars_per_token = 4 |
| 34 | + |
| 35 | + def chunk_text(self, text: str) -> List[TextChunk]: |
| 36 | + """ |
| 37 | + Chunk text into overlapping segments |
| 38 | + |
| 39 | + Args: |
| 40 | + text: Input text to chunk |
| 41 | + |
| 42 | + Returns: |
| 43 | + List of TextChunk objects |
| 44 | + """ |
| 45 | + if not text.strip(): |
| 46 | + return [] |
| 47 | + |
| 48 | + lines = text.split('\n') |
| 49 | + chunks = [] |
| 50 | + |
| 51 | + max_chars = self.max_tokens * self.chars_per_token |
| 52 | + overlap_chars = self.overlap_tokens * self.chars_per_token |
| 53 | + |
| 54 | + current_chunk = [] |
| 55 | + current_chars = 0 |
| 56 | + start_line = 1 |
| 57 | + |
| 58 | + for i, line in enumerate(lines, start=1): |
| 59 | + line_chars = len(line) |
| 60 | + |
| 61 | + # If single line exceeds max, split it |
| 62 | + if line_chars > max_chars: |
| 63 | + # Save current chunk if exists |
| 64 | + if current_chunk: |
| 65 | + chunks.append(TextChunk( |
| 66 | + text='\n'.join(current_chunk), |
| 67 | + start_line=start_line, |
| 68 | + end_line=i - 1 |
| 69 | + )) |
| 70 | + current_chunk = [] |
| 71 | + current_chars = 0 |
| 72 | + |
| 73 | + # Split long line into multiple chunks |
| 74 | + for sub_chunk in self._split_long_line(line, max_chars): |
| 75 | + chunks.append(TextChunk( |
| 76 | + text=sub_chunk, |
| 77 | + start_line=i, |
| 78 | + end_line=i |
| 79 | + )) |
| 80 | + |
| 81 | + start_line = i + 1 |
| 82 | + continue |
| 83 | + |
| 84 | + # Check if adding this line would exceed limit |
| 85 | + if current_chars + line_chars > max_chars and current_chunk: |
| 86 | + # Save current chunk |
| 87 | + chunks.append(TextChunk( |
| 88 | + text='\n'.join(current_chunk), |
| 89 | + start_line=start_line, |
| 90 | + end_line=i - 1 |
| 91 | + )) |
| 92 | + |
| 93 | + # Start new chunk with overlap |
| 94 | + overlap_lines = self._get_overlap_lines(current_chunk, overlap_chars) |
| 95 | + current_chunk = overlap_lines + [line] |
| 96 | + current_chars = sum(len(l) for l in current_chunk) |
| 97 | + start_line = i - len(overlap_lines) |
| 98 | + else: |
| 99 | + # Add line to current chunk |
| 100 | + current_chunk.append(line) |
| 101 | + current_chars += line_chars |
| 102 | + |
| 103 | + # Save last chunk |
| 104 | + if current_chunk: |
| 105 | + chunks.append(TextChunk( |
| 106 | + text='\n'.join(current_chunk), |
| 107 | + start_line=start_line, |
| 108 | + end_line=len(lines) |
| 109 | + )) |
| 110 | + |
| 111 | + return chunks |
| 112 | + |
| 113 | + def _split_long_line(self, line: str, max_chars: int) -> List[str]: |
| 114 | + """Split a single long line into multiple chunks""" |
| 115 | + chunks = [] |
| 116 | + for i in range(0, len(line), max_chars): |
| 117 | + chunks.append(line[i:i + max_chars]) |
| 118 | + return chunks |
| 119 | + |
| 120 | + def _get_overlap_lines(self, lines: List[str], target_chars: int) -> List[str]: |
| 121 | + """Get last few lines that fit within target_chars for overlap""" |
| 122 | + overlap = [] |
| 123 | + chars = 0 |
| 124 | + |
| 125 | + for line in reversed(lines): |
| 126 | + line_chars = len(line) |
| 127 | + if chars + line_chars > target_chars: |
| 128 | + break |
| 129 | + overlap.insert(0, line) |
| 130 | + chars += line_chars |
| 131 | + |
| 132 | + return overlap |
| 133 | + |
| 134 | + def chunk_markdown(self, text: str) -> List[TextChunk]: |
| 135 | + """ |
| 136 | + Chunk markdown text while respecting structure |
| 137 | + (For future enhancement: respect markdown sections) |
| 138 | + """ |
| 139 | + return self.chunk_text(text) |
0 commit comments