You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

qa.py 18KB

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