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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. import roman_numbers as r
  23. from word2number import w2n
  24. from cn2an import cn2an
  25. from PIL import Image
  26. import json
  27. all_codecs = [
  28. 'utf-8', 'gb2312', 'gbk', 'utf_16', 'ascii', 'big5', 'big5hkscs',
  29. 'cp037', 'cp273', 'cp424', 'cp437',
  30. 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857',
  31. 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869',
  32. 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1125',
  33. 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256',
  34. 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr',
  35. 'gb2312', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2',
  36. 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1',
  37. 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7',
  38. 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13',
  39. 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_t', 'koi8_u',
  40. 'kz1048', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman',
  41. 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213',
  42. 'utf_32', 'utf_32_be', 'utf_32_le''utf_16_be', 'utf_16_le', 'utf_7'
  43. ]
  44. def find_codec(blob):
  45. global all_codecs
  46. for c in all_codecs:
  47. try:
  48. blob[:1024].decode(c)
  49. return c
  50. except Exception:
  51. pass
  52. try:
  53. blob.decode(c)
  54. return c
  55. except Exception:
  56. pass
  57. return "utf-8"
  58. QUESTION_PATTERN = [
  59. r"第([零一二三四五六七八九十百0-9]+)问",
  60. r"第([零一二三四五六七八九十百0-9]+)条",
  61. r"[\((]([零一二三四五六七八九十百]+)[\))]",
  62. r"第([0-9]+)问",
  63. r"第([0-9]+)条",
  64. r"([0-9]{1,2})[\. 、]",
  65. r"([零一二三四五六七八九十百]+)[ 、]",
  66. r"[\((]([0-9]{1,2})[\))]",
  67. r"QUESTION (ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)",
  68. r"QUESTION (I+V?|VI*|XI|IX|X)",
  69. r"QUESTION ([0-9]+)",
  70. ]
  71. def has_qbullet(reg, box, last_box, last_index, last_bull, bull_x0_list):
  72. section, last_section = box['text'], last_box['text']
  73. q_reg = r'(\w|\W)*?(?:?|\?|\n|$)+'
  74. full_reg = reg + q_reg
  75. has_bull = re.match(full_reg, section)
  76. index_str = None
  77. if has_bull:
  78. if 'x0' not in last_box:
  79. last_box['x0'] = box['x0']
  80. if 'top' not in last_box:
  81. last_box['top'] = box['top']
  82. if last_bull and box['x0']-last_box['x0']>10:
  83. return None, last_index
  84. if not last_bull and box['x0'] >= last_box['x0'] and box['top'] - last_box['top'] < 20:
  85. return None, last_index
  86. avg_bull_x0 = 0
  87. if bull_x0_list:
  88. avg_bull_x0 = sum(bull_x0_list) / len(bull_x0_list)
  89. else:
  90. avg_bull_x0 = box['x0']
  91. if box['x0'] - avg_bull_x0 > 10:
  92. return None, last_index
  93. index_str = has_bull.group(1)
  94. index = index_int(index_str)
  95. if last_section[-1] == ':' or last_section[-1] == ':':
  96. return None, last_index
  97. if not last_index or index >= last_index:
  98. bull_x0_list.append(box['x0'])
  99. return has_bull, index
  100. if section[-1] == '?' or section[-1] == '?':
  101. bull_x0_list.append(box['x0'])
  102. return has_bull, index
  103. if box['layout_type'] == 'title':
  104. bull_x0_list.append(box['x0'])
  105. return has_bull, index
  106. pure_section = section.lstrip(re.match(reg, section).group()).lower()
  107. ask_reg = r'(what|when|where|how|why|which|who|whose|为什么|为啥|哪)'
  108. if re.match(ask_reg, pure_section):
  109. bull_x0_list.append(box['x0'])
  110. return has_bull, index
  111. return None, last_index
  112. def index_int(index_str):
  113. res = -1
  114. try:
  115. res=int(index_str)
  116. except ValueError:
  117. try:
  118. res=w2n.word_to_num(index_str)
  119. except ValueError:
  120. try:
  121. res = cn2an(index_str)
  122. except ValueError:
  123. try:
  124. res = r.number(index_str)
  125. except ValueError:
  126. return -1
  127. return res
  128. def qbullets_category(sections):
  129. global QUESTION_PATTERN
  130. hits = [0] * len(QUESTION_PATTERN)
  131. for i, pro in enumerate(QUESTION_PATTERN):
  132. for sec in sections:
  133. if re.match(pro, sec) and not not_bullet(sec):
  134. hits[i] += 1
  135. break
  136. maxium = 0
  137. res = -1
  138. for i, h in enumerate(hits):
  139. if h <= maxium:
  140. continue
  141. res = i
  142. maxium = h
  143. return res, QUESTION_PATTERN[res]
  144. BULLET_PATTERN = [[
  145. r"第[零一二三四五六七八九十百0-9]+(分?编|部分)",
  146. r"第[零一二三四五六七八九十百0-9]+章",
  147. r"第[零一二三四五六七八九十百0-9]+节",
  148. r"第[零一二三四五六七八九十百0-9]+条",
  149. r"[\((][零一二三四五六七八九十百]+[\))]",
  150. ], [
  151. r"第[0-9]+章",
  152. r"第[0-9]+节",
  153. r"[0-9]{,2}[\. 、]",
  154. r"[0-9]{,2}\.[0-9]{,2}[^a-zA-Z/%~-]",
  155. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  156. r"[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}\.[0-9]{,2}",
  157. ], [
  158. r"第[零一二三四五六七八九十百0-9]+章",
  159. r"第[零一二三四五六七八九十百0-9]+节",
  160. r"[零一二三四五六七八九十百]+[ 、]",
  161. r"[\((][零一二三四五六七八九十百]+[\))]",
  162. r"[\((][0-9]{,2}[\))]",
  163. ], [
  164. r"PART (ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)",
  165. r"Chapter (I+V?|VI*|XI|IX|X)",
  166. r"Section [0-9]+",
  167. r"Article [0-9]+"
  168. ]
  169. ]
  170. def random_choices(arr, k):
  171. k = min(len(arr), k)
  172. return random.choices(arr, k=k)
  173. def not_bullet(line):
  174. patt = [
  175. r"0", r"[0-9]+ +[0-9~个只-]", r"[0-9]+\.{2,}"
  176. ]
  177. return any([re.match(r, line) for r in patt])
  178. def bullets_category(sections):
  179. global BULLET_PATTERN
  180. hits = [0] * len(BULLET_PATTERN)
  181. for i, pro in enumerate(BULLET_PATTERN):
  182. for sec in sections:
  183. for p in pro:
  184. if re.match(p, sec) and not not_bullet(sec):
  185. hits[i] += 1
  186. break
  187. maxium = 0
  188. res = -1
  189. for i, h in enumerate(hits):
  190. if h <= maxium:
  191. continue
  192. res = i
  193. maxium = h
  194. return res
  195. def is_english(texts):
  196. eng = 0
  197. if not texts: return False
  198. for t in texts:
  199. if re.match(r"[ `a-zA-Z.,':;/\"?<>!\(\)-]", t.strip()):
  200. eng += 1
  201. if eng / len(texts) > 0.8:
  202. return True
  203. return False
  204. def tokenize(d, t, eng):
  205. d["content_with_weight"] = t
  206. t = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", t)
  207. d["content_ltks"] = rag_tokenizer.tokenize(t)
  208. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  209. def tokenize_chunks(chunks, doc, eng, pdf_parser=None):
  210. res = []
  211. # wrap up as es documents
  212. for ck in chunks:
  213. if len(ck.strip()) == 0:continue
  214. print("--", ck)
  215. d = copy.deepcopy(doc)
  216. if pdf_parser:
  217. try:
  218. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  219. add_positions(d, poss)
  220. ck = pdf_parser.remove_tag(ck)
  221. except NotImplementedError:
  222. pass
  223. tokenize(d, ck, eng)
  224. res.append(d)
  225. return res
  226. def tokenize_chunks_docx(chunks, doc, eng, images):
  227. res = []
  228. # wrap up as es documents
  229. for ck, image in zip(chunks, images):
  230. if len(ck.strip()) == 0:continue
  231. print("--", ck)
  232. d = copy.deepcopy(doc)
  233. d["image"] = image
  234. tokenize(d, ck, eng)
  235. res.append(d)
  236. return res
  237. def tokenize_table(tbls, doc, eng, batch_size=10):
  238. res = []
  239. # add tables
  240. for (img, rows), poss in tbls:
  241. if not rows:
  242. continue
  243. if isinstance(rows, str):
  244. d = copy.deepcopy(doc)
  245. tokenize(d, rows, eng)
  246. d["content_with_weight"] = rows
  247. if img: d["image"] = img
  248. if poss: add_positions(d, poss)
  249. res.append(d)
  250. continue
  251. de = "; " if eng else "; "
  252. for i in range(0, len(rows), batch_size):
  253. d = copy.deepcopy(doc)
  254. r = de.join(rows[i:i + batch_size])
  255. tokenize(d, r, eng)
  256. d["image"] = img
  257. add_positions(d, poss)
  258. res.append(d)
  259. return res
  260. def add_positions(d, poss):
  261. if not poss:
  262. return
  263. page_num_list = []
  264. position_list = []
  265. top_list = []
  266. for pn, left, right, top, bottom in poss:
  267. page_num_list.append(int(pn + 1))
  268. top_list.append(int(top))
  269. position_list.append((int(pn + 1), int(left), int(right), int(top), int(bottom)))
  270. d["page_num_list"] = json.dumps(page_num_list)
  271. d["position_list"] = json.dumps(position_list)
  272. d["top_list"] = json.dumps(top_list)
  273. def remove_contents_table(sections, eng=False):
  274. i = 0
  275. while i < len(sections):
  276. def get(i):
  277. nonlocal sections
  278. return (sections[i] if isinstance(sections[i],
  279. type("")) else sections[i][0]).strip()
  280. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  281. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  282. i += 1
  283. continue
  284. sections.pop(i)
  285. if i >= len(sections):
  286. break
  287. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  288. while not prefix:
  289. sections.pop(i)
  290. if i >= len(sections):
  291. break
  292. prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
  293. sections.pop(i)
  294. if i >= len(sections) or not prefix:
  295. break
  296. for j in range(i, min(i + 128, len(sections))):
  297. if not re.match(prefix, get(j)):
  298. continue
  299. for _ in range(i, j):
  300. sections.pop(i)
  301. break
  302. def make_colon_as_title(sections):
  303. if not sections:
  304. return []
  305. if isinstance(sections[0], type("")):
  306. return sections
  307. i = 0
  308. while i < len(sections):
  309. txt, layout = sections[i]
  310. i += 1
  311. txt = txt.split("@")[0].strip()
  312. if not txt:
  313. continue
  314. if txt[-1] not in "::":
  315. continue
  316. txt = txt[::-1]
  317. arr = re.split(r"([。?!!?;;]| \.)", txt)
  318. if len(arr) < 2 or len(arr[1]) < 32:
  319. continue
  320. sections.insert(i - 1, (arr[0][::-1], "title"))
  321. i += 1
  322. def title_frequency(bull, sections):
  323. bullets_size = len(BULLET_PATTERN[bull])
  324. levels = [bullets_size+1 for _ in range(len(sections))]
  325. if not sections or bull < 0:
  326. return bullets_size+1, levels
  327. for i, (txt, layout) in enumerate(sections):
  328. for j, p in enumerate(BULLET_PATTERN[bull]):
  329. if re.match(p, txt.strip()) and not not_bullet(txt):
  330. levels[i] = j
  331. break
  332. else:
  333. if re.search(r"(title|head)", layout) and not not_title(txt.split("@")[0]):
  334. levels[i] = bullets_size
  335. most_level = bullets_size+1
  336. for l, c in sorted(Counter(levels).items(), key=lambda x:x[1]*-1):
  337. if l <= bullets_size:
  338. most_level = l
  339. break
  340. return most_level, levels
  341. def not_title(txt):
  342. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
  343. return False
  344. if len(txt.split(" ")) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
  345. return True
  346. return re.search(r"[,;,。;!!]", txt)
  347. def hierarchical_merge(bull, sections, depth):
  348. if not sections or bull < 0:
  349. return []
  350. if isinstance(sections[0], type("")):
  351. sections = [(s, "") for s in sections]
  352. sections = [(t, o) for t, o in sections if
  353. t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  354. bullets_size = len(BULLET_PATTERN[bull])
  355. levels = [[] for _ in range(bullets_size + 2)]
  356. for i, (txt, layout) in enumerate(sections):
  357. for j, p in enumerate(BULLET_PATTERN[bull]):
  358. if re.match(p, txt.strip()):
  359. levels[j].append(i)
  360. break
  361. else:
  362. if re.search(r"(title|head)", layout) and not not_title(txt):
  363. levels[bullets_size].append(i)
  364. else:
  365. levels[bullets_size + 1].append(i)
  366. sections = [t for t, _ in sections]
  367. # for s in sections: print("--", s)
  368. def binary_search(arr, target):
  369. if not arr:
  370. return -1
  371. if target > arr[-1]:
  372. return len(arr) - 1
  373. if target < arr[0]:
  374. return -1
  375. s, e = 0, len(arr)
  376. while e - s > 1:
  377. i = (e + s) // 2
  378. if target > arr[i]:
  379. s = i
  380. continue
  381. elif target < arr[i]:
  382. e = i
  383. continue
  384. else:
  385. assert False
  386. return s
  387. cks = []
  388. readed = [False] * len(sections)
  389. levels = levels[::-1]
  390. for i, arr in enumerate(levels[:depth]):
  391. for j in arr:
  392. if readed[j]:
  393. continue
  394. readed[j] = True
  395. cks.append([j])
  396. if i + 1 == len(levels) - 1:
  397. continue
  398. for ii in range(i + 1, len(levels)):
  399. jj = binary_search(levels[ii], j)
  400. if jj < 0:
  401. continue
  402. if jj > cks[-1][-1]:
  403. cks[-1].pop(-1)
  404. cks[-1].append(levels[ii][jj])
  405. for ii in cks[-1]:
  406. readed[ii] = True
  407. if not cks:
  408. return cks
  409. for i in range(len(cks)):
  410. cks[i] = [sections[j] for j in cks[i][::-1]]
  411. print("--------------\n", "\n* ".join(cks[i]))
  412. res = [[]]
  413. num = [0]
  414. for ck in cks:
  415. if len(ck) == 1:
  416. n = num_tokens_from_string(re.sub(r"@@[0-9]+.*", "", ck[0]))
  417. if n + num[-1] < 218:
  418. res[-1].append(ck[0])
  419. num[-1] += n
  420. continue
  421. res.append(ck)
  422. num.append(n)
  423. continue
  424. res.append(ck)
  425. num.append(218)
  426. return res
  427. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  428. if not sections:
  429. return []
  430. if isinstance(sections[0], type("")):
  431. sections = [(s, "") for s in sections]
  432. cks = [""]
  433. tk_nums = [0]
  434. def add_chunk(t, pos):
  435. nonlocal cks, tk_nums, delimiter
  436. tnum = num_tokens_from_string(t)
  437. if not pos: pos = ""
  438. if tnum < 8:
  439. pos = ""
  440. # Ensure that the length of the merged chunk does not exceed chunk_token_num
  441. if tk_nums[-1] > chunk_token_num:
  442. if t.find(pos) < 0:
  443. t += pos
  444. cks.append(t)
  445. tk_nums.append(tnum)
  446. else:
  447. if cks[-1].find(pos) < 0:
  448. t += pos
  449. cks[-1] += t
  450. tk_nums[-1] += tnum
  451. for sec, pos in sections:
  452. add_chunk(sec, pos)
  453. return cks
  454. def docx_question_level(p, bull = -1):
  455. txt = re.sub(r"\u3000", " ", p.text).strip()
  456. if p.style.name.startswith('Heading'):
  457. return int(p.style.name.split(' ')[-1]), txt
  458. else:
  459. if bull < 0:
  460. return 0, txt
  461. for j, title in enumerate(BULLET_PATTERN[bull]):
  462. if re.match(title, txt):
  463. return j+1, txt
  464. return len(BULLET_PATTERN[bull]), txt
  465. def concat_img(img1, img2):
  466. if img1 and not img2:
  467. return img1
  468. if not img1 and img2:
  469. return img2
  470. if not img1 and not img2:
  471. return None
  472. width1, height1 = img1.size
  473. width2, height2 = img2.size
  474. new_width = max(width1, width2)
  475. new_height = height1 + height2
  476. new_image = Image.new('RGB', (new_width, new_height))
  477. new_image.paste(img1, (0, 0))
  478. new_image.paste(img2, (0, height1))
  479. return new_image
  480. def naive_merge_docx(sections, chunk_token_num=128, delimiter="\n。;!?"):
  481. if not sections:
  482. return [], []
  483. cks = [""]
  484. images = [None]
  485. tk_nums = [0]
  486. def add_chunk(t, image, pos=""):
  487. nonlocal cks, tk_nums, delimiter
  488. tnum = num_tokens_from_string(t)
  489. if tnum < 8:
  490. pos = ""
  491. if tk_nums[-1] > chunk_token_num:
  492. if t.find(pos) < 0:
  493. t += pos
  494. cks.append(t)
  495. images.append(image)
  496. tk_nums.append(tnum)
  497. else:
  498. if cks[-1].find(pos) < 0:
  499. t += pos
  500. cks[-1] += t
  501. images[-1] = concat_img(images[-1], image)
  502. tk_nums[-1] += tnum
  503. for sec, image in sections:
  504. add_chunk(sec, image, '')
  505. return cks, images