Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

__init__.py 16KB

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