您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import copy
  17. import re
  18. from api.db import ParserType
  19. from io import BytesIO
  20. from rag.nlp import rag_tokenizer, tokenize, tokenize_table, bullets_category, title_frequency, tokenize_chunks, docx_question_level
  21. from rag.utils import num_tokens_from_string
  22. from deepdoc.parser import PdfParser, PlainParser, DocxParser
  23. from docx import Document
  24. from PIL import Image
  25. from api.utils.log_utils import logger
  26. class Pdf(PdfParser):
  27. def __init__(self):
  28. self.model_speciess = ParserType.MANUAL.value
  29. super().__init__()
  30. def __call__(self, filename, binary=None, from_page=0,
  31. to_page=100000, zoomin=3, callback=None):
  32. from timeit import default_timer as timer
  33. start = timer()
  34. callback(msg="OCR is running...")
  35. self.__images__(
  36. filename if not binary else binary,
  37. zoomin,
  38. from_page,
  39. to_page,
  40. callback
  41. )
  42. callback(msg="OCR finished.")
  43. # for bb in self.boxes:
  44. # for b in bb:
  45. # print(b)
  46. logger.info("OCR: {}".format(timer() - start))
  47. self._layouts_rec(zoomin)
  48. callback(0.65, "Layout analysis finished.")
  49. logger.info("layouts: {}".format(timer() - start))
  50. self._table_transformer_job(zoomin)
  51. callback(0.67, "Table analysis finished.")
  52. self._text_merge()
  53. tbls = self._extract_table_figure(True, zoomin, True, True)
  54. self._concat_downward()
  55. self._filter_forpages()
  56. callback(0.68, "Text merging finished")
  57. # clean mess
  58. for b in self.boxes:
  59. b["text"] = re.sub(r"([\t  ]|\u3000){2,}", " ", b["text"].strip())
  60. return [(b["text"], b.get("layout_no", ""), self.get_position(b, zoomin))
  61. for i, b in enumerate(self.boxes)], tbls
  62. class Docx(DocxParser):
  63. def __init__(self):
  64. pass
  65. def get_picture(self, document, paragraph):
  66. img = paragraph._element.xpath('.//pic:pic')
  67. if not img:
  68. return None
  69. img = img[0]
  70. embed = img.xpath('.//a:blip/@r:embed')[0]
  71. related_part = document.part.related_parts[embed]
  72. image = related_part.image
  73. image = Image.open(BytesIO(image.blob))
  74. return image
  75. def concat_img(self, img1, img2):
  76. if img1 and not img2:
  77. return img1
  78. if not img1 and img2:
  79. return img2
  80. if not img1 and not img2:
  81. return None
  82. width1, height1 = img1.size
  83. width2, height2 = img2.size
  84. new_width = max(width1, width2)
  85. new_height = height1 + height2
  86. new_image = Image.new('RGB', (new_width, new_height))
  87. new_image.paste(img1, (0, 0))
  88. new_image.paste(img2, (0, height1))
  89. return new_image
  90. def __call__(self, filename, binary=None, from_page=0, to_page=100000, callback=None):
  91. self.doc = Document(
  92. filename) if not binary else Document(BytesIO(binary))
  93. pn = 0
  94. last_answer, last_image = "", None
  95. question_stack, level_stack = [], []
  96. ti_list = []
  97. for p in self.doc.paragraphs:
  98. if pn > to_page:
  99. break
  100. question_level, p_text = 0, ''
  101. if from_page <= pn < to_page and p.text.strip():
  102. question_level, p_text = docx_question_level(p)
  103. if not question_level or question_level > 6: # not a question
  104. last_answer = f'{last_answer}\n{p_text}'
  105. current_image = self.get_picture(self.doc, p)
  106. last_image = self.concat_img(last_image, current_image)
  107. else: # is a question
  108. if last_answer or last_image:
  109. sum_question = '\n'.join(question_stack)
  110. if sum_question:
  111. ti_list.append((f'{sum_question}\n{last_answer}', last_image))
  112. last_answer, last_image = '', None
  113. i = question_level
  114. while question_stack and i <= level_stack[-1]:
  115. question_stack.pop()
  116. level_stack.pop()
  117. question_stack.append(p_text)
  118. level_stack.append(question_level)
  119. for run in p.runs:
  120. if 'lastRenderedPageBreak' in run._element.xml:
  121. pn += 1
  122. continue
  123. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  124. pn += 1
  125. if last_answer:
  126. sum_question = '\n'.join(question_stack)
  127. if sum_question:
  128. ti_list.append((f'{sum_question}\n{last_answer}', last_image))
  129. tbls = []
  130. for tb in self.doc.tables:
  131. html= "<table>"
  132. for r in tb.rows:
  133. html += "<tr>"
  134. i = 0
  135. while i < len(r.cells):
  136. span = 1
  137. c = r.cells[i]
  138. for j in range(i+1, len(r.cells)):
  139. if c.text == r.cells[j].text:
  140. span += 1
  141. i = j
  142. i += 1
  143. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  144. html += "</tr>"
  145. html += "</table>"
  146. tbls.append(((None, html), ""))
  147. return ti_list, tbls
  148. def chunk(filename, binary=None, from_page=0, to_page=100000,
  149. lang="Chinese", callback=None, **kwargs):
  150. """
  151. Only pdf is supported.
  152. """
  153. pdf_parser = None
  154. doc = {
  155. "docnm_kwd": filename
  156. }
  157. doc["title_tks"] = rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  158. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  159. # is it English
  160. eng = lang.lower() == "english" # pdf_parser.is_english
  161. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  162. pdf_parser = Pdf() if kwargs.get(
  163. "parser_config", {}).get(
  164. "layout_recognize", True) else PlainParser()
  165. sections, tbls = pdf_parser(filename if not binary else binary,
  166. from_page=from_page, to_page=to_page, callback=callback)
  167. if sections and len(sections[0]) < 3:
  168. sections = [(t, l, [[0] * 5]) for t, l in sections]
  169. # set pivot using the most frequent type of title,
  170. # then merge between 2 pivot
  171. if len(sections) > 0 and len(pdf_parser.outlines) / len(sections) > 0.1:
  172. max_lvl = max([lvl for _, lvl in pdf_parser.outlines])
  173. most_level = max(0, max_lvl - 1)
  174. levels = []
  175. for txt, _, _ in sections:
  176. for t, lvl in pdf_parser.outlines:
  177. tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
  178. tks_ = set([txt[i] + txt[i + 1]
  179. for i in range(min(len(t), len(txt) - 1))])
  180. if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
  181. levels.append(lvl)
  182. break
  183. else:
  184. levels.append(max_lvl + 1)
  185. else:
  186. bull = bullets_category([txt for txt, _, _ in sections])
  187. most_level, levels = title_frequency(
  188. bull, [(txt, l) for txt, l, poss in sections])
  189. assert len(sections) == len(levels)
  190. sec_ids = []
  191. sid = 0
  192. for i, lvl in enumerate(levels):
  193. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  194. sid += 1
  195. sec_ids.append(sid)
  196. # print(lvl, self.boxes[i]["text"], most_level, sid)
  197. sections = [(txt, sec_ids[i], poss)
  198. for i, (txt, _, poss) in enumerate(sections)]
  199. for (img, rows), poss in tbls:
  200. if not rows: continue
  201. sections.append((rows if isinstance(rows, str) else rows[0], -1,
  202. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  203. def tag(pn, left, right, top, bottom):
  204. if pn + left + right + top + bottom == 0:
  205. return ""
  206. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  207. .format(pn, left, right, top, bottom)
  208. chunks = []
  209. last_sid = -2
  210. tk_cnt = 0
  211. for txt, sec_id, poss in sorted(sections, key=lambda x: (
  212. x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  213. poss = "\t".join([tag(*pos) for pos in poss])
  214. if tk_cnt < 32 or (tk_cnt < 1024 and (sec_id == last_sid or sec_id == -1)):
  215. if chunks:
  216. chunks[-1] += "\n" + txt + poss
  217. tk_cnt += num_tokens_from_string(txt)
  218. continue
  219. chunks.append(txt + poss)
  220. tk_cnt = num_tokens_from_string(txt)
  221. if sec_id > -1:
  222. last_sid = sec_id
  223. res = tokenize_table(tbls, doc, eng)
  224. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  225. return res
  226. if re.search(r"\.docx$", filename, re.IGNORECASE):
  227. docx_parser = Docx()
  228. ti_list, tbls = docx_parser(filename, binary,
  229. from_page=0, to_page=10000, callback=callback)
  230. res = tokenize_table(tbls, doc, eng)
  231. for text, image in ti_list:
  232. d = copy.deepcopy(doc)
  233. d['image'] = image
  234. tokenize(d, text, eng)
  235. res.append(d)
  236. return res
  237. else:
  238. raise NotImplementedError("file type not supported yet(pdf and docx supported)")
  239. if __name__ == "__main__":
  240. import sys
  241. def dummy(prog=None, msg=""):
  242. pass
  243. chunk(sys.argv[1], callback=dummy)