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.

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