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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import random
  17. from collections import Counter
  18. from rag.utils import num_tokens_from_string
  19. from . import rag_tokenizer
  20. import re
  21. import copy
  22. all_codecs = [
  23. 'utf-8', 'gb2312', 'gbk', 'utf_16', 'ascii', 'big5', 'big5hkscs',
  24. 'cp037', 'cp273', 'cp424', 'cp437',
  25. 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857',
  26. 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869',
  27. 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1125',
  28. 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256',
  29. 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr',
  30. 'gb2312', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2',
  31. 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1',
  32. 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7',
  33. 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13',
  34. 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_t', 'koi8_u',
  35. 'kz1048', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman',
  36. 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213',
  37. 'utf_32', 'utf_32_be', 'utf_32_le''utf_16_be', 'utf_16_le', 'utf_7'
  38. ]
  39. def find_codec(blob):
  40. global all_codecs
  41. for c in all_codecs:
  42. try:
  43. blob[:1024].decode(c)
  44. return c
  45. except Exception as e:
  46. pass
  47. try:
  48. blob.decode(c)
  49. return c
  50. except Exception as e:
  51. pass
  52. return "utf-8"
  53. BULLET_PATTERN = [[
  54. r"第[零一二三四五六七八九十百0-9]+(分?编|部分)",
  55. r"第[零一二三四五六七八九十百0-9]+章",
  56. r"第[零一二三四五六七八九十百0-9]+节",
  57. r"第[零一二三四五六七八九十百0-9]+条",
  58. r"[\((][零一二三四五六七八九十百]+[\))]",
  59. ], [
  60. r"第[0-9]+章",
  61. r"第[0-9]+节",
  62. r"[0-9]{,2}[\. 、]",
  63. r"[0-9]{,2}\.[0-9]{,2}[^a-zA-Z/%~-]",
  64. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  65. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  66. ], [
  67. r"第[零一二三四五六七八九十百0-9]+章",
  68. r"第[零一二三四五六七八九十百0-9]+节",
  69. r"[零一二三四五六七八九十百]+[ 、]",
  70. r"[\((][零一二三四五六七八九十百]+[\))]",
  71. r"[\((][0-9]{,2}[\))]",
  72. ], [
  73. r"PART (ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)",
  74. r"Chapter (I+V?|VI*|XI|IX|X)",
  75. r"Section [0-9]+",
  76. r"Article [0-9]+"
  77. ]
  78. ]
  79. def random_choices(arr, k):
  80. k = min(len(arr), k)
  81. return random.choices(arr, k=k)
  82. def not_bullet(line):
  83. patt = [
  84. r"0", r"[0-9]+ +[0-9~个只-]", r"[0-9]+\.{2,}"
  85. ]
  86. return any([re.match(r, line) for r in patt])
  87. def bullets_category(sections):
  88. global BULLET_PATTERN
  89. hits = [0] * len(BULLET_PATTERN)
  90. for i, pro in enumerate(BULLET_PATTERN):
  91. for sec in sections:
  92. for p in pro:
  93. if re.match(p, sec) and not not_bullet(sec):
  94. hits[i] += 1
  95. break
  96. maxium = 0
  97. res = -1
  98. for i, h in enumerate(hits):
  99. if h <= maxium:
  100. continue
  101. res = i
  102. maxium = h
  103. return res
  104. def is_english(texts):
  105. eng = 0
  106. if not texts: return False
  107. for t in texts:
  108. if re.match(r"[a-zA-Z]{2,}", t.strip()):
  109. eng += 1
  110. if eng / len(texts) > 0.8:
  111. return True
  112. return False
  113. def tokenize(d, t, eng):
  114. d["content_with_weight"] = t
  115. t = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", t)
  116. d["content_ltks"] = rag_tokenizer.tokenize(t)
  117. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  118. def tokenize_chunks(chunks, doc, eng, pdf_parser):
  119. res = []
  120. # wrap up as es documents
  121. for ck in chunks:
  122. if len(ck.strip()) == 0:continue
  123. print("--", ck)
  124. d = copy.deepcopy(doc)
  125. if pdf_parser:
  126. try:
  127. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  128. add_positions(d, poss)
  129. ck = pdf_parser.remove_tag(ck)
  130. except NotImplementedError as e:
  131. pass
  132. tokenize(d, ck, eng)
  133. res.append(d)
  134. return res
  135. def tokenize_table(tbls, doc, eng, batch_size=10):
  136. res = []
  137. # add tables
  138. for (img, rows), poss in tbls:
  139. if not rows:
  140. continue
  141. if isinstance(rows, str):
  142. d = copy.deepcopy(doc)
  143. tokenize(d, rows, eng)
  144. d["content_with_weight"] = rows
  145. if img: d["image"] = img
  146. if poss: add_positions(d, poss)
  147. res.append(d)
  148. continue
  149. de = "; " if eng else "; "
  150. for i in range(0, len(rows), batch_size):
  151. d = copy.deepcopy(doc)
  152. r = de.join(rows[i:i + batch_size])
  153. tokenize(d, r, eng)
  154. d["image"] = img
  155. add_positions(d, poss)
  156. res.append(d)
  157. return res
  158. def add_positions(d, poss):
  159. if not poss:
  160. return
  161. d["page_num_int"] = []
  162. d["position_int"] = []
  163. d["top_int"] = []
  164. for pn, left, right, top, bottom in poss:
  165. d["page_num_int"].append(int(pn + 1))
  166. d["top_int"].append(int(top))
  167. d["position_int"].append((int(pn + 1), int(left), int(right), int(top), int(bottom)))
  168. def remove_contents_table(sections, eng=False):
  169. i = 0
  170. while i < len(sections):
  171. def get(i):
  172. nonlocal sections
  173. return (sections[i] if isinstance(sections[i],
  174. type("")) else sections[i][0]).strip()
  175. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  176. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  177. i += 1
  178. continue
  179. sections.pop(i)
  180. if i >= len(sections):
  181. break
  182. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  183. while not prefix:
  184. sections.pop(i)
  185. if i >= len(sections):
  186. break
  187. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  188. sections.pop(i)
  189. if i >= len(sections) or not prefix:
  190. break
  191. for j in range(i, min(i + 128, len(sections))):
  192. if not re.match(prefix, get(j)):
  193. continue
  194. for _ in range(i, j):
  195. sections.pop(i)
  196. break
  197. def make_colon_as_title(sections):
  198. if not sections:
  199. return []
  200. if isinstance(sections[0], type("")):
  201. return sections
  202. i = 0
  203. while i < len(sections):
  204. txt, layout = sections[i]
  205. i += 1
  206. txt = txt.split("@")[0].strip()
  207. if not txt:
  208. continue
  209. if txt[-1] not in "::":
  210. continue
  211. txt = txt[::-1]
  212. arr = re.split(r"([。?!!?;;]| .)", txt)
  213. if len(arr) < 2 or len(arr[1]) < 32:
  214. continue
  215. sections.insert(i - 1, (arr[0][::-1], "title"))
  216. i += 1
  217. def title_frequency(bull, sections):
  218. bullets_size = len(BULLET_PATTERN[bull])
  219. levels = [bullets_size+1 for _ in range(len(sections))]
  220. if not sections or bull < 0:
  221. return bullets_size+1, levels
  222. for i, (txt, layout) in enumerate(sections):
  223. for j, p in enumerate(BULLET_PATTERN[bull]):
  224. if re.match(p, txt.strip()) and not not_bullet(txt):
  225. levels[i] = j
  226. break
  227. else:
  228. if re.search(r"(title|head)", layout) and not not_title(txt.split("@")[0]):
  229. levels[i] = bullets_size
  230. most_level = bullets_size+1
  231. for l, c in sorted(Counter(levels).items(), key=lambda x:x[1]*-1):
  232. if l <= bullets_size:
  233. most_level = l
  234. break
  235. return most_level, levels
  236. def not_title(txt):
  237. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
  238. return False
  239. if len(txt.split(" ")) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
  240. return True
  241. return re.search(r"[,;,。;!!]", txt)
  242. def hierarchical_merge(bull, sections, depth):
  243. if not sections or bull < 0:
  244. return []
  245. if isinstance(sections[0], type("")):
  246. sections = [(s, "") for s in sections]
  247. sections = [(t, o) for t, o in sections if
  248. t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  249. bullets_size = len(BULLET_PATTERN[bull])
  250. levels = [[] for _ in range(bullets_size + 2)]
  251. for i, (txt, layout) in enumerate(sections):
  252. for j, p in enumerate(BULLET_PATTERN[bull]):
  253. if re.match(p, txt.strip()):
  254. levels[j].append(i)
  255. break
  256. else:
  257. if re.search(r"(title|head)", layout) and not not_title(txt):
  258. levels[bullets_size].append(i)
  259. else:
  260. levels[bullets_size + 1].append(i)
  261. sections = [t for t, _ in sections]
  262. # for s in sections: print("--", s)
  263. def binary_search(arr, target):
  264. if not arr:
  265. return -1
  266. if target > arr[-1]:
  267. return len(arr) - 1
  268. if target < arr[0]:
  269. return -1
  270. s, e = 0, len(arr)
  271. while e - s > 1:
  272. i = (e + s) // 2
  273. if target > arr[i]:
  274. s = i
  275. continue
  276. elif target < arr[i]:
  277. e = i
  278. continue
  279. else:
  280. assert False
  281. return s
  282. cks = []
  283. readed = [False] * len(sections)
  284. levels = levels[::-1]
  285. for i, arr in enumerate(levels[:depth]):
  286. for j in arr:
  287. if readed[j]:
  288. continue
  289. readed[j] = True
  290. cks.append([j])
  291. if i + 1 == len(levels) - 1:
  292. continue
  293. for ii in range(i + 1, len(levels)):
  294. jj = binary_search(levels[ii], j)
  295. if jj < 0:
  296. continue
  297. if jj > cks[-1][-1]:
  298. cks[-1].pop(-1)
  299. cks[-1].append(levels[ii][jj])
  300. for ii in cks[-1]:
  301. readed[ii] = True
  302. if not cks:
  303. return cks
  304. for i in range(len(cks)):
  305. cks[i] = [sections[j] for j in cks[i][::-1]]
  306. print("--------------\n", "\n* ".join(cks[i]))
  307. res = [[]]
  308. num = [0]
  309. for ck in cks:
  310. if len(ck) == 1:
  311. n = num_tokens_from_string(re.sub(r"@@[0-9]+.*", "", ck[0]))
  312. if n + num[-1] < 218:
  313. res[-1].append(ck[0])
  314. num[-1] += n
  315. continue
  316. res.append(ck)
  317. num.append(n)
  318. continue
  319. res.append(ck)
  320. num.append(218)
  321. return res
  322. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  323. if not sections:
  324. return []
  325. if isinstance(sections[0], type("")):
  326. sections = [(s, "") for s in sections]
  327. cks = [""]
  328. tk_nums = [0]
  329. def add_chunk(t, pos):
  330. nonlocal cks, tk_nums, delimiter
  331. tnum = num_tokens_from_string(t)
  332. if tnum < 8:
  333. pos = ""
  334. if tk_nums[-1] > chunk_token_num:
  335. if t.find(pos) < 0:
  336. t += pos
  337. cks.append(t)
  338. tk_nums.append(tnum)
  339. else:
  340. if cks[-1].find(pos) < 0:
  341. t += pos
  342. cks[-1] += t
  343. tk_nums[-1] += tnum
  344. for sec, pos in sections:
  345. add_chunk(sec, pos)
  346. continue
  347. s, e = 0, 1
  348. while e < len(sec):
  349. if sec[e] in delimiter:
  350. add_chunk(sec[s: e + 1], pos)
  351. s = e + 1
  352. e = s + 1
  353. else:
  354. e += 1
  355. if s < e:
  356. add_chunk(sec[s: e], pos)
  357. return cks