text_splitter.py 20 KB

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