Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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
  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))
  175. return image
  176. def concat_img(self, img1, img2):
  177. if img1 and not img2:
  178. return img1
  179. if not img1 and img2:
  180. return img2
  181. if not img1 and not img2:
  182. return None
  183. width1, height1 = img1.size
  184. width2, height2 = img2.size
  185. new_width = max(width1, width2)
  186. new_height = height1 + height2
  187. new_image = Image.new('RGB', (new_width, new_height))
  188. new_image.paste(img1, (0, 0))
  189. new_image.paste(img2, (0, height1))
  190. return new_image
  191. def __call__(self, filename, binary=None, from_page=0, to_page=100000, callback=None):
  192. self.doc = Document(
  193. filename) if not binary else Document(BytesIO(binary))
  194. pn = 0
  195. last_answer, last_image = "", None
  196. question_stack, level_stack = [], []
  197. qai_list = []
  198. for p in self.doc.paragraphs:
  199. if pn > to_page:
  200. break
  201. question_level, p_text = 0, ''
  202. if from_page <= pn < to_page and p.text.strip():
  203. question_level, p_text = docx_question_level(p)
  204. if not question_level or question_level > 6: # not a question
  205. last_answer = f'{last_answer}\n{p_text}'
  206. current_image = self.get_picture(self.doc, p)
  207. last_image = self.concat_img(last_image, current_image)
  208. else: # is a question
  209. if last_answer or last_image:
  210. sum_question = '\n'.join(question_stack)
  211. if sum_question:
  212. qai_list.append((sum_question, last_answer, last_image))
  213. last_answer, last_image = '', None
  214. i = question_level
  215. while question_stack and i <= level_stack[-1]:
  216. question_stack.pop()
  217. level_stack.pop()
  218. question_stack.append(p_text)
  219. level_stack.append(question_level)
  220. for run in p.runs:
  221. if 'lastRenderedPageBreak' in run._element.xml:
  222. pn += 1
  223. continue
  224. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  225. pn += 1
  226. if last_answer:
  227. sum_question = '\n'.join(question_stack)
  228. if sum_question:
  229. qai_list.append((sum_question, last_answer, last_image))
  230. tbls = []
  231. for tb in self.doc.tables:
  232. html= "<table>"
  233. for r in tb.rows:
  234. html += "<tr>"
  235. i = 0
  236. while i < len(r.cells):
  237. span = 1
  238. c = r.cells[i]
  239. for j in range(i+1, len(r.cells)):
  240. if c.text == r.cells[j].text:
  241. span += 1
  242. i = j
  243. i += 1
  244. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  245. html += "</tr>"
  246. html += "</table>"
  247. tbls.append(((None, html), ""))
  248. return qai_list, tbls
  249. def rmPrefix(txt):
  250. return re.sub(
  251. r"^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+", "", txt.strip(), flags=re.IGNORECASE)
  252. def beAdocPdf(d, q, a, eng, image, poss):
  253. qprefix = "Question: " if eng else "问题:"
  254. aprefix = "Answer: " if eng else "回答:"
  255. d["content_with_weight"] = "\t".join(
  256. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  257. d["content_ltks"] = rag_tokenizer.tokenize(q)
  258. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  259. d["image"] = image
  260. add_positions(d, poss)
  261. return d
  262. def beAdocDocx(d, q, a, eng, image):
  263. qprefix = "Question: " if eng else "问题:"
  264. aprefix = "Answer: " if eng else "回答:"
  265. d["content_with_weight"] = "\t".join(
  266. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  267. d["content_ltks"] = rag_tokenizer.tokenize(q)
  268. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  269. d["image"] = image
  270. return d
  271. def beAdoc(d, q, a, eng):
  272. qprefix = "Question: " if eng else "问题:"
  273. aprefix = "Answer: " if eng else "回答:"
  274. d["content_with_weight"] = "\t".join(
  275. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  276. d["content_ltks"] = rag_tokenizer.tokenize(q)
  277. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  278. return d
  279. def mdQuestionLevel(s):
  280. match = re.match(r'#*', s)
  281. return (len(match.group(0)), s.lstrip('#').lstrip()) if match else (0, s)
  282. def chunk(filename, binary=None, lang="Chinese", callback=None, **kwargs):
  283. """
  284. Excel and csv(txt) format files are supported.
  285. If the file is in excel format, there should be 2 column question and answer without header.
  286. And question column is ahead of answer column.
  287. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  288. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate question and answer.
  289. All the deformed lines will be ignored.
  290. Every pair of Q&A will be treated as a chunk.
  291. """
  292. eng = lang.lower() == "english"
  293. res = []
  294. doc = {
  295. "docnm_kwd": filename,
  296. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  297. }
  298. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  299. callback(0.1, "Start to parse.")
  300. excel_parser = Excel()
  301. for q, a in excel_parser(filename, binary, callback):
  302. res.append(beAdoc(deepcopy(doc), q, a, eng))
  303. return res
  304. elif re.search(r"\.(txt|csv)$", filename, re.IGNORECASE):
  305. callback(0.1, "Start to parse.")
  306. txt = ""
  307. if binary:
  308. encoding = find_codec(binary)
  309. txt = binary.decode(encoding, errors="ignore")
  310. else:
  311. with open(filename, "r") as f:
  312. while True:
  313. l = f.readline()
  314. if not l:
  315. break
  316. txt += l
  317. lines = txt.split("\n")
  318. comma, tab = 0, 0
  319. for l in lines:
  320. if len(l.split(",")) == 2: comma += 1
  321. if len(l.split("\t")) == 2: tab += 1
  322. delimiter = "\t" if tab >= comma else ","
  323. fails = []
  324. question, answer = "", ""
  325. i = 0
  326. while i < len(lines):
  327. arr = lines[i].split(delimiter)
  328. if len(arr) != 2:
  329. if question: answer += "\n" + lines[i]
  330. else:
  331. fails.append(str(i+1))
  332. elif len(arr) == 2:
  333. if question and answer: res.append(beAdoc(deepcopy(doc), question, answer, eng))
  334. question, answer = arr
  335. i += 1
  336. if len(res) % 999 == 0:
  337. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  338. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  339. if question: res.append(beAdoc(deepcopy(doc), question, answer, eng))
  340. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  341. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  342. return res
  343. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  344. callback(0.1, "Start to parse.")
  345. pdf_parser = Pdf()
  346. qai_list, tbls = pdf_parser(filename if not binary else binary,
  347. from_page=0, to_page=10000, callback=callback)
  348. for q, a, image, poss in qai_list:
  349. res.append(beAdocPdf(deepcopy(doc), q, a, eng, image, poss))
  350. return res
  351. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  352. callback(0.1, "Start to parse.")
  353. txt = ""
  354. if binary:
  355. encoding = find_codec(binary)
  356. txt = binary.decode(encoding, errors="ignore")
  357. else:
  358. with open(filename, "r") as f:
  359. while True:
  360. l = f.readline()
  361. if not l:
  362. break
  363. txt += l
  364. lines = txt.split("\n")
  365. last_question, last_answer = "", ""
  366. question_stack, level_stack = [], []
  367. code_block = False
  368. level_index = [-1] * 7
  369. for index, l in enumerate(lines):
  370. if not l.strip():
  371. continue
  372. if l.strip().startswith('```'):
  373. code_block = not code_block
  374. question_level, question = 0, ''
  375. if not code_block:
  376. question_level, question = mdQuestionLevel(l)
  377. if not question_level or question_level > 6: # not a question
  378. last_answer = f'{last_answer}\n{l}'
  379. else: # is a question
  380. if last_answer:
  381. sum_question = '\n'.join(question_stack)
  382. if sum_question:
  383. res.append(beAdoc(deepcopy(doc), sum_question, last_answer, eng))
  384. last_answer = ''
  385. i = question_level
  386. while question_stack and i <= level_stack[-1]:
  387. question_stack.pop()
  388. level_stack.pop()
  389. question_stack.append(question)
  390. level_stack.append(question_level)
  391. if last_answer:
  392. sum_question = '\n'.join(question_stack)
  393. if sum_question:
  394. res.append(beAdoc(deepcopy(doc), sum_question, last_answer, eng))
  395. return res
  396. elif re.search(r"\.docx$", filename, re.IGNORECASE):
  397. docx_parser = Docx()
  398. qai_list, tbls = docx_parser(filename, binary,
  399. from_page=0, to_page=10000, callback=callback)
  400. res = tokenize_table(tbls, doc, eng)
  401. for q, a, image in qai_list:
  402. res.append(beAdocDocx(deepcopy(doc), q, a, eng, image))
  403. return res
  404. raise NotImplementedError(
  405. "Excel, csv(txt), pdf, markdown and docx format files are supported.")
  406. if __name__ == "__main__":
  407. import sys
  408. def dummy(prog=None, msg=""):
  409. pass
  410. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)