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

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