Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

__init__.py 17KB

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