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.

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