text_splitter.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. @classmethod
  142. def from_tiktoken_encoder(
  143. cls: type[TS],
  144. encoding_name: str = "gpt2",
  145. model_name: Optional[str] = None,
  146. allowed_special: Union[Literal["all"], Set[str]] = set(),
  147. disallowed_special: Union[Literal["all"], Collection[str]] = "all",
  148. **kwargs: Any,
  149. ) -> TS:
  150. """Text splitter that uses tiktoken encoder to count length."""
  151. try:
  152. import tiktoken
  153. except ImportError:
  154. raise ImportError(
  155. "Could not import tiktoken python package. "
  156. "This is needed in order to calculate max_tokens_for_prompt. "
  157. "Please install it with `pip install tiktoken`."
  158. )
  159. if model_name is not None:
  160. enc = tiktoken.encoding_for_model(model_name)
  161. else:
  162. enc = tiktoken.get_encoding(encoding_name)
  163. def _tiktoken_encoder(text: str) -> int:
  164. return len(
  165. enc.encode(
  166. text,
  167. allowed_special=allowed_special,
  168. disallowed_special=disallowed_special,
  169. )
  170. )
  171. if issubclass(cls, TokenTextSplitter):
  172. extra_kwargs = {
  173. "encoding_name": encoding_name,
  174. "model_name": model_name,
  175. "allowed_special": allowed_special,
  176. "disallowed_special": disallowed_special,
  177. }
  178. kwargs = {**kwargs, **extra_kwargs}
  179. return cls(length_function=lambda x: [_tiktoken_encoder(text) for text in x], **kwargs)
  180. def transform_documents(self, documents: Sequence[Document], **kwargs: Any) -> Sequence[Document]:
  181. """Transform sequence of documents by splitting them."""
  182. return self.split_documents(list(documents))
  183. async def atransform_documents(self, documents: Sequence[Document], **kwargs: Any) -> Sequence[Document]:
  184. """Asynchronously transform a sequence of documents by splitting them."""
  185. raise NotImplementedError
  186. class CharacterTextSplitter(TextSplitter):
  187. """Splitting text that looks at characters."""
  188. def __init__(self, separator: str = "\n\n", **kwargs: Any) -> None:
  189. """Create a new TextSplitter."""
  190. super().__init__(**kwargs)
  191. self._separator = separator
  192. def split_text(self, text: str) -> list[str]:
  193. """Split incoming text and return chunks."""
  194. # First we naively split the large input into a bunch of smaller ones.
  195. splits = _split_text_with_regex(text, self._separator, self._keep_separator)
  196. _separator = "" if self._keep_separator else self._separator
  197. _good_splits_lengths = [] # cache the lengths of the splits
  198. if splits:
  199. _good_splits_lengths.extend(self._length_function(splits))
  200. return self._merge_splits(splits, _separator, _good_splits_lengths)
  201. class LineType(TypedDict):
  202. """Line type as typed dict."""
  203. metadata: dict[str, str]
  204. content: str
  205. class HeaderType(TypedDict):
  206. """Header type as typed dict."""
  207. level: int
  208. name: str
  209. data: str
  210. class MarkdownHeaderTextSplitter:
  211. """Splitting markdown files based on specified headers."""
  212. def __init__(self, headers_to_split_on: list[tuple[str, str]], return_each_line: bool = False):
  213. """Create a new MarkdownHeaderTextSplitter.
  214. Args:
  215. headers_to_split_on: Headers we want to track
  216. return_each_line: Return each line w/ associated headers
  217. """
  218. # Output line-by-line or aggregated into chunks w/ common headers
  219. self.return_each_line = return_each_line
  220. # Given the headers we want to split on,
  221. # (e.g., "#, ##, etc") order by length
  222. self.headers_to_split_on = sorted(headers_to_split_on, key=lambda split: len(split[0]), reverse=True)
  223. def aggregate_lines_to_chunks(self, lines: list[LineType]) -> list[Document]:
  224. """Combine lines with common metadata into chunks
  225. Args:
  226. lines: Line of text / associated header metadata
  227. """
  228. aggregated_chunks: list[LineType] = []
  229. for line in lines:
  230. if aggregated_chunks and aggregated_chunks[-1]["metadata"] == line["metadata"]:
  231. # If the last line in the aggregated list
  232. # has the same metadata as the current line,
  233. # append the current content to the last lines's content
  234. aggregated_chunks[-1]["content"] += " \n" + line["content"]
  235. else:
  236. # Otherwise, append the current line to the aggregated list
  237. aggregated_chunks.append(line)
  238. return [Document(page_content=chunk["content"], metadata=chunk["metadata"]) for chunk in aggregated_chunks]
  239. def split_text(self, text: str) -> list[Document]:
  240. """Split markdown file
  241. Args:
  242. text: Markdown file"""
  243. # Split the input text by newline character ("\n").
  244. lines = text.split("\n")
  245. # Final output
  246. lines_with_metadata: list[LineType] = []
  247. # Content and metadata of the chunk currently being processed
  248. current_content: list[str] = []
  249. current_metadata: dict[str, str] = {}
  250. # Keep track of the nested header structure
  251. # header_stack: List[Dict[str, Union[int, str]]] = []
  252. header_stack: list[HeaderType] = []
  253. initial_metadata: dict[str, str] = {}
  254. for line in lines:
  255. stripped_line = line.strip()
  256. # Check each line against each of the header types (e.g., #, ##)
  257. for sep, name in self.headers_to_split_on:
  258. # Check if line starts with a header that we intend to split on
  259. if stripped_line.startswith(sep) and (
  260. # Header with no text OR header is followed by space
  261. # Both are valid conditions that sep is being used a header
  262. len(stripped_line) == len(sep) or stripped_line[len(sep)] == " "
  263. ):
  264. # Ensure we are tracking the header as metadata
  265. if name is not None:
  266. # Get the current header level
  267. current_header_level = sep.count("#")
  268. # Pop out headers of lower or same level from the stack
  269. while header_stack and header_stack[-1]["level"] >= current_header_level:
  270. # We have encountered a new header
  271. # at the same or higher level
  272. popped_header = header_stack.pop()
  273. # Clear the metadata for the
  274. # popped header in initial_metadata
  275. if popped_header["name"] in initial_metadata:
  276. initial_metadata.pop(popped_header["name"])
  277. # Push the current header to the stack
  278. header: HeaderType = {
  279. "level": current_header_level,
  280. "name": name,
  281. "data": stripped_line[len(sep) :].strip(),
  282. }
  283. header_stack.append(header)
  284. # Update initial_metadata with the current header
  285. initial_metadata[name] = header["data"]
  286. # Add the previous line to the lines_with_metadata
  287. # only if current_content is not empty
  288. if current_content:
  289. lines_with_metadata.append(
  290. {
  291. "content": "\n".join(current_content),
  292. "metadata": current_metadata.copy(),
  293. }
  294. )
  295. current_content.clear()
  296. break
  297. else:
  298. if stripped_line:
  299. current_content.append(stripped_line)
  300. elif current_content:
  301. lines_with_metadata.append(
  302. {
  303. "content": "\n".join(current_content),
  304. "metadata": current_metadata.copy(),
  305. }
  306. )
  307. current_content.clear()
  308. current_metadata = initial_metadata.copy()
  309. if current_content:
  310. lines_with_metadata.append({"content": "\n".join(current_content), "metadata": current_metadata})
  311. # lines_with_metadata has each line with associated header metadata
  312. # aggregate these into chunks based on common metadata
  313. if not self.return_each_line:
  314. return self.aggregate_lines_to_chunks(lines_with_metadata)
  315. else:
  316. return [
  317. Document(page_content=chunk["content"], metadata=chunk["metadata"]) for chunk in lines_with_metadata
  318. ]
  319. # should be in newer Python versions (3.10+)
  320. # @dataclass(frozen=True, kw_only=True, slots=True)
  321. @dataclass(frozen=True)
  322. class Tokenizer:
  323. chunk_overlap: int
  324. tokens_per_chunk: int
  325. decode: Callable[[list[int]], str]
  326. encode: Callable[[str], list[int]]
  327. def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> list[str]:
  328. """Split incoming text and return chunks using tokenizer."""
  329. splits: list[str] = []
  330. input_ids = tokenizer.encode(text)
  331. start_idx = 0
  332. cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))
  333. chunk_ids = input_ids[start_idx:cur_idx]
  334. while start_idx < len(input_ids):
  335. splits.append(tokenizer.decode(chunk_ids))
  336. start_idx += tokenizer.tokens_per_chunk - tokenizer.chunk_overlap
  337. cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))
  338. chunk_ids = input_ids[start_idx:cur_idx]
  339. return splits
  340. class TokenTextSplitter(TextSplitter):
  341. """Splitting text to tokens using model tokenizer."""
  342. def __init__(
  343. self,
  344. encoding_name: str = "gpt2",
  345. model_name: Optional[str] = None,
  346. allowed_special: Union[Literal["all"], Set[str]] = set(),
  347. disallowed_special: Union[Literal["all"], Collection[str]] = "all",
  348. **kwargs: Any,
  349. ) -> None:
  350. """Create a new TextSplitter."""
  351. super().__init__(**kwargs)
  352. try:
  353. import tiktoken
  354. except ImportError:
  355. raise ImportError(
  356. "Could not import tiktoken python package. "
  357. "This is needed in order to for TokenTextSplitter. "
  358. "Please install it with `pip install tiktoken`."
  359. )
  360. if model_name is not None:
  361. enc = tiktoken.encoding_for_model(model_name)
  362. else:
  363. enc = tiktoken.get_encoding(encoding_name)
  364. self._tokenizer = enc
  365. self._allowed_special = allowed_special
  366. self._disallowed_special = disallowed_special
  367. def split_text(self, text: str) -> list[str]:
  368. def _encode(_text: str) -> list[int]:
  369. return self._tokenizer.encode(
  370. _text,
  371. allowed_special=self._allowed_special,
  372. disallowed_special=self._disallowed_special,
  373. )
  374. tokenizer = Tokenizer(
  375. chunk_overlap=self._chunk_overlap,
  376. tokens_per_chunk=self._chunk_size,
  377. decode=self._tokenizer.decode,
  378. encode=_encode,
  379. )
  380. return split_text_on_tokens(text=text, tokenizer=tokenizer)
  381. class RecursiveCharacterTextSplitter(TextSplitter):
  382. """Splitting text by recursively look at characters.
  383. Recursively tries to split by different characters to find one
  384. that works.
  385. """
  386. def __init__(
  387. self,
  388. separators: Optional[list[str]] = None,
  389. keep_separator: bool = True,
  390. **kwargs: Any,
  391. ) -> None:
  392. """Create a new TextSplitter."""
  393. super().__init__(keep_separator=keep_separator, **kwargs)
  394. self._separators = separators or ["\n\n", "\n", " ", ""]
  395. def _split_text(self, text: str, separators: list[str]) -> list[str]:
  396. final_chunks = []
  397. separator = separators[-1]
  398. new_separators = []
  399. for i, _s in enumerate(separators):
  400. if _s == "":
  401. separator = _s
  402. break
  403. if re.search(_s, text):
  404. separator = _s
  405. new_separators = separators[i + 1 :]
  406. break
  407. splits = _split_text_with_regex(text, separator, self._keep_separator)
  408. _good_splits = []
  409. _good_splits_lengths = [] # cache the lengths of the splits
  410. _separator = "" if self._keep_separator else separator
  411. s_lens = self._length_function(splits)
  412. for s, s_len in zip(splits, s_lens):
  413. if s_len < self._chunk_size:
  414. _good_splits.append(s)
  415. _good_splits_lengths.append(s_len)
  416. else:
  417. if _good_splits:
  418. merged_text = self._merge_splits(_good_splits, _separator, _good_splits_lengths)
  419. final_chunks.extend(merged_text)
  420. _good_splits = []
  421. _good_splits_lengths = []
  422. if not new_separators:
  423. final_chunks.append(s)
  424. else:
  425. other_info = self._split_text(s, new_separators)
  426. final_chunks.extend(other_info)
  427. if _good_splits:
  428. merged_text = self._merge_splits(_good_splits, _separator, _good_splits_lengths)
  429. final_chunks.extend(merged_text)
  430. return final_chunks
  431. def split_text(self, text: str) -> list[str]:
  432. return self._split_text(text, self._separators)