text_splitter.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. _good_splits_lengths = [] # cache the lengths of the splits
  216. for split in splits:
  217. _good_splits_lengths.append(self._length_function(split))
  218. return self._merge_splits(splits, _separator, _good_splits_lengths)
  219. class LineType(TypedDict):
  220. """Line type as typed dict."""
  221. metadata: dict[str, str]
  222. content: str
  223. class HeaderType(TypedDict):
  224. """Header type as typed dict."""
  225. level: int
  226. name: str
  227. data: str
  228. class MarkdownHeaderTextSplitter:
  229. """Splitting markdown files based on specified headers."""
  230. def __init__(
  231. self, headers_to_split_on: list[tuple[str, str]], return_each_line: bool = False
  232. ):
  233. """Create a new MarkdownHeaderTextSplitter.
  234. Args:
  235. headers_to_split_on: Headers we want to track
  236. return_each_line: Return each line w/ associated headers
  237. """
  238. # Output line-by-line or aggregated into chunks w/ common headers
  239. self.return_each_line = return_each_line
  240. # Given the headers we want to split on,
  241. # (e.g., "#, ##, etc") order by length
  242. self.headers_to_split_on = sorted(
  243. headers_to_split_on, key=lambda split: len(split[0]), reverse=True
  244. )
  245. def aggregate_lines_to_chunks(self, lines: list[LineType]) -> list[Document]:
  246. """Combine lines with common metadata into chunks
  247. Args:
  248. lines: Line of text / associated header metadata
  249. """
  250. aggregated_chunks: list[LineType] = []
  251. for line in lines:
  252. if (
  253. aggregated_chunks
  254. and aggregated_chunks[-1]["metadata"] == line["metadata"]
  255. ):
  256. # If the last line in the aggregated list
  257. # has the same metadata as the current line,
  258. # append the current content to the last lines's content
  259. aggregated_chunks[-1]["content"] += " \n" + line["content"]
  260. else:
  261. # Otherwise, append the current line to the aggregated list
  262. aggregated_chunks.append(line)
  263. return [
  264. Document(page_content=chunk["content"], metadata=chunk["metadata"])
  265. for chunk in aggregated_chunks
  266. ]
  267. def split_text(self, text: str) -> list[Document]:
  268. """Split markdown file
  269. Args:
  270. text: Markdown file"""
  271. # Split the input text by newline character ("\n").
  272. lines = text.split("\n")
  273. # Final output
  274. lines_with_metadata: list[LineType] = []
  275. # Content and metadata of the chunk currently being processed
  276. current_content: list[str] = []
  277. current_metadata: dict[str, str] = {}
  278. # Keep track of the nested header structure
  279. # header_stack: List[Dict[str, Union[int, str]]] = []
  280. header_stack: list[HeaderType] = []
  281. initial_metadata: dict[str, str] = {}
  282. for line in lines:
  283. stripped_line = line.strip()
  284. # Check each line against each of the header types (e.g., #, ##)
  285. for sep, name in self.headers_to_split_on:
  286. # Check if line starts with a header that we intend to split on
  287. if stripped_line.startswith(sep) and (
  288. # Header with no text OR header is followed by space
  289. # Both are valid conditions that sep is being used a header
  290. len(stripped_line) == len(sep)
  291. or stripped_line[len(sep)] == " "
  292. ):
  293. # Ensure we are tracking the header as metadata
  294. if name is not None:
  295. # Get the current header level
  296. current_header_level = sep.count("#")
  297. # Pop out headers of lower or same level from the stack
  298. while (
  299. header_stack
  300. and header_stack[-1]["level"] >= current_header_level
  301. ):
  302. # We have encountered a new header
  303. # at the same or higher level
  304. popped_header = header_stack.pop()
  305. # Clear the metadata for the
  306. # popped header in initial_metadata
  307. if popped_header["name"] in initial_metadata:
  308. initial_metadata.pop(popped_header["name"])
  309. # Push the current header to the stack
  310. header: HeaderType = {
  311. "level": current_header_level,
  312. "name": name,
  313. "data": stripped_line[len(sep):].strip(),
  314. }
  315. header_stack.append(header)
  316. # Update initial_metadata with the current header
  317. initial_metadata[name] = header["data"]
  318. # Add the previous line to the lines_with_metadata
  319. # only if current_content is not empty
  320. if current_content:
  321. lines_with_metadata.append(
  322. {
  323. "content": "\n".join(current_content),
  324. "metadata": current_metadata.copy(),
  325. }
  326. )
  327. current_content.clear()
  328. break
  329. else:
  330. if stripped_line:
  331. current_content.append(stripped_line)
  332. elif current_content:
  333. lines_with_metadata.append(
  334. {
  335. "content": "\n".join(current_content),
  336. "metadata": current_metadata.copy(),
  337. }
  338. )
  339. current_content.clear()
  340. current_metadata = initial_metadata.copy()
  341. if current_content:
  342. lines_with_metadata.append(
  343. {"content": "\n".join(current_content), "metadata": current_metadata}
  344. )
  345. # lines_with_metadata has each line with associated header metadata
  346. # aggregate these into chunks based on common metadata
  347. if not self.return_each_line:
  348. return self.aggregate_lines_to_chunks(lines_with_metadata)
  349. else:
  350. return [
  351. Document(page_content=chunk["content"], metadata=chunk["metadata"])
  352. for chunk in lines_with_metadata
  353. ]
  354. # should be in newer Python versions (3.10+)
  355. # @dataclass(frozen=True, kw_only=True, slots=True)
  356. @dataclass(frozen=True)
  357. class Tokenizer:
  358. chunk_overlap: int
  359. tokens_per_chunk: int
  360. decode: Callable[[list[int]], str]
  361. encode: Callable[[str], list[int]]
  362. def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> list[str]:
  363. """Split incoming text and return chunks using tokenizer."""
  364. splits: list[str] = []
  365. input_ids = tokenizer.encode(text)
  366. start_idx = 0
  367. cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))
  368. chunk_ids = input_ids[start_idx:cur_idx]
  369. while start_idx < len(input_ids):
  370. splits.append(tokenizer.decode(chunk_ids))
  371. start_idx += tokenizer.tokens_per_chunk - tokenizer.chunk_overlap
  372. cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))
  373. chunk_ids = input_ids[start_idx:cur_idx]
  374. return splits
  375. class TokenTextSplitter(TextSplitter):
  376. """Splitting text to tokens using model tokenizer."""
  377. def __init__(
  378. self,
  379. encoding_name: str = "gpt2",
  380. model_name: Optional[str] = None,
  381. allowed_special: Union[Literal["all"], Set[str]] = set(),
  382. disallowed_special: Union[Literal["all"], Collection[str]] = "all",
  383. **kwargs: Any,
  384. ) -> None:
  385. """Create a new TextSplitter."""
  386. super().__init__(**kwargs)
  387. try:
  388. import tiktoken
  389. except ImportError:
  390. raise ImportError(
  391. "Could not import tiktoken python package. "
  392. "This is needed in order to for TokenTextSplitter. "
  393. "Please install it with `pip install tiktoken`."
  394. )
  395. if model_name is not None:
  396. enc = tiktoken.encoding_for_model(model_name)
  397. else:
  398. enc = tiktoken.get_encoding(encoding_name)
  399. self._tokenizer = enc
  400. self._allowed_special = allowed_special
  401. self._disallowed_special = disallowed_special
  402. def split_text(self, text: str) -> list[str]:
  403. def _encode(_text: str) -> list[int]:
  404. return self._tokenizer.encode(
  405. _text,
  406. allowed_special=self._allowed_special,
  407. disallowed_special=self._disallowed_special,
  408. )
  409. tokenizer = Tokenizer(
  410. chunk_overlap=self._chunk_overlap,
  411. tokens_per_chunk=self._chunk_size,
  412. decode=self._tokenizer.decode,
  413. encode=_encode,
  414. )
  415. return split_text_on_tokens(text=text, tokenizer=tokenizer)
  416. class RecursiveCharacterTextSplitter(TextSplitter):
  417. """Splitting text by recursively look at characters.
  418. Recursively tries to split by different characters to find one
  419. that works.
  420. """
  421. def __init__(
  422. self,
  423. separators: Optional[list[str]] = None,
  424. keep_separator: bool = True,
  425. **kwargs: Any,
  426. ) -> None:
  427. """Create a new TextSplitter."""
  428. super().__init__(keep_separator=keep_separator, **kwargs)
  429. self._separators = separators or ["\n\n", "\n", " ", ""]
  430. def _split_text(self, text: str, separators: list[str]) -> list[str]:
  431. final_chunks = []
  432. separator = separators[-1]
  433. new_separators = []
  434. for i, _s in enumerate(separators):
  435. if _s == "":
  436. separator = _s
  437. break
  438. if re.search(_s, text):
  439. separator = _s
  440. new_separators = separators[i + 1:]
  441. break
  442. splits = _split_text_with_regex(text, separator, self._keep_separator)
  443. _good_splits = []
  444. _good_splits_lengths = [] # cache the lengths of the splits
  445. _separator = "" if self._keep_separator else separator
  446. for s in splits:
  447. s_len = self._length_function(s)
  448. if s_len < self._chunk_size:
  449. _good_splits.append(s)
  450. _good_splits_lengths.append(s_len)
  451. else:
  452. if _good_splits:
  453. merged_text = self._merge_splits(_good_splits, _separator, _good_splits_lengths)
  454. final_chunks.extend(merged_text)
  455. _good_splits = []
  456. _good_splits_lengths = []
  457. if not new_separators:
  458. final_chunks.append(s)
  459. else:
  460. other_info = self._split_text(s, new_separators)
  461. final_chunks.extend(other_info)
  462. if _good_splits:
  463. merged_text = self._merge_splits(_good_splits, _separator, _good_splits_lengths)
  464. final_chunks.extend(merged_text)
  465. return final_chunks
  466. def split_text(self, text: str) -> list[str]:
  467. return self._split_text(text, self._separators)