Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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