您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

__init__.py 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from nltk.stem import PorterStemmer
  2. stemmer = PorterStemmer()
  3. import re
  4. from nltk import word_tokenize
  5. from . import huqie
  6. from rag.utils import num_tokens_from_string
  7. import random
  8. BULLET_PATTERN = [[
  9. r"第[零一二三四五六七八九十百0-9]+(分?编|部分)",
  10. r"第[零一二三四五六七八九十百0-9]+章",
  11. r"第[零一二三四五六七八九十百0-9]+节",
  12. r"第[零一二三四五六七八九十百0-9]+条",
  13. r"[\((][零一二三四五六七八九十百]+[\))]",
  14. ], [
  15. r"第[0-9]+章",
  16. r"第[0-9]+节",
  17. r"[0-9]{,3}[\. 、]",
  18. r"[0-9]{,2}\.[0-9]{,2}",
  19. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  20. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  21. ], [
  22. r"第[零一二三四五六七八九十百0-9]+章",
  23. r"第[零一二三四五六七八九十百0-9]+节",
  24. r"[零一二三四五六七八九十百]+[ 、]",
  25. r"[\((][零一二三四五六七八九十百]+[\))]",
  26. r"[\((][0-9]{,2}[\))]",
  27. ], [
  28. r"PART (ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)",
  29. r"Chapter (I+V?|VI*|XI|IX|X)",
  30. r"Section [0-9]+",
  31. r"Article [0-9]+"
  32. ]
  33. ]
  34. def random_choices(arr, k):
  35. k = min(len(arr), k)
  36. return random.choices(arr, k=k)
  37. def bullets_category(sections):
  38. global BULLET_PATTERN
  39. hits = [0] * len(BULLET_PATTERN)
  40. for i, pro in enumerate(BULLET_PATTERN):
  41. for sec in sections:
  42. for p in pro:
  43. if re.match(p, sec):
  44. hits[i] += 1
  45. break
  46. maxium = 0
  47. res = -1
  48. for i, h in enumerate(hits):
  49. if h <= maxium: continue
  50. res = i
  51. maxium = h
  52. return res
  53. def is_english(texts):
  54. eng = 0
  55. for t in texts:
  56. if re.match(r"[a-zA-Z]{2,}", t.strip()):
  57. eng += 1
  58. if eng / len(texts) > 0.8:
  59. return True
  60. return False
  61. def tokenize(d, t, eng):
  62. d["content_with_weight"] = t
  63. if eng:
  64. t = re.sub(r"([a-z])-([a-z])", r"\1\2", t)
  65. d["content_ltks"] = " ".join([stemmer.stem(w) for w in word_tokenize(t)])
  66. else:
  67. d["content_ltks"] = huqie.qie(t)
  68. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  69. def remove_contents_table(sections, eng=False):
  70. i = 0
  71. while i < len(sections):
  72. def get(i):
  73. nonlocal sections
  74. return (sections[i] if type(sections[i]) == type("") else sections[i][0]).strip()
  75. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  76. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  77. i += 1
  78. continue
  79. sections.pop(i)
  80. if i >= len(sections): break
  81. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  82. while not prefix:
  83. sections.pop(i)
  84. if i >= len(sections): break
  85. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  86. sections.pop(i)
  87. if i >= len(sections) or not prefix: break
  88. for j in range(i, min(i + 128, len(sections))):
  89. if not re.match(prefix, get(j)):
  90. continue
  91. for _ in range(i, j): sections.pop(i)
  92. break
  93. def make_colon_as_title(sections):
  94. if not sections: return []
  95. if type(sections[0]) == type(""): return sections
  96. i = 0
  97. while i < len(sections):
  98. txt, layout = sections[i]
  99. i += 1
  100. txt = txt.split("@")[0].strip()
  101. if not txt:
  102. continue
  103. if txt[-1] not in "::":
  104. continue
  105. txt = txt[::-1]
  106. arr = re.split(r"([。?!!?;;]| .)", txt)
  107. if len(arr) < 2 or len(arr[1]) < 32:
  108. continue
  109. sections.insert(i - 1, (arr[0][::-1], "title"))
  110. i += 1
  111. def hierarchical_merge(bull, sections, depth):
  112. if not sections or bull < 0: return []
  113. if type(sections[0]) == type(""): sections = [(s, "") for s in sections]
  114. sections = [(t,o) for t, o in sections if t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  115. bullets_size = len(BULLET_PATTERN[bull])
  116. levels = [[] for _ in range(bullets_size + 2)]
  117. def not_title(txt):
  118. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt): return False
  119. if len(txt) >= 128: return True
  120. return re.search(r"[,;,。;!!]", txt)
  121. for i, (txt, layout) in enumerate(sections):
  122. for j, p in enumerate(BULLET_PATTERN[bull]):
  123. if re.match(p, txt.strip()) and not not_title(txt):
  124. levels[j].append(i)
  125. break
  126. else:
  127. if re.search(r"(title|head)", layout):
  128. levels[bullets_size].append(i)
  129. else:
  130. levels[bullets_size + 1].append(i)
  131. sections = [t for t, _ in sections]
  132. for s in sections: print("--", s)
  133. def binary_search(arr, target):
  134. if not arr: return -1
  135. if target > arr[-1]: return len(arr) - 1
  136. if target < arr[0]: return -1
  137. s, e = 0, len(arr)
  138. while e - s > 1:
  139. i = (e + s) // 2
  140. if target > arr[i]:
  141. s = i
  142. continue
  143. elif target < arr[i]:
  144. e = i
  145. continue
  146. else:
  147. assert False
  148. return s
  149. cks = []
  150. readed = [False] * len(sections)
  151. levels = levels[::-1]
  152. for i, arr in enumerate(levels[:depth]):
  153. for j in arr:
  154. if readed[j]: continue
  155. readed[j] = True
  156. cks.append([j])
  157. if i + 1 == len(levels) - 1: continue
  158. for ii in range(i + 1, len(levels)):
  159. jj = binary_search(levels[ii], j)
  160. if jj < 0: continue
  161. if jj > cks[-1][-1]: cks[-1].pop(-1)
  162. cks[-1].append(levels[ii][jj])
  163. for ii in cks[-1]: readed[ii] = True
  164. for i in range(len(cks)):
  165. cks[i] = [sections[j] for j in cks[i][::-1]]
  166. print("--------------\n", "\n* ".join(cks[i]))
  167. return cks
  168. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  169. if not sections: return []
  170. if type(sections[0]) == type(""): sections = [(s, "") for s in sections]
  171. cks = [""]
  172. tk_nums = [0]
  173. def add_chunk(t, pos):
  174. nonlocal cks, tk_nums, delimiter
  175. tnum = num_tokens_from_string(t)
  176. if tnum < 8: pos = ""
  177. if tk_nums[-1] > chunk_token_num:
  178. cks.append(t + pos)
  179. tk_nums.append(tnum)
  180. else:
  181. cks[-1] += t + pos
  182. tk_nums[-1] += tnum
  183. for sec, pos in sections:
  184. s, e = 0, 1
  185. while e < len(sec):
  186. if sec[e] in delimiter:
  187. add_chunk(sec[s: e+1], pos)
  188. s = e + 1
  189. e = s + 1
  190. else:
  191. e += 1
  192. if s < e: add_chunk(sec[s: e], pos)
  193. return cks