text_splitter.py 19 KB

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