Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

qa.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. d["image"] = image
  253. add_positions(d, poss)
  254. return d
  255. def beAdocDocx(d, q, a, eng, image, row_num=-1):
  256. qprefix = "Question: " if eng else "问题:"
  257. aprefix = "Answer: " if eng else "回答:"
  258. d["content_with_weight"] = "\t".join(
  259. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  260. d["content_ltks"] = rag_tokenizer.tokenize(q)
  261. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  262. d["image"] = image
  263. if row_num >= 0:
  264. d["top_int"] = [row_num]
  265. return d
  266. def beAdoc(d, q, a, eng, row_num=-1):
  267. qprefix = "Question: " if eng else "问题:"
  268. aprefix = "Answer: " if eng else "回答:"
  269. d["content_with_weight"] = "\t".join(
  270. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  271. d["content_ltks"] = rag_tokenizer.tokenize(q)
  272. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  273. if row_num >= 0:
  274. d["top_int"] = [row_num]
  275. return d
  276. def mdQuestionLevel(s):
  277. match = re.match(r'#*', s)
  278. return (len(match.group(0)), s.lstrip('#').lstrip()) if match else (0, s)
  279. def chunk(filename, binary=None, lang="Chinese", callback=None, **kwargs):
  280. """
  281. Excel and csv(txt) format files are supported.
  282. If the file is in excel format, there should be 2 column question and answer without header.
  283. And question column is ahead of answer column.
  284. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  285. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate question and answer.
  286. All the deformed lines will be ignored.
  287. Every pair of Q&A will be treated as a chunk.
  288. """
  289. eng = lang.lower() == "english"
  290. res = []
  291. doc = {
  292. "docnm_kwd": filename,
  293. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  294. }
  295. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  296. callback(0.1, "Start to parse.")
  297. excel_parser = Excel()
  298. for ii, (q, a) in enumerate(excel_parser(filename, binary, callback)):
  299. res.append(beAdoc(deepcopy(doc), q, a, eng, ii))
  300. return res
  301. elif re.search(r"\.(txt)$", filename, re.IGNORECASE):
  302. callback(0.1, "Start to parse.")
  303. txt = get_text(filename, binary)
  304. lines = txt.split("\n")
  305. comma, tab = 0, 0
  306. for line in lines:
  307. if len(line.split(",")) == 2:
  308. comma += 1
  309. if len(line.split("\t")) == 2:
  310. tab += 1
  311. delimiter = "\t" if tab >= comma else ","
  312. fails = []
  313. question, answer = "", ""
  314. i = 0
  315. while i < len(lines):
  316. arr = lines[i].split(delimiter)
  317. if len(arr) != 2:
  318. if question:
  319. answer += "\n" + lines[i]
  320. else:
  321. fails.append(str(i+1))
  322. elif len(arr) == 2:
  323. if question and answer:
  324. res.append(beAdoc(deepcopy(doc), question, answer, eng, i))
  325. question, answer = arr
  326. i += 1
  327. if len(res) % 999 == 0:
  328. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  329. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  330. if question:
  331. res.append(beAdoc(deepcopy(doc), question, answer, eng, len(lines)))
  332. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  333. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  334. return res
  335. elif re.search(r"\.(csv)$", filename, re.IGNORECASE):
  336. callback(0.1, "Start to parse.")
  337. txt = get_text(filename, binary)
  338. lines = txt.split("\n")
  339. delimiter = "\t" if any("\t" in line for line in lines) else ","
  340. fails = []
  341. question, answer = "", ""
  342. res = []
  343. reader = csv.reader(lines, delimiter=delimiter)
  344. for i, row in enumerate(reader):
  345. if len(row) != 2:
  346. if question:
  347. answer += "\n" + lines[i]
  348. else:
  349. fails.append(str(i + 1))
  350. elif len(row) == 2:
  351. if question and answer:
  352. res.append(beAdoc(deepcopy(doc), question, answer, eng, i))
  353. question, answer = row
  354. if len(res) % 999 == 0:
  355. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  356. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  357. if question:
  358. res.append(beAdoc(deepcopy(doc), question, answer, eng, len(list(reader))))
  359. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  360. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  361. return res
  362. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  363. callback(0.1, "Start to parse.")
  364. pdf_parser = Pdf()
  365. qai_list, tbls = pdf_parser(filename if not binary else binary,
  366. from_page=0, to_page=10000, callback=callback)
  367. for q, a, image, poss in qai_list:
  368. res.append(beAdocPdf(deepcopy(doc), q, a, eng, image, poss))
  369. return res
  370. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  371. callback(0.1, "Start to parse.")
  372. txt = get_text(filename, binary)
  373. lines = txt.split("\n")
  374. _last_question, last_answer = "", ""
  375. question_stack, level_stack = [], []
  376. code_block = False
  377. for index, line in enumerate(lines):
  378. if line.strip().startswith('```'):
  379. code_block = not code_block
  380. question_level, question = 0, ''
  381. if not code_block:
  382. question_level, question = mdQuestionLevel(line)
  383. if not question_level or question_level > 6: # not a question
  384. last_answer = f'{last_answer}\n{line}'
  385. else: # is a question
  386. if last_answer.strip():
  387. sum_question = '\n'.join(question_stack)
  388. if sum_question:
  389. res.append(beAdoc(deepcopy(doc), sum_question, markdown(last_answer, extensions=['markdown.extensions.tables']), eng, index))
  390. last_answer = ''
  391. i = question_level
  392. while question_stack and i <= level_stack[-1]:
  393. question_stack.pop()
  394. level_stack.pop()
  395. question_stack.append(question)
  396. level_stack.append(question_level)
  397. if last_answer.strip():
  398. sum_question = '\n'.join(question_stack)
  399. if sum_question:
  400. res.append(beAdoc(deepcopy(doc), sum_question, markdown(last_answer, extensions=['markdown.extensions.tables']), eng, index))
  401. return res
  402. elif re.search(r"\.docx$", filename, re.IGNORECASE):
  403. docx_parser = Docx()
  404. qai_list, tbls = docx_parser(filename, binary,
  405. from_page=0, to_page=10000, callback=callback)
  406. res = tokenize_table(tbls, doc, eng)
  407. for i, (q, a, image) in enumerate(qai_list):
  408. res.append(beAdocDocx(deepcopy(doc), q, a, eng, image, i))
  409. return res
  410. raise NotImplementedError(
  411. "Excel, csv(txt), pdf, markdown and docx format files are supported.")
  412. if __name__ == "__main__":
  413. import sys
  414. def dummy(prog=None, msg=""):
  415. pass
  416. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)