You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

text_splitter.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. from __future__ import annotations
  2. import copy
  3. import logging
  4. import re
  5. from abc import ABC, abstractmethod
  6. from collections.abc import Callable, Collection, Iterable, Sequence, Set
  7. from dataclasses import dataclass
  8. from typing import (
  9. Any,
  10. Literal,
  11. Optional,
  12. TypedDict,
  13. TypeVar,
  14. Union,
  15. )
  16. from core.rag.models.document import BaseDocumentTransformer, Document
  17. logger = logging.getLogger(__name__)
  18. TS = TypeVar("TS", bound="TextSplitter")
  19. def _split_text_with_regex(text: str, separator: str, keep_separator: bool) -> list[str]:
  20. # Now that we have the separator, split the text
  21. if separator:
  22. if keep_separator:
  23. # The parentheses in the pattern keep the delimiters in the result.
  24. _splits = re.split(f"({re.escape(separator)})", text)
  25. splits = [_splits[i - 1] + _splits[i] for i in range(1, len(_splits), 2)]
  26. if len(_splits) % 2 != 0:
  27. splits += _splits[-1:]
  28. else:
  29. splits = re.split(separator, text)
  30. else:
  31. splits = list(text)
  32. return [s for s in splits if (s not in {"", "\n"})]
  33. class TextSplitter(BaseDocumentTransformer, ABC):
  34. """Interface for splitting text into chunks."""
  35. def __init__(
  36. self,
  37. chunk_size: int = 4000,
  38. chunk_overlap: int = 200,
  39. length_function: Callable[[list[str]], list[int]] = lambda x: [len(x) for x in x],
  40. keep_separator: bool = False,
  41. add_start_index: bool = False,
  42. ) -> None:
  43. """Create a new TextSplitter.
  44. Args:
  45. chunk_size: Maximum size of chunks to return
  46. chunk_overlap: Overlap in characters between chunks
  47. length_function: Function that measures the length of given chunks
  48. keep_separator: Whether to keep the separator in the chunks
  49. add_start_index: If `True`, includes chunk's start index in metadata
  50. """
  51. if chunk_overlap > chunk_size:
  52. raise ValueError(
  53. f"Got a larger chunk overlap ({chunk_overlap}) than chunk size ({chunk_size}), should be smaller."
  54. )
  55. self._chunk_size = chunk_size
  56. self._chunk_overlap = chunk_overlap
  57. self._length_function = length_function
  58. self._keep_separator = keep_separator
  59. self._add_start_index = add_start_index
  60. @abstractmethod
  61. def split_text(self, text: str) -> list[str]:
  62. """Split text into multiple components."""
  63. def create_documents(self, texts: list[str], metadatas: Optional[list[dict]] = None) -> list[Document]:
  64. """Create documents from a list of texts."""
  65. _metadatas = metadatas or [{}] * len(texts)
  66. documents = []
  67. for i, text in enumerate(texts):
  68. index = -1
  69. for chunk in self.split_text(text):
  70. metadata = copy.deepcopy(_metadatas[i])
  71. if self._add_start_index:
  72. index = text.find(chunk, index + 1)
  73. metadata["start_index"] = index
  74. new_doc = Document(page_content=chunk, metadata=metadata)
  75. documents.append(new_doc)
  76. return documents
  77. def split_documents(self, documents: Iterable[Document]) -> list[Document]:
  78. """Split documents."""
  79. texts, metadatas = [], []
  80. for doc in documents:
  81. texts.append(doc.page_content)
  82. metadatas.append(doc.metadata or {})
  83. return self.create_documents(texts, metadatas=metadatas)
  84. def _join_docs(self, docs: list[str], separator: str) -> Optional[str]:
  85. text = separator.join(docs)
  86. text = text.strip()
  87. if text == "":
  88. return None
  89. else:
  90. return text
  91. def _merge_splits(self, splits: Iterable[str], separator: str, lengths: list[int]) -> list[str]:
  92. # We now want to combine these smaller pieces into medium size
  93. # chunks to send to the LLM.
  94. separator_len = self._length_function([separator])[0]
  95. docs = []
  96. current_doc: list[str] = []
  97. total = 0
  98. index = 0
  99. for d in splits:
  100. _len = lengths[index]
  101. if total + _len + (separator_len if len(current_doc) > 0 else 0) > self._chunk_size:
  102. if total > self._chunk_size:
  103. logger.warning(
  104. f"Created a chunk of size {total}, which is longer than the specified {self._chunk_size}"
  105. )
  106. if len(current_doc) > 0:
  107. doc = self._join_docs(current_doc, separator)
  108. if doc is not None:
  109. docs.append(doc)
  110. # Keep on popping if:
  111. # - we have a larger chunk than in the chunk overlap
  112. # - or if we still have any chunks and the length is long
  113. while total > self._chunk_overlap or (
  114. total + _len + (separator_len if len(current_doc) > 0 else 0) > self._chunk_size and total > 0
  115. ):
  116. total -= self._length_function([current_doc[0]])[0] + (
  117. separator_len if len(current_doc) > 1 else 0
  118. )
  119. current_doc = current_doc[1:]
  120. current_doc.append(d)
  121. total += _len + (separator_len if len(current_doc) > 1 else 0)
  122. index += 1
  123. doc = self._join_docs(current_doc, separator)
  124. if doc is not None:
  125. docs.append(doc)
  126. return docs
  127. @classmethod
  128. def from_huggingface_tokenizer(cls, tokenizer: Any, **kwargs: Any) -> TextSplitter:
  129. """Text splitter that uses HuggingFace tokenizer to count length."""
  130. try:
  131. from transformers import PreTrainedTokenizerBase # type: ignore
  132. if not isinstance(tokenizer, PreTrainedTokenizerBase):
  133. raise ValueError("Tokenizer received was not an instance of PreTrainedTokenizerBase")
  134. def _huggingface_tokenizer_length(text: str) -> int:
  135. return len(tokenizer.encode(text))
  136. except ImportError:
  137. raise ValueError(
  138. "Could not import transformers python package. Please install it with `pip install transformers`."
  139. )
  140. return cls(length_function=lambda x: [_huggingface_tokenizer_length(text) for text in x], **kwargs)
  141. def transform_documents(self, documents: Sequence[Document], **kwargs: Any) -> Sequence[Document]:
  142. """Transform sequence of documents by splitting them."""
  143. return self.split_documents(list(documents))
  144. async def atransform_documents(self, documents: Sequence[Document], **kwargs: Any) -> Sequence[Document]:
  145. """Asynchronously transform a sequence of documents by splitting them."""
  146. raise NotImplementedError
  147. class CharacterTextSplitter(TextSplitter):
  148. """Splitting text that looks at characters."""
  149. def __init__(self, separator: str = "\n\n", **kwargs: Any) -> None:
  150. """Create a new TextSplitter."""
  151. super().__init__(**kwargs)
  152. self._separator = separator
  153. def split_text(self, text: str) -> list[str]:
  154. """Split incoming text and return chunks."""
  155. # First we naively split the large input into a bunch of smaller ones.
  156. splits = _split_text_with_regex(text, self._separator, self._keep_separator)
  157. _separator = "" if self._keep_separator else self._separator
  158. _good_splits_lengths = [] # cache the lengths of the splits
  159. if splits:
  160. _good_splits_lengths.extend(self._length_function(splits))
  161. return self._merge_splits(splits, _separator, _good_splits_lengths)
  162. class LineType(TypedDict):
  163. """Line type as typed dict."""
  164. metadata: dict[str, str]
  165. content: str
  166. class HeaderType(TypedDict):
  167. """Header type as typed dict."""
  168. level: int
  169. name: str
  170. data: str
  171. class MarkdownHeaderTextSplitter:
  172. """Splitting markdown files based on specified headers."""
  173. def __init__(self, headers_to_split_on: list[tuple[str, str]], return_each_line: bool = False):
  174. """Create a new MarkdownHeaderTextSplitter.
  175. Args:
  176. headers_to_split_on: Headers we want to track
  177. return_each_line: Return each line w/ associated headers
  178. """
  179. # Output line-by-line or aggregated into chunks w/ common headers
  180. self.return_each_line = return_each_line
  181. # Given the headers we want to split on,
  182. # (e.g., "#, ##, etc") order by length
  183. self.headers_to_split_on = sorted(headers_to_split_on, key=lambda split: len(split[0]), reverse=True)
  184. def aggregate_lines_to_chunks(self, lines: list[LineType]) -> list[Document]:
  185. """Combine lines with common metadata into chunks
  186. Args:
  187. lines: Line of text / associated header metadata
  188. """
  189. aggregated_chunks: list[LineType] = []
  190. for line in lines:
  191. if aggregated_chunks and aggregated_chunks[-1]["metadata"] == line["metadata"]:
  192. # If the last line in the aggregated list
  193. # has the same metadata as the current line,
  194. # append the current content to the last lines's content
  195. aggregated_chunks[-1]["content"] += " \n" + line["content"]
  196. else:
  197. # Otherwise, append the current line to the aggregated list
  198. aggregated_chunks.append(line)
  199. return [Document(page_content=chunk["content"], metadata=chunk["metadata"]) for chunk in aggregated_chunks]
  200. def split_text(self, text: str) -> list[Document]:
  201. """Split markdown file
  202. Args:
  203. text: Markdown file"""
  204. # Split the input text by newline character ("\n").
  205. lines = text.split("\n")
  206. # Final output
  207. lines_with_metadata: list[LineType] = []
  208. # Content and metadata of the chunk currently being processed
  209. current_content: list[str] = []
  210. current_metadata: dict[str, str] = {}
  211. # Keep track of the nested header structure
  212. # header_stack: List[Dict[str, Union[int, str]]] = []
  213. header_stack: list[HeaderType] = []
  214. initial_metadata: dict[str, str] = {}
  215. for line in lines:
  216. stripped_line = line.strip()
  217. # Check each line against each of the header types (e.g., #, ##)
  218. for sep, name in self.headers_to_split_on:
  219. # Check if line starts with a header that we intend to split on
  220. if stripped_line.startswith(sep) and (
  221. # Header with no text OR header is followed by space
  222. # Both are valid conditions that sep is being used a header
  223. len(stripped_line) == len(sep) or stripped_line[len(sep)] == " "
  224. ):
  225. # Ensure we are tracking the header as metadata
  226. if name is not None:
  227. # Get the current header level
  228. current_header_level = sep.count("#")
  229. # Pop out headers of lower or same level from the stack
  230. while header_stack and header_stack[-1]["level"] >= current_header_level:
  231. # We have encountered a new header
  232. # at the same or higher level
  233. popped_header = header_stack.pop()
  234. # Clear the metadata for the
  235. # popped header in initial_metadata
  236. if popped_header["name"] in initial_metadata:
  237. initial_metadata.pop(popped_header["name"])
  238. # Push the current header to the stack
  239. header: HeaderType = {
  240. "level": current_header_level,
  241. "name": name,
  242. "data": stripped_line[len(sep) :].strip(),
  243. }
  244. header_stack.append(header)
  245. # Update initial_metadata with the current header
  246. initial_metadata[name] = header["data"]
  247. # Add the previous line to the lines_with_metadata
  248. # only if current_content is not empty
  249. if current_content:
  250. lines_with_metadata.append(
  251. {
  252. "content": "\n".join(current_content),
  253. "metadata": current_metadata.copy(),
  254. }
  255. )
  256. current_content.clear()
  257. break
  258. else:
  259. if stripped_line:
  260. current_content.append(stripped_line)
  261. elif current_content:
  262. lines_with_metadata.append(
  263. {
  264. "content": "\n".join(current_content),
  265. "metadata": current_metadata.copy(),
  266. }
  267. )
  268. current_content.clear()
  269. current_metadata = initial_metadata.copy()
  270. if current_content:
  271. lines_with_metadata.append({"content": "\n".join(current_content), "metadata": current_metadata})
  272. # lines_with_metadata has each line with associated header metadata
  273. # aggregate these into chunks based on common metadata
  274. if not self.return_each_line:
  275. return self.aggregate_lines_to_chunks(lines_with_metadata)
  276. else:
  277. return [
  278. Document(page_content=chunk["content"], metadata=chunk["metadata"]) for chunk in lines_with_metadata
  279. ]
  280. # should be in newer Python versions (3.10+)
  281. # @dataclass(frozen=True, kw_only=True, slots=True)
  282. @dataclass(frozen=True)
  283. class Tokenizer:
  284. chunk_overlap: int
  285. tokens_per_chunk: int
  286. decode: Callable[[list[int]], str]
  287. encode: Callable[[str], list[int]]
  288. def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> list[str]:
  289. """Split incoming text and return chunks using tokenizer."""
  290. splits: list[str] = []
  291. input_ids = tokenizer.encode(text)
  292. start_idx = 0
  293. cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))
  294. chunk_ids = input_ids[start_idx:cur_idx]
  295. while start_idx < len(input_ids):
  296. splits.append(tokenizer.decode(chunk_ids))
  297. start_idx += tokenizer.tokens_per_chunk - tokenizer.chunk_overlap
  298. cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))
  299. chunk_ids = input_ids[start_idx:cur_idx]
  300. return splits
  301. class TokenTextSplitter(TextSplitter):
  302. """Splitting text to tokens using model tokenizer."""
  303. def __init__(
  304. self,
  305. encoding_name: str = "gpt2",
  306. model_name: Optional[str] = None,
  307. allowed_special: Union[Literal["all"], Set[str]] = set(),
  308. disallowed_special: Union[Literal["all"], Collection[str]] = "all",
  309. **kwargs: Any,
  310. ) -> None:
  311. """Create a new TextSplitter."""
  312. super().__init__(**kwargs)
  313. try:
  314. import tiktoken
  315. except ImportError:
  316. raise ImportError(
  317. "Could not import tiktoken python package. "
  318. "This is needed in order to for TokenTextSplitter. "
  319. "Please install it with `pip install tiktoken`."
  320. )
  321. if model_name is not None:
  322. enc = tiktoken.encoding_for_model(model_name)
  323. else:
  324. enc = tiktoken.get_encoding(encoding_name)
  325. self._tokenizer = enc
  326. self._allowed_special = allowed_special
  327. self._disallowed_special = disallowed_special
  328. def split_text(self, text: str) -> list[str]:
  329. def _encode(_text: str) -> list[int]:
  330. return self._tokenizer.encode(
  331. _text,
  332. allowed_special=self._allowed_special,
  333. disallowed_special=self._disallowed_special,
  334. )
  335. tokenizer = Tokenizer(
  336. chunk_overlap=self._chunk_overlap,
  337. tokens_per_chunk=self._chunk_size,
  338. decode=self._tokenizer.decode,
  339. encode=_encode,
  340. )
  341. return split_text_on_tokens(text=text, tokenizer=tokenizer)
  342. class RecursiveCharacterTextSplitter(TextSplitter):
  343. """Splitting text by recursively look at characters.
  344. Recursively tries to split by different characters to find one
  345. that works.
  346. """
  347. def __init__(
  348. self,
  349. separators: Optional[list[str]] = None,
  350. keep_separator: bool = True,
  351. **kwargs: Any,
  352. ) -> None:
  353. """Create a new TextSplitter."""
  354. super().__init__(keep_separator=keep_separator, **kwargs)
  355. self._separators = separators or ["\n\n", "\n", " ", ""]
  356. def _split_text(self, text: str, separators: list[str]) -> list[str]:
  357. final_chunks = []
  358. separator = separators[-1]
  359. new_separators = []
  360. for i, _s in enumerate(separators):
  361. if _s == "":
  362. separator = _s
  363. break
  364. if re.search(_s, text):
  365. separator = _s
  366. new_separators = separators[i + 1 :]
  367. break
  368. splits = _split_text_with_regex(text, separator, self._keep_separator)
  369. _good_splits = []
  370. _good_splits_lengths = [] # cache the lengths of the splits
  371. _separator = "" if self._keep_separator else separator
  372. s_lens = self._length_function(splits)
  373. for s, s_len in zip(splits, s_lens):
  374. if s_len < self._chunk_size:
  375. _good_splits.append(s)
  376. _good_splits_lengths.append(s_len)
  377. else:
  378. if _good_splits:
  379. merged_text = self._merge_splits(_good_splits, _separator, _good_splits_lengths)
  380. final_chunks.extend(merged_text)
  381. _good_splits = []
  382. _good_splits_lengths = []
  383. if not new_separators:
  384. final_chunks.append(s)
  385. else:
  386. other_info = self._split_text(s, new_separators)
  387. final_chunks.extend(other_info)
  388. if _good_splits:
  389. merged_text = self._merge_splits(_good_splits, _separator, _good_splits_lengths)
  390. final_chunks.extend(merged_text)
  391. return final_chunks
  392. def split_text(self, text: str) -> list[str]:
  393. return self._split_text(text, self._separators)