fixed_text_splitter.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """Functionality for splitting text."""
  2. from __future__ import annotations
  3. from typing import Any, Optional
  4. from core.model_manager import ModelInstance
  5. from core.model_runtime.model_providers.__base.tokenizers.gpt2_tokenzier import GPT2Tokenizer
  6. from core.rag.splitter.text_splitter import (
  7. TS,
  8. Collection,
  9. Literal,
  10. RecursiveCharacterTextSplitter,
  11. Set,
  12. TokenTextSplitter,
  13. Union,
  14. )
  15. class EnhanceRecursiveCharacterTextSplitter(RecursiveCharacterTextSplitter):
  16. """
  17. This class is used to implement from_gpt2_encoder, to prevent using of tiktoken
  18. """
  19. @classmethod
  20. def from_encoder(
  21. cls: type[TS],
  22. embedding_model_instance: Optional[ModelInstance],
  23. allowed_special: Union[Literal[all], Set[str]] = set(),
  24. disallowed_special: Union[Literal[all], Collection[str]] = "all",
  25. **kwargs: Any,
  26. ):
  27. def _token_encoder(text: str) -> int:
  28. if not text:
  29. return 0
  30. if embedding_model_instance:
  31. return embedding_model_instance.get_text_embedding_num_tokens(texts=[text])
  32. else:
  33. return GPT2Tokenizer.get_num_tokens(text)
  34. if issubclass(cls, TokenTextSplitter):
  35. extra_kwargs = {
  36. "model_name": embedding_model_instance.model if embedding_model_instance else "gpt2",
  37. "allowed_special": allowed_special,
  38. "disallowed_special": disallowed_special,
  39. }
  40. kwargs = {**kwargs, **extra_kwargs}
  41. return cls(length_function=_token_encoder, **kwargs)
  42. class FixedRecursiveCharacterTextSplitter(EnhanceRecursiveCharacterTextSplitter):
  43. def __init__(self, fixed_separator: str = "\n\n", separators: Optional[list[str]] = None, **kwargs: Any):
  44. """Create a new TextSplitter."""
  45. super().__init__(**kwargs)
  46. self._fixed_separator = fixed_separator
  47. self._separators = separators or ["\n\n", "\n", " ", ""]
  48. def split_text(self, text: str) -> list[str]:
  49. """Split incoming text and return chunks."""
  50. if self._fixed_separator:
  51. chunks = text.split(self._fixed_separator)
  52. else:
  53. chunks = [text]
  54. final_chunks = []
  55. for chunk in chunks:
  56. if self._length_function(chunk) > self._chunk_size:
  57. final_chunks.extend(self.recursive_split_text(chunk))
  58. else:
  59. final_chunks.append(chunk)
  60. return final_chunks
  61. def recursive_split_text(self, text: str) -> list[str]:
  62. """Split incoming text and return chunks."""
  63. final_chunks = []
  64. # Get appropriate separator to use
  65. separator = self._separators[-1]
  66. for _s in self._separators:
  67. if _s == "":
  68. separator = _s
  69. break
  70. if _s in text:
  71. separator = _s
  72. break
  73. # Now that we have the separator, split the text
  74. if separator:
  75. splits = text.split(separator)
  76. else:
  77. splits = list(text)
  78. # Now go merging things, recursively splitting longer texts.
  79. _good_splits = []
  80. _good_splits_lengths = [] # cache the lengths of the splits
  81. for s in splits:
  82. s_len = self._length_function(s)
  83. if s_len < self._chunk_size:
  84. _good_splits.append(s)
  85. _good_splits_lengths.append(s_len)
  86. else:
  87. if _good_splits:
  88. merged_text = self._merge_splits(_good_splits, separator, _good_splits_lengths)
  89. final_chunks.extend(merged_text)
  90. _good_splits = []
  91. _good_splits_lengths = []
  92. other_info = self.recursive_split_text(s)
  93. final_chunks.extend(other_info)
  94. if _good_splits:
  95. merged_text = self._merge_splits(_good_splits, separator, _good_splits_lengths)
  96. final_chunks.extend(merged_text)
  97. return final_chunks