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.

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