text_splitter.py 20 KB

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