Emit function/class chunks for Python AST; non-Python falls back to line windows.
With merge_small=True the whole file is covered: top-level definitions and the runs
of other top-level code between them (imports, constants, statements) are greedily
merged while the merged span stays within max_tokens.
Source code in src/chunktuner/chunking/code_ast.py
| def chunk(self, doc: Document, config: ChunkConfig) -> list[Chunk]:
"""Emit function/class chunks for Python AST; non-Python falls back to line windows.
With ``merge_small=True`` the whole file is covered: top-level definitions and the runs
of other top-level code between them (imports, constants, statements) are greedily
merged while the merged span stays within ``max_tokens``.
"""
validate_content_type(self.name, self.supported_content_types, doc.content_type)
max_tokens = int(config.params.get("max_tokens", 512))
merge_small = bool(config.params.get("merge_small", False))
lang = (doc.language or "").lower()
use_ast = self._parser is not None and lang in ("", "python", "py")
if not use_ast:
out = self._fallback().chunk(doc, config)
validate_chunk_offsets(doc, out)
return out
b = doc.content.encode("utf8")
tree = self._parser.parse(b)
root = tree.root_node
def to_char(byte_off: int) -> int:
return len(b[:byte_off].decode("utf8"))
if merge_small:
chunks = self._merged_chunks(doc, root, to_char, max_tokens)
else:
chunks = self._definition_chunks(doc, root, to_char, max_tokens)
if not chunks:
out = self._fallback().chunk(doc, config)
validate_chunk_offsets(doc, out)
return out
validate_chunk_offsets(doc, chunks)
return chunks
|