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

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