topic_aware_chunking.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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) -> Dict[str, Any]:
  26. # sentence_list = self.jieba_sent_tokenize(text)
  27. sentence_list = self.lang_chain_tokenize(text)
  28. if not sentence_list:
  29. return {}
  30. sentences_embeddings = await self._encode_batch(sentence_list)
  31. boundaries = self.detect_boundaries(sentence_list, sentences_embeddings)
  32. return {
  33. "sentence_list": sentence_list,
  34. "boundaries": boundaries,
  35. "embeddings": sentences_embeddings,
  36. }
  37. class TopicAwarePackerV1(TopicAwareChunker):
  38. def _pack_v1(
  39. self,
  40. sentence_list: List[str],
  41. boundaries: List[int],
  42. text_type: int,
  43. dataset_id: int,
  44. ) -> List[Chunk]:
  45. boundary_set = set(boundaries)
  46. chunks: List[Chunk] = []
  47. start = 0
  48. n = len(sentence_list)
  49. chunk_id = 0
  50. while start < n:
  51. end = start
  52. sent_count = 0
  53. while end < n and sent_count < self.max_sent_per_chunk:
  54. cur_tokens = num_tokens(" ".join(sentence_list[start : end + 1]))
  55. sent_count += 1
  56. if cur_tokens >= self.target_tokens:
  57. cut = end
  58. for b in range(end, start - 1, -1):
  59. if b in boundary_set:
  60. cut = b
  61. break
  62. if cut - start + 1 >= self.min_sent_per_chunk:
  63. end = cut
  64. break
  65. end += 1
  66. text = " ".join(sentence_list[start : end + 1]).strip()
  67. tokens = num_tokens(text)
  68. chunk_id += 1
  69. chunk = Chunk(
  70. doc_id=self.doc_id,
  71. chunk_id=chunk_id,
  72. text=text,
  73. tokens=tokens,
  74. text_type=text_type,
  75. dataset_id=dataset_id,
  76. )
  77. chunks.append(chunk)
  78. start = end + 1
  79. return chunks
  80. async def chunk(self, text: str, text_type: int, dataset_id: int) -> List[Chunk]:
  81. raw_info = await self._raw_chunk(text)
  82. if not raw_info:
  83. return []
  84. return self._pack_v1(
  85. sentence_list=raw_info["sentence_list"],
  86. boundaries=raw_info["boundaries"],
  87. text_type=text_type,
  88. dataset_id=dataset_id,
  89. )
  90. class TopicAwarePackerV2(TopicAwareChunker):
  91. def _pack_v2(
  92. self,
  93. sentence_list: List[str],
  94. boundaries: List[int],
  95. embeddings: np.ndarray,
  96. text_type: int,
  97. dataset_id: int,
  98. ) -> List[Chunk]:
  99. segments = []
  100. seg_embs = []
  101. last_idx = 0
  102. for b in boundaries + [len(sentence_list) - 1]:
  103. seg = sentence_list[last_idx : b + 1]
  104. seg_emb = np.mean(embeddings[last_idx : b + 1], axis=0)
  105. if seg:
  106. segments.append(seg)
  107. seg_embs.append(seg_emb)
  108. last_idx = b + 1
  109. final_segments = []
  110. for seg in segments:
  111. tokens = num_tokens("".join(seg))
  112. if tokens > self.max_tokens and len(seg) > 1:
  113. mid = len(seg) // 2
  114. final_segments.append(seg[:mid])
  115. final_segments.append(seg[mid:])
  116. else:
  117. final_segments.append(seg)
  118. chunks = []
  119. for index, seg in enumerate(final_segments, 1):
  120. text = "".join(seg)
  121. tokens = num_tokens(text)
  122. # 如果 token 过短,则暂时不用
  123. status = 2 if tokens < self.min_tokens else 1
  124. chunks.append(
  125. Chunk(
  126. doc_id=self.doc_id,
  127. dataset_id=dataset_id,
  128. text=text,
  129. chunk_id=index,
  130. tokens=num_tokens(text),
  131. text_type=text_type,
  132. status=status,
  133. )
  134. )
  135. return chunks
  136. async def chunk(self, text: str, text_type: int, dataset_id: int) -> List[Chunk]:
  137. raw_info = await self._raw_chunk(text)
  138. if not raw_info:
  139. return []
  140. return self._pack_v2(
  141. sentence_list=raw_info["sentence_list"],
  142. boundaries=raw_info["boundaries"],
  143. embeddings=raw_info["embeddings"],
  144. text_type=text_type,
  145. dataset_id=dataset_id,
  146. )