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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import random
  2. from collections import Counter
  3. from rag.utils import num_tokens_from_string
  4. from . import huqie
  5. import re
  6. import copy
  7. BULLET_PATTERN = [[
  8. r"第[零一二三四五六七八九十百0-9]+(分?编|部分)",
  9. r"第[零一二三四五六七八九十百0-9]+章",
  10. r"第[零一二三四五六七八九十百0-9]+节",
  11. r"第[零一二三四五六七八九十百0-9]+条",
  12. r"[\((][零一二三四五六七八九十百]+[\))]",
  13. ], [
  14. r"第[0-9]+章",
  15. r"第[0-9]+节",
  16. r"[0-9]{,3}[\. 、]",
  17. r"[0-9]{,2}\.[0-9]{,2}",
  18. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  19. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  20. ], [
  21. r"第[零一二三四五六七八九十百0-9]+章",
  22. r"第[零一二三四五六七八九十百0-9]+节",
  23. r"[零一二三四五六七八九十百]+[ 、]",
  24. r"[\((][零一二三四五六七八九十百]+[\))]",
  25. r"[\((][0-9]{,2}[\))]",
  26. ], [
  27. r"PART (ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)",
  28. r"Chapter (I+V?|VI*|XI|IX|X)",
  29. r"Section [0-9]+",
  30. r"Article [0-9]+"
  31. ]
  32. ]
  33. def random_choices(arr, k):
  34. k = min(len(arr), k)
  35. return random.choices(arr, k=k)
  36. def bullets_category(sections):
  37. global BULLET_PATTERN
  38. hits = [0] * len(BULLET_PATTERN)
  39. for i, pro in enumerate(BULLET_PATTERN):
  40. for sec in sections:
  41. for p in pro:
  42. if re.match(p, sec):
  43. hits[i] += 1
  44. break
  45. maxium = 0
  46. res = -1
  47. for i, h in enumerate(hits):
  48. if h <= maxium:
  49. 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. t = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", t)
  64. d["content_ltks"] = huqie.qie(t)
  65. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  66. def tokenize_chunks(chunks, doc, eng, pdf_parser):
  67. res = []
  68. # wrap up as es documents
  69. for ck in chunks:
  70. if len(ck.strip()) == 0:continue
  71. print("--", ck)
  72. d = copy.deepcopy(doc)
  73. if pdf_parser:
  74. try:
  75. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  76. add_positions(d, poss)
  77. ck = pdf_parser.remove_tag(ck)
  78. except NotImplementedError as e:
  79. pass
  80. tokenize(d, ck, eng)
  81. res.append(d)
  82. return res
  83. def tokenize_table(tbls, doc, eng, batch_size=10):
  84. res = []
  85. # add tables
  86. for (img, rows), poss in tbls:
  87. if not rows:
  88. continue
  89. if isinstance(rows, str):
  90. d = copy.deepcopy(doc)
  91. tokenize(d, rows, eng)
  92. d["content_with_weight"] = rows
  93. d["image"] = img
  94. add_positions(d, poss)
  95. res.append(d)
  96. continue
  97. de = "; " if eng else "; "
  98. for i in range(0, len(rows), batch_size):
  99. d = copy.deepcopy(doc)
  100. r = de.join(rows[i:i + batch_size])
  101. tokenize(d, r, eng)
  102. d["image"] = img
  103. add_positions(d, poss)
  104. res.append(d)
  105. return res
  106. def add_positions(d, poss):
  107. if not poss:
  108. return
  109. d["page_num_int"] = []
  110. d["position_int"] = []
  111. d["top_int"] = []
  112. for pn, left, right, top, bottom in poss:
  113. d["page_num_int"].append(pn + 1)
  114. d["top_int"].append(top)
  115. d["position_int"].append((pn + 1, left, right, top, bottom))
  116. def remove_contents_table(sections, eng=False):
  117. i = 0
  118. while i < len(sections):
  119. def get(i):
  120. nonlocal sections
  121. return (sections[i] if isinstance(sections[i],
  122. type("")) else sections[i][0]).strip()
  123. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  124. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  125. i += 1
  126. continue
  127. sections.pop(i)
  128. if i >= len(sections):
  129. break
  130. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  131. while not prefix:
  132. sections.pop(i)
  133. if i >= len(sections):
  134. break
  135. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  136. sections.pop(i)
  137. if i >= len(sections) or not prefix:
  138. break
  139. for j in range(i, min(i + 128, len(sections))):
  140. if not re.match(prefix, get(j)):
  141. continue
  142. for _ in range(i, j):
  143. sections.pop(i)
  144. break
  145. def make_colon_as_title(sections):
  146. if not sections:
  147. return []
  148. if isinstance(sections[0], type("")):
  149. return sections
  150. i = 0
  151. while i < len(sections):
  152. txt, layout = sections[i]
  153. i += 1
  154. txt = txt.split("@")[0].strip()
  155. if not txt:
  156. continue
  157. if txt[-1] not in "::":
  158. continue
  159. txt = txt[::-1]
  160. arr = re.split(r"([。?!!?;;]| .)", txt)
  161. if len(arr) < 2 or len(arr[1]) < 32:
  162. continue
  163. sections.insert(i - 1, (arr[0][::-1], "title"))
  164. i += 1
  165. def title_frequency(bull, sections):
  166. bullets_size = len(BULLET_PATTERN[bull])
  167. levels = [bullets_size+1 for _ in range(len(sections))]
  168. if not sections or bull < 0:
  169. return bullets_size+1, levels
  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[i] = j
  174. break
  175. else:
  176. if re.search(r"(title|head)", layout) and not not_title(txt.split("@")[0]):
  177. levels[i] = bullets_size
  178. most_level = bullets_size+1
  179. for l, c in sorted(Counter(levels).items(), key=lambda x:x[1]*-1):
  180. if l <= bullets_size:
  181. most_level = l
  182. break
  183. return most_level, levels
  184. def not_title(txt):
  185. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
  186. return False
  187. if len(txt.split(" ")) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
  188. return True
  189. return re.search(r"[,;,。;!!]", txt)
  190. def hierarchical_merge(bull, sections, depth):
  191. if not sections or bull < 0:
  192. return []
  193. if isinstance(sections[0], type("")):
  194. sections = [(s, "") for s in sections]
  195. sections = [(t, o) for t, o in sections if
  196. t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  197. bullets_size = len(BULLET_PATTERN[bull])
  198. levels = [[] for _ in range(bullets_size + 2)]
  199. for i, (txt, layout) in enumerate(sections):
  200. for j, p in enumerate(BULLET_PATTERN[bull]):
  201. if re.match(p, txt.strip()):
  202. levels[j].append(i)
  203. break
  204. else:
  205. if re.search(r"(title|head)", layout) and not not_title(txt):
  206. levels[bullets_size].append(i)
  207. else:
  208. levels[bullets_size + 1].append(i)
  209. sections = [t for t, _ in sections]
  210. # for s in sections: print("--", s)
  211. def binary_search(arr, target):
  212. if not arr:
  213. return -1
  214. if target > arr[-1]:
  215. return len(arr) - 1
  216. if target < arr[0]:
  217. return -1
  218. s, e = 0, len(arr)
  219. while e - s > 1:
  220. i = (e + s) // 2
  221. if target > arr[i]:
  222. s = i
  223. continue
  224. elif target < arr[i]:
  225. e = i
  226. continue
  227. else:
  228. assert False
  229. return s
  230. cks = []
  231. readed = [False] * len(sections)
  232. levels = levels[::-1]
  233. for i, arr in enumerate(levels[:depth]):
  234. for j in arr:
  235. if readed[j]:
  236. continue
  237. readed[j] = True
  238. cks.append([j])
  239. if i + 1 == len(levels) - 1:
  240. continue
  241. for ii in range(i + 1, len(levels)):
  242. jj = binary_search(levels[ii], j)
  243. if jj < 0:
  244. continue
  245. if jj > cks[-1][-1]:
  246. cks[-1].pop(-1)
  247. cks[-1].append(levels[ii][jj])
  248. for ii in cks[-1]:
  249. readed[ii] = True
  250. if not cks:
  251. return cks
  252. for i in range(len(cks)):
  253. cks[i] = [sections[j] for j in cks[i][::-1]]
  254. print("--------------\n", "\n* ".join(cks[i]))
  255. res = [[]]
  256. num = [0]
  257. for ck in cks:
  258. if len(ck) == 1:
  259. n = num_tokens_from_string(re.sub(r"@@[0-9]+.*", "", ck[0]))
  260. if n + num[-1] < 218:
  261. res[-1].append(ck[0])
  262. num[-1] += n
  263. continue
  264. res.append(ck)
  265. num.append(n)
  266. continue
  267. res.append(ck)
  268. num.append(218)
  269. return res
  270. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  271. if not sections:
  272. return []
  273. if isinstance(sections[0], type("")):
  274. sections = [(s, "") for s in sections]
  275. cks = [""]
  276. tk_nums = [0]
  277. def add_chunk(t, pos):
  278. nonlocal cks, tk_nums, delimiter
  279. tnum = num_tokens_from_string(t)
  280. if tnum < 8:
  281. pos = ""
  282. if tk_nums[-1] > chunk_token_num:
  283. if t.find(pos) < 0:
  284. t += pos
  285. cks.append(t)
  286. tk_nums.append(tnum)
  287. else:
  288. if cks[-1].find(pos) < 0:
  289. t += pos
  290. cks[-1] += t
  291. tk_nums[-1] += tnum
  292. for sec, pos in sections:
  293. add_chunk(sec, pos)
  294. continue
  295. s, e = 0, 1
  296. while e < len(sec):
  297. if sec[e] in delimiter:
  298. add_chunk(sec[s: e + 1], pos)
  299. s = e + 1
  300. e = s + 1
  301. else:
  302. e += 1
  303. if s < e:
  304. add_chunk(sec[s: e], pos)
  305. return cks