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.

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