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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. def remove_contents_table(sections, eng=False):
  107. i = 0
  108. while i < len(sections):
  109. def get(i):
  110. nonlocal sections
  111. return (sections[i] if isinstance(sections[i],
  112. type("")) else sections[i][0]).strip()
  113. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  114. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  115. i += 1
  116. continue
  117. sections.pop(i)
  118. if i >= len(sections):
  119. break
  120. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  121. while not prefix:
  122. sections.pop(i)
  123. if i >= len(sections):
  124. break
  125. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  126. sections.pop(i)
  127. if i >= len(sections) or not prefix:
  128. break
  129. for j in range(i, min(i + 128, len(sections))):
  130. if not re.match(prefix, get(j)):
  131. continue
  132. for _ in range(i, j):
  133. sections.pop(i)
  134. break
  135. def make_colon_as_title(sections):
  136. if not sections:
  137. return []
  138. if isinstance(sections[0], type("")):
  139. return sections
  140. i = 0
  141. while i < len(sections):
  142. txt, layout = sections[i]
  143. i += 1
  144. txt = txt.split("@")[0].strip()
  145. if not txt:
  146. continue
  147. if txt[-1] not in "::":
  148. continue
  149. txt = txt[::-1]
  150. arr = re.split(r"([。?!!?;;]| .)", txt)
  151. if len(arr) < 2 or len(arr[1]) < 32:
  152. continue
  153. sections.insert(i - 1, (arr[0][::-1], "title"))
  154. i += 1
  155. def hierarchical_merge(bull, sections, depth):
  156. if not sections or bull < 0:
  157. return []
  158. if isinstance(sections[0], type("")):
  159. sections = [(s, "") for s in sections]
  160. sections = [(t, o) for t, o in sections if
  161. t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  162. bullets_size = len(BULLET_PATTERN[bull])
  163. levels = [[] for _ in range(bullets_size + 2)]
  164. def not_title(txt):
  165. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
  166. return False
  167. if len(txt.split(" ")) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
  168. return True
  169. return re.search(r"[,;,。;!!]", txt)
  170. for i, (txt, layout) in enumerate(sections):
  171. for j, p in enumerate(BULLET_PATTERN[bull]):
  172. if re.match(p, txt.strip()):
  173. levels[j].append(i)
  174. break
  175. else:
  176. if re.search(r"(title|head)", layout) and not not_title(txt):
  177. levels[bullets_size].append(i)
  178. else:
  179. levels[bullets_size + 1].append(i)
  180. sections = [t for t, _ in sections]
  181. # for s in sections: print("--", s)
  182. def binary_search(arr, target):
  183. if not arr:
  184. return -1
  185. if target > arr[-1]:
  186. return len(arr) - 1
  187. if target < arr[0]:
  188. return -1
  189. s, e = 0, len(arr)
  190. while e - s > 1:
  191. i = (e + s) // 2
  192. if target > arr[i]:
  193. s = i
  194. continue
  195. elif target < arr[i]:
  196. e = i
  197. continue
  198. else:
  199. assert False
  200. return s
  201. cks = []
  202. readed = [False] * len(sections)
  203. levels = levels[::-1]
  204. for i, arr in enumerate(levels[:depth]):
  205. for j in arr:
  206. if readed[j]:
  207. continue
  208. readed[j] = True
  209. cks.append([j])
  210. if i + 1 == len(levels) - 1:
  211. continue
  212. for ii in range(i + 1, len(levels)):
  213. jj = binary_search(levels[ii], j)
  214. if jj < 0:
  215. continue
  216. if jj > cks[-1][-1]:
  217. cks[-1].pop(-1)
  218. cks[-1].append(levels[ii][jj])
  219. for ii in cks[-1]:
  220. readed[ii] = True
  221. if not cks:
  222. return cks
  223. for i in range(len(cks)):
  224. cks[i] = [sections[j] for j in cks[i][::-1]]
  225. print("--------------\n", "\n* ".join(cks[i]))
  226. res = [[]]
  227. num = [0]
  228. for ck in cks:
  229. if len(ck) == 1:
  230. n = num_tokens_from_string(re.sub(r"@@[0-9]+.*", "", ck[0]))
  231. if n + num[-1] < 218:
  232. res[-1].append(ck[0])
  233. num[-1] += n
  234. continue
  235. res.append(ck)
  236. num.append(n)
  237. continue
  238. res.append(ck)
  239. num.append(218)
  240. return res
  241. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  242. if not sections:
  243. return []
  244. if isinstance(sections[0], type("")):
  245. sections = [(s, "") for s in sections]
  246. cks = [""]
  247. tk_nums = [0]
  248. def add_chunk(t, pos):
  249. nonlocal cks, tk_nums, delimiter
  250. tnum = num_tokens_from_string(t)
  251. if tnum < 8:
  252. pos = ""
  253. if tk_nums[-1] > chunk_token_num:
  254. if t.find(pos) < 0:
  255. t += pos
  256. cks.append(t)
  257. tk_nums.append(tnum)
  258. else:
  259. if cks[-1].find(pos) < 0:
  260. t += pos
  261. cks[-1] += t
  262. tk_nums[-1] += tnum
  263. for sec, pos in sections:
  264. add_chunk(sec, pos)
  265. continue
  266. s, e = 0, 1
  267. while e < len(sec):
  268. if sec[e] in delimiter:
  269. add_chunk(sec[s: e + 1], pos)
  270. s = e + 1
  271. e = s + 1
  272. else:
  273. e += 1
  274. if s < e:
  275. add_chunk(sec[s: e], pos)
  276. return cks