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 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import random
  2. from rag.utils import num_tokens_from_string
  3. from . import huqie
  4. from nltk import word_tokenize
  5. import re
  6. import copy
  7. from nltk.stem import PorterStemmer
  8. stemmer = PorterStemmer()
  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:
  51. continue
  52. res = i
  53. maxium = h
  54. return res
  55. def is_english(texts):
  56. eng = 0
  57. for t in texts:
  58. if re.match(r"[a-zA-Z]{2,}", t.strip()):
  59. eng += 1
  60. if eng / len(texts) > 0.8:
  61. return True
  62. return False
  63. def tokenize(d, t, eng):
  64. d["content_with_weight"] = t
  65. if eng:
  66. t = re.sub(r"([a-z])-([a-z])", r"\1\2", t)
  67. d["content_ltks"] = " ".join([stemmer.stem(w)
  68. for w in word_tokenize(t)])
  69. else:
  70. d["content_ltks"] = huqie.qie(t)
  71. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  72. def tokenize_table(tbls, doc, eng, batch_size=10):
  73. res = []
  74. # add tables
  75. for (img, rows), poss in tbls:
  76. if not rows:
  77. continue
  78. if isinstance(rows, str):
  79. d = copy.deepcopy(doc)
  80. r = re.sub(r"<[^<>]{,12}>", "", rows)
  81. tokenize(d, r, eng)
  82. d["content_with_weight"] = rows
  83. d["image"] = img
  84. add_positions(d, poss)
  85. res.append(d)
  86. continue
  87. de = "; " if eng else "; "
  88. for i in range(0, len(rows), batch_size):
  89. d = copy.deepcopy(doc)
  90. r = de.join(rows[i:i + batch_size])
  91. tokenize(d, r, eng)
  92. d["image"] = img
  93. add_positions(d, poss)
  94. res.append(d)
  95. return res
  96. def add_positions(d, poss):
  97. if not poss:
  98. return
  99. d["page_num_int"] = []
  100. d["position_int"] = []
  101. d["top_int"] = []
  102. for pn, left, right, top, bottom in poss:
  103. d["page_num_int"].append(pn + 1)
  104. d["top_int"].append(top)
  105. d["position_int"].append((pn + 1, left, right, top, bottom))
  106. d["top_int"] = d["top_int"][:1]
  107. def remove_contents_table(sections, eng=False):
  108. i = 0
  109. while i < len(sections):
  110. def get(i):
  111. nonlocal sections
  112. return (sections[i] if isinstance(sections[i],
  113. type("")) else sections[i][0]).strip()
  114. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  115. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  116. i += 1
  117. continue
  118. sections.pop(i)
  119. if i >= len(sections):
  120. break
  121. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  122. while not prefix:
  123. sections.pop(i)
  124. if i >= len(sections):
  125. break
  126. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  127. sections.pop(i)
  128. if i >= len(sections) or not prefix:
  129. break
  130. for j in range(i, min(i + 128, len(sections))):
  131. if not re.match(prefix, get(j)):
  132. continue
  133. for _ in range(i, j):
  134. sections.pop(i)
  135. break
  136. def make_colon_as_title(sections):
  137. if not sections:
  138. return []
  139. if isinstance(sections[0], type("")):
  140. return sections
  141. i = 0
  142. while i < len(sections):
  143. txt, layout = sections[i]
  144. i += 1
  145. txt = txt.split("@")[0].strip()
  146. if not txt:
  147. continue
  148. if txt[-1] not in "::":
  149. continue
  150. txt = txt[::-1]
  151. arr = re.split(r"([。?!!?;;]| .)", txt)
  152. if len(arr) < 2 or len(arr[1]) < 32:
  153. continue
  154. sections.insert(i - 1, (arr[0][::-1], "title"))
  155. i += 1
  156. def hierarchical_merge(bull, sections, depth):
  157. if not sections or bull < 0:
  158. return []
  159. if isinstance(sections[0], type("")):
  160. sections = [(s, "") for s in sections]
  161. sections = [(t, o) for t, o in sections if
  162. t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  163. bullets_size = len(BULLET_PATTERN[bull])
  164. levels = [[] for _ in range(bullets_size + 2)]
  165. def not_title(txt):
  166. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
  167. return False
  168. if len(txt.split(" ")) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
  169. return True
  170. return re.search(r"[,;,。;!!]", txt)
  171. for i, (txt, layout) in enumerate(sections):
  172. for j, p in enumerate(BULLET_PATTERN[bull]):
  173. if re.match(p, txt.strip()):
  174. levels[j].append(i)
  175. break
  176. else:
  177. if re.search(r"(title|head)", layout) and not not_title(txt):
  178. levels[bullets_size].append(i)
  179. else:
  180. levels[bullets_size + 1].append(i)
  181. sections = [t for t, _ in sections]
  182. # for s in sections: print("--", s)
  183. def binary_search(arr, target):
  184. if not arr:
  185. return -1
  186. if target > arr[-1]:
  187. return len(arr) - 1
  188. if target < arr[0]:
  189. return -1
  190. s, e = 0, len(arr)
  191. while e - s > 1:
  192. i = (e + s) // 2
  193. if target > arr[i]:
  194. s = i
  195. continue
  196. elif target < arr[i]:
  197. e = i
  198. continue
  199. else:
  200. assert False
  201. return s
  202. cks = []
  203. readed = [False] * len(sections)
  204. levels = levels[::-1]
  205. for i, arr in enumerate(levels[:depth]):
  206. for j in arr:
  207. if readed[j]:
  208. continue
  209. readed[j] = True
  210. cks.append([j])
  211. if i + 1 == len(levels) - 1:
  212. continue
  213. for ii in range(i + 1, len(levels)):
  214. jj = binary_search(levels[ii], j)
  215. if jj < 0:
  216. continue
  217. if jj > cks[-1][-1]:
  218. cks[-1].pop(-1)
  219. cks[-1].append(levels[ii][jj])
  220. for ii in cks[-1]:
  221. readed[ii] = True
  222. if not cks:
  223. return cks
  224. for i in range(len(cks)):
  225. cks[i] = [sections[j] for j in cks[i][::-1]]
  226. print("--------------\n", "\n* ".join(cks[i]))
  227. res = [[]]
  228. num = [0]
  229. for ck in cks:
  230. if len(ck) == 1:
  231. n = num_tokens_from_string(re.sub(r"@@[0-9]+.*", "", ck[0]))
  232. if n + num[-1] < 218:
  233. res[-1].append(ck[0])
  234. num[-1] += n
  235. continue
  236. res.append(ck)
  237. num.append(n)
  238. continue
  239. res.append(ck)
  240. num.append(218)
  241. return res
  242. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  243. if not sections:
  244. return []
  245. if isinstance(sections[0], type("")):
  246. sections = [(s, "") for s in sections]
  247. cks = [""]
  248. tk_nums = [0]
  249. def add_chunk(t, pos):
  250. nonlocal cks, tk_nums, delimiter
  251. tnum = num_tokens_from_string(t)
  252. if tnum < 8:
  253. pos = ""
  254. if tk_nums[-1] > chunk_token_num:
  255. if t.find(pos) < 0:
  256. t += pos
  257. cks.append(t)
  258. tk_nums.append(tnum)
  259. else:
  260. if cks[-1].find(pos) < 0:
  261. t += pos
  262. cks[-1] += t
  263. tk_nums[-1] += tnum
  264. for sec, pos in sections:
  265. add_chunk(sec, pos)
  266. continue
  267. s, e = 0, 1
  268. while e < len(sec):
  269. if sec[e] in delimiter:
  270. add_chunk(sec[s: e + 1], pos)
  271. s = e + 1
  272. e = s + 1
  273. else:
  274. e += 1
  275. if s < e:
  276. add_chunk(sec[s: e], pos)
  277. return cks