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

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