topic_aware_chunking.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. """
  2. 主题感知分块
  3. """
  4. from __future__ import annotations
  5. from typing import List, Dict, Any
  6. import numpy as np
  7. from applications.api import get_basic_embedding
  8. from applications.config import DEFAULT_MODEL, Chunk
  9. from applications.utils.nlp import SplitTextIntoSentences, num_tokens, BoundaryDetector
  10. class TopicAwareChunker(BoundaryDetector, SplitTextIntoSentences):
  11. INIT_STATUS = 0
  12. PROCESSING_STATUS = 1
  13. FINISHED_STATUS = 2
  14. FAILED_STATUS = 3
  15. def __init__(self, doc_id: str):
  16. super().__init__()
  17. self.doc_id = doc_id
  18. @staticmethod
  19. async def _encode_batch(texts: List[str]) -> np.ndarray:
  20. embs = []
  21. for t in texts:
  22. e = await get_basic_embedding(t, model=DEFAULT_MODEL)
  23. embs.append(np.array(e, dtype=np.float32))
  24. return np.stack(embs)
  25. async def _raw_chunk(self, text: str, dont_chunk: bool) -> Dict[str, Any]:
  26. # sentence_list = self.jieba_sent_tokenize(text)
  27. if dont_chunk:
  28. return {
  29. "sentence_list": [text],
  30. "boundaries": [],
  31. "embeddings": await self._encode_batch([text]),
  32. }
  33. sentence_list = self.lang_chain_tokenize(text)
  34. if not sentence_list:
  35. return {}
  36. sentences_embeddings = await self._encode_batch(sentence_list)
  37. boundaries = self.detect_boundaries(sentence_list, sentences_embeddings)
  38. return {
  39. "sentence_list": sentence_list,
  40. "boundaries": boundaries,
  41. "embeddings": sentences_embeddings,
  42. }
  43. class TopicAwarePackerV1(TopicAwareChunker):
  44. def _pack_v1(
  45. self,
  46. sentence_list: List[str],
  47. boundaries: List[int],
  48. text_type: int,
  49. dataset_id: int,
  50. ) -> List[Chunk]:
  51. boundary_set = set(boundaries)
  52. chunks: List[Chunk] = []
  53. start = 0
  54. n = len(sentence_list)
  55. chunk_id = 0
  56. while start < n:
  57. end = start
  58. sent_count = 0
  59. while end < n and sent_count < self.max_sent_per_chunk:
  60. cur_tokens = num_tokens(" ".join(sentence_list[start : end + 1]))
  61. sent_count += 1
  62. if cur_tokens >= self.target_tokens:
  63. cut = end
  64. for b in range(end, start - 1, -1):
  65. if b in boundary_set:
  66. cut = b
  67. break
  68. if cut - start + 1 >= self.min_sent_per_chunk:
  69. end = cut
  70. break
  71. end += 1
  72. text = " ".join(sentence_list[start : end + 1]).strip()
  73. tokens = num_tokens(text)
  74. chunk_id += 1
  75. chunk = Chunk(
  76. doc_id=self.doc_id,
  77. chunk_id=chunk_id,
  78. text=text,
  79. tokens=tokens,
  80. text_type=text_type,
  81. dataset_id=dataset_id,
  82. )
  83. chunks.append(chunk)
  84. start = end + 1
  85. return chunks
  86. async def chunk(self, text: str, text_type: int, dataset_id: int) -> List[Chunk]:
  87. raw_info = await self._raw_chunk(text)
  88. if not raw_info:
  89. return []
  90. return self._pack_v1(
  91. sentence_list=raw_info["sentence_list"],
  92. boundaries=raw_info["boundaries"],
  93. text_type=text_type,
  94. dataset_id=dataset_id,
  95. )
  96. class TopicAwarePackerV2(TopicAwareChunker):
  97. def _pack_v2(
  98. self,
  99. sentence_list: List[str],
  100. boundaries: List[int],
  101. embeddings: np.ndarray,
  102. text_type: int,
  103. dataset_id: int,
  104. ) -> List[Chunk]:
  105. segments = []
  106. seg_embs = []
  107. last_idx = 0
  108. for b in boundaries + [len(sentence_list) - 1]:
  109. seg = sentence_list[last_idx : b + 1]
  110. seg_emb = np.mean(embeddings[last_idx : b + 1], axis=0)
  111. if seg:
  112. segments.append(seg)
  113. seg_embs.append(seg_emb)
  114. last_idx = b + 1
  115. final_segments = []
  116. for seg in segments:
  117. tokens = num_tokens("".join(seg))
  118. if tokens > self.max_tokens and len(seg) > 1:
  119. mid = len(seg) // 2
  120. final_segments.append(seg[:mid])
  121. final_segments.append(seg[mid:])
  122. else:
  123. final_segments.append(seg)
  124. chunks = []
  125. for index, seg in enumerate(final_segments, 1):
  126. text = "".join(seg)
  127. tokens = num_tokens(text)
  128. # 如果 token 过短,则暂时不用
  129. status = 2 if tokens < self.min_tokens else 1
  130. chunks.append(
  131. Chunk(
  132. doc_id=self.doc_id,
  133. dataset_id=dataset_id,
  134. text=text,
  135. chunk_id=index,
  136. tokens=tokens,
  137. text_type=text_type,
  138. status=status,
  139. )
  140. )
  141. return chunks
  142. async def chunk(self, text: str, text_type: int, dataset_id: int, dont_chunk: bool) -> List[Chunk]:
  143. raw_info = await self._raw_chunk(text, dont_chunk)
  144. if not raw_info:
  145. return []
  146. return self._pack_v2(
  147. sentence_list=raw_info["sentence_list"],
  148. boundaries=raw_info["boundaries"],
  149. embeddings=raw_info["embeddings"],
  150. text_type=text_type,
  151. dataset_id=dataset_id,
  152. )