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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #
  2. # Copyright 2025 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 re
  18. import csv
  19. from copy import deepcopy
  20. from io import BytesIO
  21. from timeit import default_timer as timer
  22. from openpyxl import load_workbook
  23. from deepdoc.parser.utils import get_text
  24. from rag.nlp import is_english, random_choices, qbullets_category, add_positions, has_qbullet, docx_question_level
  25. from rag.nlp import rag_tokenizer, tokenize_table, concat_img
  26. from deepdoc.parser import PdfParser, ExcelParser, DocxParser
  27. from docx import Document
  28. from PIL import Image
  29. from markdown import markdown
  30. class Excel(ExcelParser):
  31. def __call__(self, fnm, binary=None, callback=None):
  32. if not binary:
  33. wb = load_workbook(fnm)
  34. else:
  35. wb = load_workbook(BytesIO(binary))
  36. total = 0
  37. for sheetname in wb.sheetnames:
  38. total += len(list(wb[sheetname].rows))
  39. res, fails = [], []
  40. for sheetname in wb.sheetnames:
  41. ws = wb[sheetname]
  42. rows = list(ws.rows)
  43. for i, r in enumerate(rows):
  44. q, a = "", ""
  45. for cell in r:
  46. if not cell.value:
  47. continue
  48. if not q:
  49. q = str(cell.value)
  50. elif not a:
  51. a = str(cell.value)
  52. else:
  53. break
  54. if q and a:
  55. res.append((q, a))
  56. else:
  57. fails.append(str(i + 1))
  58. if len(res) % 999 == 0:
  59. callback(len(res) *
  60. 0.6 /
  61. total, ("Extract pairs: {}".format(len(res)) +
  62. (f"{len(fails)} failure, line: %s..." %
  63. (",".join(fails[:3])) if fails else "")))
  64. callback(0.6, ("Extract pairs: {}. ".format(len(res)) + (
  65. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  66. self.is_english = is_english(
  67. [rmPrefix(q) for q, _ in random_choices(res, k=30) if len(q) > 1])
  68. return res
  69. class Pdf(PdfParser):
  70. def __call__(self, filename, binary=None, from_page=0,
  71. to_page=100000, zoomin=3, callback=None):
  72. start = timer()
  73. callback(msg="OCR started")
  74. self.__images__(
  75. filename if not binary else binary,
  76. zoomin,
  77. from_page,
  78. to_page,
  79. callback
  80. )
  81. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  82. logging.debug("OCR({}~{}): {:.2f}s".format(from_page, to_page, timer() - start))
  83. start = timer()
  84. self._layouts_rec(zoomin, drop=False)
  85. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  86. start = timer()
  87. self._table_transformer_job(zoomin)
  88. callback(0.65, "Table analysis ({:.2f}s)".format(timer() - start))
  89. start = timer()
  90. self._text_merge()
  91. callback(0.67, "Text merged ({:.2f}s)".format(timer() - start))
  92. tbls = self._extract_table_figure(True, zoomin, True, True)
  93. #self._naive_vertical_merge()
  94. # self._concat_downward()
  95. #self._filter_forpages()
  96. logging.debug("layouts: {}".format(timer() - start))
  97. sections = [b["text"] for b in self.boxes]
  98. bull_x0_list = []
  99. q_bull, reg = qbullets_category(sections)
  100. if q_bull == -1:
  101. raise ValueError("Unable to recognize Q&A structure.")
  102. qai_list = []
  103. last_q, last_a, last_tag = '', '', ''
  104. last_index = -1
  105. last_box = {'text':''}
  106. last_bull = None
  107. def sort_key(element):
  108. tbls_pn = element[1][0][0]
  109. tbls_top = element[1][0][3]
  110. return tbls_pn, tbls_top
  111. tbls.sort(key=sort_key)
  112. tbl_index = 0
  113. last_pn, last_bottom = 0, 0
  114. tbl_pn, tbl_left, tbl_right, tbl_top, tbl_bottom, tbl_tag, tbl_text = 1, 0, 0, 0, 0, '@@0\t0\t0\t0\t0##', ''
  115. for box in self.boxes:
  116. section, line_tag = box['text'], self._line_tag(box, zoomin)
  117. has_bull, index = has_qbullet(reg, box, last_box, last_index, last_bull, bull_x0_list)
  118. last_box, last_index, last_bull = box, index, has_bull
  119. line_pn = float(line_tag.lstrip('@@').split('\t')[0])
  120. line_top = float(line_tag.rstrip('##').split('\t')[3])
  121. tbl_pn, tbl_left, tbl_right, tbl_top, tbl_bottom, tbl_tag, tbl_text = self.get_tbls_info(tbls, tbl_index)
  122. if not has_bull: # No question bullet
  123. if not last_q:
  124. if tbl_pn < line_pn or (tbl_pn == line_pn and tbl_top <= line_top): # image passed
  125. tbl_index += 1
  126. continue
  127. else:
  128. sum_tag = line_tag
  129. sum_section = section
  130. while ((tbl_pn == last_pn and tbl_top>= last_bottom) or (tbl_pn > last_pn)) \
  131. and ((tbl_pn == line_pn and tbl_top <= line_top) or (tbl_pn < line_pn)): # add image at the middle of current answer
  132. sum_tag = f'{tbl_tag}{sum_tag}'
  133. sum_section = f'{tbl_text}{sum_section}'
  134. tbl_index += 1
  135. tbl_pn, tbl_left, tbl_right, tbl_top, tbl_bottom, tbl_tag, tbl_text = self.get_tbls_info(tbls, tbl_index)
  136. last_a = f'{last_a}{sum_section}'
  137. last_tag = f'{last_tag}{sum_tag}'
  138. else:
  139. if last_q:
  140. while ((tbl_pn == last_pn and tbl_top>= last_bottom) or (tbl_pn > last_pn)) \
  141. and ((tbl_pn == line_pn and tbl_top <= line_top) or (tbl_pn < line_pn)): # add image at the end of last answer
  142. last_tag = f'{last_tag}{tbl_tag}'
  143. last_a = f'{last_a}{tbl_text}'
  144. tbl_index += 1
  145. tbl_pn, tbl_left, tbl_right, tbl_top, tbl_bottom, tbl_tag, tbl_text = self.get_tbls_info(tbls, tbl_index)
  146. image, poss = self.crop(last_tag, need_position=True)
  147. qai_list.append((last_q, last_a, image, poss))
  148. last_q, last_a, last_tag = '', '', ''
  149. last_q = has_bull.group()
  150. _, end = has_bull.span()
  151. last_a = section[end:]
  152. last_tag = line_tag
  153. last_bottom = float(line_tag.rstrip('##').split('\t')[4])
  154. last_pn = line_pn
  155. if last_q:
  156. qai_list.append((last_q, last_a, *self.crop(last_tag, need_position=True)))
  157. return qai_list, tbls
  158. def get_tbls_info(self, tbls, tbl_index):
  159. if tbl_index >= len(tbls):
  160. return 1, 0, 0, 0, 0, '@@0\t0\t0\t0\t0##', ''
  161. tbl_pn = tbls[tbl_index][1][0][0]+1
  162. tbl_left = tbls[tbl_index][1][0][1]
  163. tbl_right = tbls[tbl_index][1][0][2]
  164. tbl_top = tbls[tbl_index][1][0][3]
  165. tbl_bottom = tbls[tbl_index][1][0][4]
  166. tbl_tag = "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  167. .format(tbl_pn, tbl_left, tbl_right, tbl_top, tbl_bottom)
  168. _tbl_text = ''.join(tbls[tbl_index][0][1])
  169. return tbl_pn, tbl_left, tbl_right, tbl_top, tbl_bottom, tbl_tag,
  170. class Docx(DocxParser):
  171. def __init__(self):
  172. pass
  173. def get_picture(self, document, paragraph):
  174. img = paragraph._element.xpath('.//pic:pic')
  175. if not img:
  176. return None
  177. img = img[0]
  178. embed = img.xpath('.//a:blip/@r:embed')[0]
  179. related_part = document.part.related_parts[embed]
  180. image = related_part.image
  181. image = Image.open(BytesIO(image.blob)).convert('RGB')
  182. return image
  183. def __call__(self, filename, binary=None, from_page=0, to_page=100000, callback=None):
  184. self.doc = Document(
  185. filename) if not binary else Document(BytesIO(binary))
  186. pn = 0
  187. last_answer, last_image = "", None
  188. question_stack, level_stack = [], []
  189. qai_list = []
  190. for p in self.doc.paragraphs:
  191. if pn > to_page:
  192. break
  193. question_level, p_text = 0, ''
  194. if from_page <= pn < to_page and p.text.strip():
  195. question_level, p_text = docx_question_level(p)
  196. if not question_level or question_level > 6: # not a question
  197. last_answer = f'{last_answer}\n{p_text}'
  198. current_image = self.get_picture(self.doc, p)
  199. last_image = concat_img(last_image, current_image)
  200. else: # is a question
  201. if last_answer or last_image:
  202. sum_question = '\n'.join(question_stack)
  203. if sum_question:
  204. qai_list.append((sum_question, last_answer, last_image))
  205. last_answer, last_image = '', None
  206. i = question_level
  207. while question_stack and i <= level_stack[-1]:
  208. question_stack.pop()
  209. level_stack.pop()
  210. question_stack.append(p_text)
  211. level_stack.append(question_level)
  212. for run in p.runs:
  213. if 'lastRenderedPageBreak' in run._element.xml:
  214. pn += 1
  215. continue
  216. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  217. pn += 1
  218. if last_answer:
  219. sum_question = '\n'.join(question_stack)
  220. if sum_question:
  221. qai_list.append((sum_question, last_answer, last_image))
  222. tbls = []
  223. for tb in self.doc.tables:
  224. html= "<table>"
  225. for r in tb.rows:
  226. html += "<tr>"
  227. i = 0
  228. while i < len(r.cells):
  229. span = 1
  230. c = r.cells[i]
  231. for j in range(i+1, len(r.cells)):
  232. if c.text == r.cells[j].text:
  233. span += 1
  234. i = j
  235. i += 1
  236. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  237. html += "</tr>"
  238. html += "</table>"
  239. tbls.append(((None, html), ""))
  240. return qai_list, tbls
  241. def rmPrefix(txt):
  242. return re.sub(
  243. r"^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+", "", txt.strip(), flags=re.IGNORECASE)
  244. def beAdocPdf(d, q, a, eng, image, poss):
  245. qprefix = "Question: " if eng else "问题:"
  246. aprefix = "Answer: " if eng else "回答:"
  247. d["content_with_weight"] = "\t".join(
  248. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  249. d["content_ltks"] = rag_tokenizer.tokenize(q)
  250. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  251. d["image"] = image
  252. add_positions(d, poss)
  253. return d
  254. def beAdocDocx(d, q, a, eng, image, row_num=-1):
  255. qprefix = "Question: " if eng else "问题:"
  256. aprefix = "Answer: " if eng else "回答:"
  257. d["content_with_weight"] = "\t".join(
  258. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  259. d["content_ltks"] = rag_tokenizer.tokenize(q)
  260. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  261. d["image"] = image
  262. if row_num >= 0:
  263. d["top_int"] = [row_num]
  264. return d
  265. def beAdoc(d, q, a, eng, row_num=-1):
  266. qprefix = "Question: " if eng else "问题:"
  267. aprefix = "Answer: " if eng else "回答:"
  268. d["content_with_weight"] = "\t".join(
  269. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  270. d["content_ltks"] = rag_tokenizer.tokenize(q)
  271. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  272. if row_num >= 0:
  273. d["top_int"] = [row_num]
  274. return d
  275. def mdQuestionLevel(s):
  276. match = re.match(r'#*', s)
  277. return (len(match.group(0)), s.lstrip('#').lstrip()) if match else (0, s)
  278. def chunk(filename, binary=None, lang="Chinese", callback=None, **kwargs):
  279. """
  280. Excel and csv(txt) format files are supported.
  281. If the file is in excel format, there should be 2 column question and answer without header.
  282. And question column is ahead of answer column.
  283. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  284. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate question and answer.
  285. All the deformed lines will be ignored.
  286. Every pair of Q&A will be treated as a chunk.
  287. """
  288. eng = lang.lower() == "english"
  289. res = []
  290. doc = {
  291. "docnm_kwd": filename,
  292. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  293. }
  294. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  295. callback(0.1, "Start to parse.")
  296. excel_parser = Excel()
  297. for ii, (q, a) in enumerate(excel_parser(filename, binary, callback)):
  298. res.append(beAdoc(deepcopy(doc), q, a, eng, ii))
  299. return res
  300. elif re.search(r"\.(txt)$", filename, re.IGNORECASE):
  301. callback(0.1, "Start to parse.")
  302. txt = get_text(filename, binary)
  303. lines = txt.split("\n")
  304. comma, tab = 0, 0
  305. for line in lines:
  306. if len(line.split(",")) == 2:
  307. comma += 1
  308. if len(line.split("\t")) == 2:
  309. tab += 1
  310. delimiter = "\t" if tab >= comma else ","
  311. fails = []
  312. question, answer = "", ""
  313. i = 0
  314. while i < len(lines):
  315. arr = lines[i].split(delimiter)
  316. if len(arr) != 2:
  317. if question:
  318. answer += "\n" + lines[i]
  319. else:
  320. fails.append(str(i+1))
  321. elif len(arr) == 2:
  322. if question and answer:
  323. res.append(beAdoc(deepcopy(doc), question, answer, eng, i))
  324. question, answer = arr
  325. i += 1
  326. if len(res) % 999 == 0:
  327. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  328. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  329. if question:
  330. res.append(beAdoc(deepcopy(doc), question, answer, eng, len(lines)))
  331. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  332. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  333. return res
  334. elif re.search(r"\.(csv)$", filename, re.IGNORECASE):
  335. callback(0.1, "Start to parse.")
  336. txt = get_text(filename, binary)
  337. lines = txt.split("\n")
  338. delimiter = "\t" if any("\t" in line for line in lines) else ","
  339. fails = []
  340. question, answer = "", ""
  341. res = []
  342. reader = csv.reader(lines, delimiter=delimiter)
  343. for i, row in enumerate(reader):
  344. if len(row) != 2:
  345. if question:
  346. answer += "\n" + lines[i]
  347. else:
  348. fails.append(str(i + 1))
  349. elif len(row) == 2:
  350. if question and answer:
  351. res.append(beAdoc(deepcopy(doc), question, answer, eng, i))
  352. question, answer = row
  353. if len(res) % 999 == 0:
  354. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  355. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  356. if question:
  357. res.append(beAdoc(deepcopy(doc), question, answer, eng, len(reader)))
  358. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  359. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  360. return res
  361. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  362. callback(0.1, "Start to parse.")
  363. pdf_parser = Pdf()
  364. qai_list, tbls = pdf_parser(filename if not binary else binary,
  365. from_page=0, to_page=10000, callback=callback)
  366. for q, a, image, poss in qai_list:
  367. res.append(beAdocPdf(deepcopy(doc), q, a, eng, image, poss))
  368. return res
  369. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  370. callback(0.1, "Start to parse.")
  371. txt = get_text(filename, binary)
  372. lines = txt.split("\n")
  373. _last_question, last_answer = "", ""
  374. question_stack, level_stack = [], []
  375. code_block = False
  376. for index, line in enumerate(lines):
  377. if line.strip().startswith('```'):
  378. code_block = not code_block
  379. question_level, question = 0, ''
  380. if not code_block:
  381. question_level, question = mdQuestionLevel(line)
  382. if not question_level or question_level > 6: # not a question
  383. last_answer = f'{last_answer}\n{line}'
  384. else: # is a question
  385. if last_answer.strip():
  386. sum_question = '\n'.join(question_stack)
  387. if sum_question:
  388. res.append(beAdoc(deepcopy(doc), sum_question, markdown(last_answer, extensions=['markdown.extensions.tables']), eng, index))
  389. last_answer = ''
  390. i = question_level
  391. while question_stack and i <= level_stack[-1]:
  392. question_stack.pop()
  393. level_stack.pop()
  394. question_stack.append(question)
  395. level_stack.append(question_level)
  396. if last_answer.strip():
  397. sum_question = '\n'.join(question_stack)
  398. if sum_question:
  399. res.append(beAdoc(deepcopy(doc), sum_question, markdown(last_answer, extensions=['markdown.extensions.tables']), eng, index))
  400. return res
  401. elif re.search(r"\.docx$", filename, re.IGNORECASE):
  402. docx_parser = Docx()
  403. qai_list, tbls = docx_parser(filename, binary,
  404. from_page=0, to_page=10000, callback=callback)
  405. res = tokenize_table(tbls, doc, eng)
  406. for i, (q, a, image) in enumerate(qai_list):
  407. res.append(beAdocDocx(deepcopy(doc), q, a, eng, image, i))
  408. return res
  409. raise NotImplementedError(
  410. "Excel, csv(txt), pdf, markdown and docx format files are supported.")
  411. if __name__ == "__main__":
  412. import sys
  413. def dummy(prog=None, msg=""):
  414. pass
  415. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)