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.

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