您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

__init__.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. '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. if not text:
  212. return False
  213. chinese = 0
  214. for ch in text:
  215. if '\u4e00' <= ch <= '\u9fff':
  216. chinese += 1
  217. if chinese / len(text) > 0.2:
  218. return True
  219. return False
  220. def tokenize(d, t, eng):
  221. d["content_with_weight"] = t
  222. t = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", t)
  223. d["content_ltks"] = rag_tokenizer.tokenize(t)
  224. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  225. def tokenize_chunks(chunks, doc, eng, pdf_parser=None):
  226. res = []
  227. # wrap up as es documents
  228. for ck in chunks:
  229. if len(ck.strip()) == 0:
  230. continue
  231. logging.debug("-- {}".format(ck))
  232. d = copy.deepcopy(doc)
  233. if pdf_parser:
  234. try:
  235. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  236. add_positions(d, poss)
  237. ck = pdf_parser.remove_tag(ck)
  238. except NotImplementedError:
  239. pass
  240. tokenize(d, ck, eng)
  241. res.append(d)
  242. return res
  243. def tokenize_chunks_docx(chunks, doc, eng, images):
  244. res = []
  245. # wrap up as es documents
  246. for ck, image in zip(chunks, images):
  247. if len(ck.strip()) == 0:
  248. continue
  249. logging.debug("-- {}".format(ck))
  250. d = copy.deepcopy(doc)
  251. d["image"] = image
  252. tokenize(d, ck, eng)
  253. res.append(d)
  254. return res
  255. def tokenize_table(tbls, doc, eng, batch_size=10):
  256. res = []
  257. # add tables
  258. for (img, rows), poss in tbls:
  259. if not rows:
  260. continue
  261. if isinstance(rows, str):
  262. d = copy.deepcopy(doc)
  263. tokenize(d, rows, eng)
  264. d["content_with_weight"] = rows
  265. if img:
  266. d["image"] = img
  267. if poss:
  268. add_positions(d, poss)
  269. res.append(d)
  270. continue
  271. de = "; " if eng else "; "
  272. for i in range(0, len(rows), batch_size):
  273. d = copy.deepcopy(doc)
  274. r = de.join(rows[i:i + batch_size])
  275. tokenize(d, r, eng)
  276. d["image"] = img
  277. add_positions(d, poss)
  278. res.append(d)
  279. return res
  280. def add_positions(d, poss):
  281. if not poss:
  282. return
  283. page_num_int = []
  284. position_int = []
  285. top_int = []
  286. for pn, left, right, top, bottom in poss:
  287. page_num_int.append(int(pn + 1))
  288. top_int.append(int(top))
  289. position_int.append((int(pn + 1), int(left), int(right), int(top), int(bottom)))
  290. d["page_num_int"] = page_num_int
  291. d["position_int"] = position_int
  292. d["top_int"] = top_int
  293. def remove_contents_table(sections, eng=False):
  294. i = 0
  295. while i < len(sections):
  296. def get(i):
  297. nonlocal sections
  298. return (sections[i] if isinstance(sections[i],
  299. type("")) else sections[i][0]).strip()
  300. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
  301. re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
  302. i += 1
  303. continue
  304. sections.pop(i)
  305. if i >= len(sections):
  306. break
  307. prefix = get(i)[:3] if not eng else " ".join(get(i).split()[:2])
  308. while not prefix:
  309. sections.pop(i)
  310. if i >= len(sections):
  311. break
  312. prefix = get(i)[:3] if not eng else " ".join(get(i).split()[:2])
  313. sections.pop(i)
  314. if i >= len(sections) or not prefix:
  315. break
  316. for j in range(i, min(i + 128, len(sections))):
  317. if not re.match(prefix, get(j)):
  318. continue
  319. for _ in range(i, j):
  320. sections.pop(i)
  321. break
  322. def make_colon_as_title(sections):
  323. if not sections:
  324. return []
  325. if isinstance(sections[0], type("")):
  326. return sections
  327. i = 0
  328. while i < len(sections):
  329. txt, layout = sections[i]
  330. i += 1
  331. txt = txt.split("@")[0].strip()
  332. if not txt:
  333. continue
  334. if txt[-1] not in "::":
  335. continue
  336. txt = txt[::-1]
  337. arr = re.split(r"([。?!!?;;]| \.)", txt)
  338. if len(arr) < 2 or len(arr[1]) < 32:
  339. continue
  340. sections.insert(i - 1, (arr[0][::-1], "title"))
  341. i += 1
  342. def title_frequency(bull, sections):
  343. bullets_size = len(BULLET_PATTERN[bull])
  344. levels = [bullets_size + 1 for _ in range(len(sections))]
  345. if not sections or bull < 0:
  346. return bullets_size + 1, levels
  347. for i, (txt, layout) in enumerate(sections):
  348. for j, p in enumerate(BULLET_PATTERN[bull]):
  349. if re.match(p, txt.strip()) and not not_bullet(txt):
  350. levels[i] = j
  351. break
  352. else:
  353. if re.search(r"(title|head)", layout) and not not_title(txt.split("@")[0]):
  354. levels[i] = bullets_size
  355. most_level = bullets_size + 1
  356. for level, c in sorted(Counter(levels).items(), key=lambda x: x[1] * -1):
  357. if level <= bullets_size:
  358. most_level = level
  359. break
  360. return most_level, levels
  361. def not_title(txt):
  362. if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
  363. return False
  364. if len(txt.split()) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
  365. return True
  366. return re.search(r"[,;,。;!!]", txt)
  367. def hierarchical_merge(bull, sections, depth):
  368. if not sections or bull < 0:
  369. return []
  370. if isinstance(sections[0], type("")):
  371. sections = [(s, "") for s in sections]
  372. sections = [(t, o) for t, o in sections if
  373. t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
  374. bullets_size = len(BULLET_PATTERN[bull])
  375. levels = [[] for _ in range(bullets_size + 2)]
  376. for i, (txt, layout) in enumerate(sections):
  377. for j, p in enumerate(BULLET_PATTERN[bull]):
  378. if re.match(p, txt.strip()):
  379. levels[j].append(i)
  380. break
  381. else:
  382. if re.search(r"(title|head)", layout) and not not_title(txt):
  383. levels[bullets_size].append(i)
  384. else:
  385. levels[bullets_size + 1].append(i)
  386. sections = [t for t, _ in sections]
  387. # for s in sections: print("--", s)
  388. def binary_search(arr, target):
  389. if not arr:
  390. return -1
  391. if target > arr[-1]:
  392. return len(arr) - 1
  393. if target < arr[0]:
  394. return -1
  395. s, e = 0, len(arr)
  396. while e - s > 1:
  397. i = (e + s) // 2
  398. if target > arr[i]:
  399. s = i
  400. continue
  401. elif target < arr[i]:
  402. e = i
  403. continue
  404. else:
  405. assert False
  406. return s
  407. cks = []
  408. readed = [False] * len(sections)
  409. levels = levels[::-1]
  410. for i, arr in enumerate(levels[:depth]):
  411. for j in arr:
  412. if readed[j]:
  413. continue
  414. readed[j] = True
  415. cks.append([j])
  416. if i + 1 == len(levels) - 1:
  417. continue
  418. for ii in range(i + 1, len(levels)):
  419. jj = binary_search(levels[ii], j)
  420. if jj < 0:
  421. continue
  422. if levels[ii][jj] > cks[-1][-1]:
  423. cks[-1].pop(-1)
  424. cks[-1].append(levels[ii][jj])
  425. for ii in cks[-1]:
  426. readed[ii] = True
  427. if not cks:
  428. return cks
  429. for i in range(len(cks)):
  430. cks[i] = [sections[j] for j in cks[i][::-1]]
  431. logging.debug("\n* ".join(cks[i]))
  432. res = [[]]
  433. num = [0]
  434. for ck in cks:
  435. if len(ck) == 1:
  436. n = num_tokens_from_string(re.sub(r"@@[0-9]+.*", "", ck[0]))
  437. if n + num[-1] < 218:
  438. res[-1].append(ck[0])
  439. num[-1] += n
  440. continue
  441. res.append(ck)
  442. num.append(n)
  443. continue
  444. res.append(ck)
  445. num.append(218)
  446. return res
  447. def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
  448. if not sections:
  449. return []
  450. if isinstance(sections[0], type("")):
  451. sections = [(s, "") for s in sections]
  452. cks = [""]
  453. tk_nums = [0]
  454. def add_chunk(t, pos):
  455. nonlocal cks, tk_nums, delimiter
  456. tnum = num_tokens_from_string(t)
  457. if not pos:
  458. pos = ""
  459. if tnum < 8:
  460. pos = ""
  461. # Ensure that the length of the merged chunk does not exceed chunk_token_num
  462. if tk_nums[-1] > chunk_token_num:
  463. if t.find(pos) < 0:
  464. t += pos
  465. cks.append(t)
  466. tk_nums.append(tnum)
  467. else:
  468. if cks[-1].find(pos) < 0:
  469. t += pos
  470. cks[-1] += t
  471. tk_nums[-1] += tnum
  472. for sec, pos in sections:
  473. add_chunk(sec, pos)
  474. return cks
  475. def docx_question_level(p, bull=-1):
  476. txt = re.sub(r"\u3000", " ", p.text).strip()
  477. if p.style.name.startswith('Heading'):
  478. return int(p.style.name.split(' ')[-1]), txt
  479. else:
  480. if bull < 0:
  481. return 0, txt
  482. for j, title in enumerate(BULLET_PATTERN[bull]):
  483. if re.match(title, txt):
  484. return j + 1, txt
  485. return len(BULLET_PATTERN[bull]), txt
  486. def concat_img(img1, img2):
  487. if img1 and not img2:
  488. return img1
  489. if not img1 and img2:
  490. return img2
  491. if not img1 and not img2:
  492. return None
  493. width1, height1 = img1.size
  494. width2, height2 = img2.size
  495. new_width = max(width1, width2)
  496. new_height = height1 + height2
  497. new_image = Image.new('RGB', (new_width, new_height))
  498. new_image.paste(img1, (0, 0))
  499. new_image.paste(img2, (0, height1))
  500. return new_image
  501. def naive_merge_docx(sections, chunk_token_num=128, delimiter="\n。;!?"):
  502. if not sections:
  503. return [], []
  504. cks = [""]
  505. images = [None]
  506. tk_nums = [0]
  507. def add_chunk(t, image, pos=""):
  508. nonlocal cks, tk_nums, delimiter
  509. tnum = num_tokens_from_string(t)
  510. if tnum < 8:
  511. pos = ""
  512. if tk_nums[-1] > chunk_token_num:
  513. if t.find(pos) < 0:
  514. t += pos
  515. cks.append(t)
  516. images.append(image)
  517. tk_nums.append(tnum)
  518. else:
  519. if cks[-1].find(pos) < 0:
  520. t += pos
  521. cks[-1] += t
  522. images[-1] = concat_img(images[-1], image)
  523. tk_nums[-1] += tnum
  524. for sec, image in sections:
  525. add_chunk(sec, image, '')
  526. return cks, images
  527. def extract_between(text: str, start_tag: str, end_tag: str) -> list[str]:
  528. pattern = re.escape(start_tag) + r"(.*?)" + re.escape(end_tag)
  529. return re.findall(pattern, text, flags=re.DOTALL)