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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #
  2. # Copyright 2025 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. logging.debug("OCR: {}".format(timer() - start))
  44. start = timer()
  45. self._layouts_rec(zoomin)
  46. callback(0.65, "Layout analysis ({:.2f}s)".format(timer() - start))
  47. logging.debug("layouts: {}".format(timer() - start))
  48. start = timer()
  49. self._table_transformer_job(zoomin)
  50. callback(0.67, "Table analysis ({:.2f}s)".format(timer() - start))
  51. start = timer()
  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 merged ({:.2f}s)".format(timer() - start))
  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("layoutno", ""), 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. else:
  143. break
  144. i += 1
  145. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  146. html += "</tr>"
  147. html += "</table>"
  148. tbls.append(((None, html), ""))
  149. return ti_list, tbls
  150. def chunk(filename, binary=None, from_page=0, to_page=100000,
  151. lang="Chinese", callback=None, **kwargs):
  152. """
  153. Only pdf is supported.
  154. """
  155. parser_config = kwargs.get(
  156. "parser_config", {
  157. "chunk_token_num": 512, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  158. pdf_parser = None
  159. doc = {
  160. "docnm_kwd": filename
  161. }
  162. doc["title_tks"] = rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  163. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  164. # is it English
  165. eng = lang.lower() == "english" # pdf_parser.is_english
  166. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  167. pdf_parser = Pdf()
  168. if parser_config.get("layout_recognize", "DeepDOC") == "Plain Text":
  169. pdf_parser = PlainParser()
  170. sections, tbls = pdf_parser(filename if not binary else binary,
  171. from_page=from_page, to_page=to_page, callback=callback)
  172. if sections and len(sections[0]) < 3:
  173. sections = [(t, lvl, [[0] * 5]) for t, lvl in sections]
  174. # set pivot using the most frequent type of title,
  175. # then merge between 2 pivot
  176. if len(sections) > 0 and len(pdf_parser.outlines) / len(sections) > 0.03:
  177. max_lvl = max([lvl for _, lvl in pdf_parser.outlines])
  178. most_level = max(0, max_lvl - 1)
  179. levels = []
  180. for txt, _, _ in sections:
  181. for t, lvl in pdf_parser.outlines:
  182. tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
  183. tks_ = set([txt[i] + txt[i + 1]
  184. for i in range(min(len(t), len(txt) - 1))])
  185. if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
  186. levels.append(lvl)
  187. break
  188. else:
  189. levels.append(max_lvl + 1)
  190. else:
  191. bull = bullets_category([txt for txt, _, _ in sections])
  192. most_level, levels = title_frequency(
  193. bull, [(txt, lvl) for txt, lvl, _ in sections])
  194. assert len(sections) == len(levels)
  195. sec_ids = []
  196. sid = 0
  197. for i, lvl in enumerate(levels):
  198. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  199. sid += 1
  200. sec_ids.append(sid)
  201. sections = [(txt, sec_ids[i], poss)
  202. for i, (txt, _, poss) in enumerate(sections)]
  203. for (img, rows), poss in tbls:
  204. if not rows:
  205. continue
  206. sections.append((rows if isinstance(rows, str) else rows[0], -1,
  207. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  208. def tag(pn, left, right, top, bottom):
  209. if pn + left + right + top + bottom == 0:
  210. return ""
  211. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  212. .format(pn, left, right, top, bottom)
  213. chunks = []
  214. last_sid = -2
  215. tk_cnt = 0
  216. for txt, sec_id, poss in sorted(sections, key=lambda x: (
  217. x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  218. poss = "\t".join([tag(*pos) for pos in poss])
  219. if tk_cnt < 32 or (tk_cnt < 1024 and (sec_id == last_sid or sec_id == -1)):
  220. if chunks:
  221. chunks[-1] += "\n" + txt + poss
  222. tk_cnt += num_tokens_from_string(txt)
  223. continue
  224. chunks.append(txt + poss)
  225. tk_cnt = num_tokens_from_string(txt)
  226. if sec_id > -1:
  227. last_sid = sec_id
  228. res = tokenize_table(tbls, doc, eng)
  229. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  230. return res
  231. elif re.search(r"\.docx?$", filename, re.IGNORECASE):
  232. docx_parser = Docx()
  233. ti_list, tbls = docx_parser(filename, binary,
  234. from_page=0, to_page=10000, callback=callback)
  235. res = tokenize_table(tbls, doc, eng)
  236. for text, image in ti_list:
  237. d = copy.deepcopy(doc)
  238. if image:
  239. d['image'] = image
  240. d["doc_type_kwd"] = "image"
  241. tokenize(d, text, eng)
  242. res.append(d)
  243. return res
  244. else:
  245. raise NotImplementedError("file type not supported yet(pdf and docx supported)")
  246. if __name__ == "__main__":
  247. import sys
  248. def dummy(prog=None, msg=""):
  249. pass
  250. chunk(sys.argv[1], callback=dummy)