Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

__init__.py 6.8KB

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