You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 6.8KB

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