topic_aware_chunking.py 5.1 KB

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