Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathchunking.py
More file actions
Latest commit
434 lines (381 loc) · 15.4 KB
/
Copy pathchunking.py
File metadata and controls
434 lines (381 loc) · 15.4 KB
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
importlogging
importos
importre
fromabcimportABC, abstractmethod
fromdataclassesimportdataclass
fromfunctoolsimportcache
fromioimportTextIOWrapper
fromtypingimportGenerator, Optional, cast
frompygments.lexerimportLexer
frompygments.lexersimportget_lexer_for_filename
frompygments.utilimportClassNotFound
fromtree_sitterimportNode, Point
fromtree_sitter_language_packimportSupportedLanguage, get_parser
fromvectorcode.cli_utilsimportConfig
logger=logging.getLogger(name=__name__)
@dataclass
classChunk:
"""
rows are 1-indexed, cols are 0-indexed.
"""
text: str
start: Point|None=None
end: Point|None=None
path: str|None=None
id: str|None=None
def__str__(self):
returnself.text
def__hash__(self) ->int:
returnhash(f"VectorCodeChunk_{self.path}({self.start}:{self.end}@{self.text})")
defexport_dict(self):
d: dict[str, str|dict[str, int]] = {"text": self.text}
ifself.startisnotNone:
d.update(
{
"start": {"row": self.start.row, "column": self.start.column},
}
)
ifself.endisnotNone:
d.update(
{
"end": {"row": self.end.row, "column": self.end.column},
}
)
ifself.path:
d["path"] =self.path
ifself.id:
d["chunk_id"] =self.id
returnd
@dataclass
classChunkOpts:
start_pos: Point
classChunkerBase(ABC): # pragma: nocover
def__init__(self, config: Optional[Config] =None) ->None:
ifconfigisNone:
config=Config()
assert0<=config.overlap_ratio<1, (
"Overlap ratio has to be a float between 0 (inclusive) and 1 (exclusive)."
)
self.config=config
@abstractmethod
defchunk(
self, data, opts: Optional[ChunkOpts] =None
) ->Generator[Chunk, None, None]:
raiseNotImplementedError
classStringChunker(ChunkerBase):
def__init__(self, config: Optional[Config] =None) ->None:
ifconfigisNone:
config=Config()
super().__init__(config)
defchunk(self, data: str, opts: Optional[ChunkOpts] =None):
start_pos=Point(row=1, column=0)
ifoptsisnotNone:
start_pos=opts.start_pos
logger.info("Started chunking with StringChunker.")
logger.debug(f"{data=}")
ifself.config.chunk_size<0:
yieldChunk(
text=data,
start=start_pos,
end=Point(
row=data.count("\n") +start_pos.row,
column=len(data.split("\n")[-1]) -1,
),
)
else:
step_size=max(
1, int(self.config.chunk_size* (1-self.config.overlap_ratio))
)
i=0
whilei<len(data):
chunk_text=data[i : i+self.config.chunk_size]
start_lines_before_chunk=data[:i].count("\n")
chunk_start_row=start_pos.row+start_lines_before_chunk
ifstart_lines_before_chunk==0:
chunk_start_column=start_pos.column+i
else:
last_newline_idx_before_i=data.rfind("\n", 0, i)
chunk_start_column=i- (last_newline_idx_before_i+1)
chunk_end_row=chunk_start_row+chunk_text.count("\n")
if"\n"inchunk_text:
chunk_end_column=len(chunk_text.split("\n")[-1]) -1
else:
chunk_end_column=chunk_start_column+len(chunk_text) -1
yieldChunk(
text=chunk_text,
start=Point(row=chunk_start_row, column=chunk_start_column),
end=Point(row=chunk_end_row, column=chunk_end_column),
)
ifi+self.config.chunk_size>=len(data):
break
i+=step_size
classFileChunker(ChunkerBase):
def__init__(self, config: Optional[Config] =None) ->None:
ifconfigisNone:
config=Config()
super().__init__(config)
defchunk(
self, data: TextIOWrapper, opts: Optional[ChunkOpts] =None
) ->Generator[Chunk, None, None]:
logger.info("Started chunking %s using FileChunker.", data.name)
lines=data.readlines()
iflen(lines) ==0: # pragma: nocover
return
if (
self.config.chunk_size<0
orsum(len(i) foriinlines) <self.config.chunk_size
):
text="".join(lines)
yieldChunk(text, Point(1, 0), Point(1, len(text) -1))
return
text="".join(lines)
step_size=max(
1, int(self.config.chunk_size* (1-self.config.overlap_ratio))
)
# Convert lines to absolute positions
line_offsets= [0]
forlineinlines:
line_offsets.append(line_offsets[-1] +len(line))
i=0
whilei<len(text):
chunk_text=text[i : i+self.config.chunk_size]
# Find start position
start_line= (
next(lnforln, offsetinenumerate(line_offsets) ifoffset>i) -1
)
start_col=i-line_offsets[start_line]
# Find end position
end_pos=i+len(chunk_text)
end_line= (
next(lnforln, offsetinenumerate(line_offsets) ifoffset>=end_pos)
-1
)
end_col=end_pos-line_offsets[end_line] -1
yieldChunk(
chunk_text,
Point(start_line+1, start_col),
Point(end_line+1, end_col),
)
ifi+self.config.chunk_size>=len(text):
break
i+=step_size
classTreeSitterChunker(ChunkerBase):
def__init__(self, config: Optional[Config] =None):
ifconfigisNone:
config=Config()
super().__init__(config)
self._fallback_chunker=StringChunker(config)
def__chunk_node(
self, node: Node, text_bytes: bytes
) ->Generator[Chunk, None, None]:
ifnode.textisnotNone:
logger.debug(
f"Traversing at node {node.text.decode()} at position {node.byte_range}"
)
current_chunk: str=""
prev_node=None
current_start=None
logger.debug("nbr children: %s", len(node.children))
# if node has no children we fallback to the string chunker
iflen(node.children) ==0andnode.text:
logger.debug("No children, falling back to string chunker")
yieldfromself._fallback_chunker.chunk(
node.text.decode(), ChunkOpts(start_pos=node.start_point)
)
forchildinnode.children:
child_bytes=text_bytes[child.start_byte : child.end_byte]
child_text=child_bytes.decode()
child_length=len(child_text)
ifchild_length>self.config.chunk_size:
# Yield current chunk if exists
ifcurrent_chunk:
assertcurrent_startisnotNone
yieldChunk(
text=current_chunk,
start=current_start,
end=Point(
row=current_start.row+current_chunk.count("\n"),
column=len(current_chunk.split("\n")[-1]) -1
if"\n"incurrent_chunk
elsecurrent_start.column+len(current_chunk) -1,
),
)
current_chunk=""
current_start=None
# Recursively chunk the large child node
yieldfromself.__chunk_node(child, text_bytes)
elifnotcurrent_chunk:
# Start new chunk
current_chunk=child_bytes.decode()
current_start=Point(
row=child.start_point.row+1, column=child.start_point.column
)
prev_node=child
eliflen(current_chunk) +child_length+1<=self.config.chunk_size:
# Add to current chunk
ifprev_node:
ifprev_node.end_point.row!=child.start_point.row:
current_chunk+="\n"
else:
current_chunk+=" "* (
child.start_point.column-prev_node.end_point.column
)
current_chunk+=child_bytes.decode()
prev_node=child
else:
# Yield current chunk and start new one
assertcurrent_startisnotNone
yieldChunk(
text=current_chunk,
start=current_start,
end=Point(
row=current_start.row+current_chunk.count("\n"),
column=len(current_chunk.split("\n")[-1]) -1
if"\n"incurrent_chunk
elsecurrent_start.column+len(current_chunk) -1,
),
)
current_chunk=child_bytes.decode()
current_start=Point(
row=child.start_point.row+1, column=child.start_point.column
)
# Yield remaining chunk
ifcurrent_chunk:
assertcurrent_startisnotNone
yieldChunk(
text=current_chunk,
start=current_start,
end=Point(
row=current_start.row+current_chunk.count("\n"),
column=len(current_chunk.split("\n")[-1]) -1
if"\n"incurrent_chunk
elsecurrent_start.column+len(current_chunk) -1,
),
)
@cache
def__guess_type(self, path: str, content: str) ->Optional[Lexer]:
try:
returnget_lexer_for_filename(path, content)
exceptClassNotFound:
returnNone
@cache
def__build_pattern(self, language: str):
patterns= []
lang_specific_pat=self.config.chunk_filters.get(language)
iflang_specific_pat:
patterns.extend(lang_specific_pat)
else:
patterns.extend(self.config.chunk_filters.get("*", []))
iflen(patterns):
logger.debug(
f"Merging {len(patterns)} filter patterns for excluding chunks."
)
patterns= [f"(?:{i})"foriinpatterns]
returnf"(?:{'|'.join(patterns)})"
return""
def__load_file_lines(self, path: str) ->list[str]:
assertos.path.isfile(path), f"{path} is not a valid file!"
logger.info(f"Started chunking {path} with TreeSitterChunker.")
encoding=self.config.encoding
ifencoding=="_auto":
fromcharset_normalizerimportfrom_path
match=from_path(path).best()
ifmatchisNone: # pragma: nocover
raiseUnicodeError(f"Failed to detect the encoding for {path}!")
logger.info(f"Automatically selected {encoding} for decoding {path}.")
encoding=match.encoding
else:
logger.debug(f"Decoding {path} with {encoding=}.")
withopen(path, encoding=encoding) asfin:
lines=fin.readlines()
returnlines
def__get_parser_from_config(self, file_path: str):
"""
Get parser based on filetype_map config.
"""
filetype_map=self.config.filetype_map
ifnotfiletype_map:
logger.debug("filetype_map is empty in config.")
returnNone
filename=os.path.basename(file_path)
extension=os.path.splitext(file_path)[1]
ifextension.startswith("."):
extension=extension[1:]
logger.debug(f"Checking filetype map for extension '{extension}' in {filename}")
for_language, patternsinfiletype_map.items():
language=_language.lower()
forpatterninpatterns:
try:
ifre.search(pattern, extension):
logger.debug(
f"'{filename}' extension matches pattern '{pattern}' for language '{language}'. Attempting to load parser."
)
parser=get_parser(cast(SupportedLanguage, language))
logger.debug(
f"Found parser for language '{language}' from config."
)
returnparser
exceptre.errorase:
e.add_note(
f"\nInvalid regex pattern '{pattern}' for language '{language}' in filetype_map"
)
raise
exceptLookupErrorase:
e.add_note(
f"\nTreeSitter Parser for language '{language}' not found. Please check your filetype_map config."
)
raise
logger.debug(f"No matching filetype map entry found for {filename}.")
returnNone
defchunk(
self, data: str, opts: Optional[ChunkOpts] =None
) ->Generator[Chunk, None, None]:
"""
data: path to the file
"""
lines=self.__load_file_lines(data)
content="".join(lines)
ifself.config.chunk_size<0andcontent:
logger.info(
"Skipping chunking %s because document is smaller than chunk_size.",
data,
)
yieldChunk(content, Point(1, 0), Point(len(lines), len(lines[-1]) -1))
return
parser=None
language=None
parser=self.__get_parser_from_config(data)
ifparserisNone:
lexer=self.__guess_type(data, content)
iflexerisnotNone:
lang_names= [lexer.name]
lang_names.extend(lexer.aliases)
fornameinlang_names:
try:
parser=get_parser(cast(SupportedLanguage, name.lower()))
ifparserisnotNone:
language=name.lower()
logger.debug(
"Detected %s filetype for treesitter chunking.",
language,
)
break
exceptLookupError: # pragma: nocover
pass
ifparserisNone:
logger.debug(
"Unable to pick a suitable parser. Fall back to naive chunking"
)
yieldfromself._fallback_chunker.chunk(content, opts)
else:
pattern_str=self.__build_pattern(language=language)
content_bytes=content.encode()
tree=parser.parse(content_bytes)
chunks_gen=self.__chunk_node(tree.root_node, content_bytes)
ifpattern_str:
re_pattern=re.compile(pattern_str)
forchunkinchunks_gen:
ifre_pattern.match(chunk.text) isNone:
yieldchunk
else:
yieldfromchunks_gen