Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 re
  18. from functools import reduce
  19. from io import BytesIO
  20. from timeit import default_timer as timer
  21. from docx import Document
  22. from docx.image.exceptions import InvalidImageStreamError, UnexpectedEndOfFileError, UnrecognizedImageError
  23. from markdown import markdown
  24. from PIL import Image
  25. from tika import parser
  26. from api.db import LLMType
  27. from api.db.services.llm_service import LLMBundle
  28. from deepdoc.parser import DocxParser, ExcelParser, HtmlParser, JsonParser, MarkdownParser, PdfParser, TxtParser
  29. from deepdoc.parser.pdf_parser import PlainParser, VisionParser
  30. from rag.nlp import concat_img, find_codec, naive_merge, naive_merge_docx, rag_tokenizer, tokenize_chunks, tokenize_chunks_docx, tokenize_table
  31. from rag.utils import num_tokens_from_string
  32. class Docx(DocxParser):
  33. def __init__(self):
  34. pass
  35. def get_picture(self, document, paragraph):
  36. img = paragraph._element.xpath('.//pic:pic')
  37. if not img:
  38. return None
  39. img = img[0]
  40. embed = img.xpath('.//a:blip/@r:embed')[0]
  41. related_part = document.part.related_parts[embed]
  42. try:
  43. image_blob = related_part.image.blob
  44. except UnrecognizedImageError:
  45. logging.info("Unrecognized image format. Skipping image.")
  46. return None
  47. except UnexpectedEndOfFileError:
  48. logging.info("EOF was unexpectedly encountered while reading an image stream. Skipping image.")
  49. return None
  50. except InvalidImageStreamError:
  51. logging.info("The recognized image stream appears to be corrupted. Skipping image.")
  52. return None
  53. try:
  54. image = Image.open(BytesIO(image_blob)).convert('RGB')
  55. return image
  56. except Exception:
  57. return None
  58. def __clean(self, line):
  59. line = re.sub(r"\u3000", " ", line).strip()
  60. return line
  61. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  62. self.doc = Document(
  63. filename) if not binary else Document(BytesIO(binary))
  64. pn = 0
  65. lines = []
  66. last_image = None
  67. for p in self.doc.paragraphs:
  68. if pn > to_page:
  69. break
  70. if from_page <= pn < to_page:
  71. if p.text.strip():
  72. if p.style and p.style.name == 'Caption':
  73. former_image = None
  74. if lines and lines[-1][1] and lines[-1][2] != 'Caption':
  75. former_image = lines[-1][1].pop()
  76. elif last_image:
  77. former_image = last_image
  78. last_image = None
  79. lines.append((self.__clean(p.text), [former_image], p.style.name))
  80. else:
  81. current_image = self.get_picture(self.doc, p)
  82. image_list = [current_image]
  83. if last_image:
  84. image_list.insert(0, last_image)
  85. last_image = None
  86. lines.append((self.__clean(p.text), image_list, p.style.name if p.style else ""))
  87. else:
  88. if current_image := self.get_picture(self.doc, p):
  89. if lines:
  90. lines[-1][1].append(current_image)
  91. else:
  92. last_image = current_image
  93. for run in p.runs:
  94. if 'lastRenderedPageBreak' in run._element.xml:
  95. pn += 1
  96. continue
  97. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  98. pn += 1
  99. new_line = [(line[0], reduce(concat_img, line[1]) if line[1] else None) for line in lines]
  100. tbls = []
  101. for tb in self.doc.tables:
  102. html = "<table>"
  103. for r in tb.rows:
  104. html += "<tr>"
  105. i = 0
  106. while i < len(r.cells):
  107. span = 1
  108. c = r.cells[i]
  109. for j in range(i + 1, len(r.cells)):
  110. if c.text == r.cells[j].text:
  111. span += 1
  112. i = j
  113. else:
  114. break
  115. i += 1
  116. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  117. html += "</tr>"
  118. html += "</table>"
  119. tbls.append(((None, html), ""))
  120. return new_line, tbls
  121. class Pdf(PdfParser):
  122. def __init__(self):
  123. super().__init__()
  124. def __call__(self, filename, binary=None, from_page=0,
  125. to_page=100000, zoomin=3, callback=None):
  126. start = timer()
  127. first_start = start
  128. callback(msg="OCR started")
  129. self.__images__(
  130. filename if not binary else binary,
  131. zoomin,
  132. from_page,
  133. to_page,
  134. callback
  135. )
  136. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  137. logging.info("OCR({}~{}): {:.2f}s".format(from_page, to_page, timer() - start))
  138. start = timer()
  139. self._layouts_rec(zoomin)
  140. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  141. start = timer()
  142. self._table_transformer_job(zoomin)
  143. callback(0.65, "Table analysis ({:.2f}s)".format(timer() - start))
  144. start = timer()
  145. self._text_merge()
  146. callback(0.67, "Text merged ({:.2f}s)".format(timer() - start))
  147. tbls = self._extract_table_figure(True, zoomin, True, True)
  148. # self._naive_vertical_merge()
  149. self._concat_downward()
  150. # self._filter_forpages()
  151. logging.info("layouts cost: {}s".format(timer() - first_start))
  152. return [(b["text"], self._line_tag(b, zoomin))
  153. for b in self.boxes], tbls
  154. class Markdown(MarkdownParser):
  155. def __call__(self, filename, binary=None):
  156. if binary:
  157. encoding = find_codec(binary)
  158. txt = binary.decode(encoding, errors="ignore")
  159. else:
  160. with open(filename, "r") as f:
  161. txt = f.read()
  162. remainder, tables = self.extract_tables_and_remainder(f'{txt}\n')
  163. sections = []
  164. tbls = []
  165. for sec in remainder.split("\n"):
  166. if num_tokens_from_string(sec) > 3 * self.chunk_token_num:
  167. sections.append((sec[:int(len(sec) / 2)], ""))
  168. sections.append((sec[int(len(sec) / 2):], ""))
  169. else:
  170. if sec.strip().find("#") == 0:
  171. sections.append((sec, ""))
  172. elif sections and sections[-1][0].strip().find("#") == 0:
  173. sec_, _ = sections.pop(-1)
  174. sections.append((sec_ + "\n" + sec, ""))
  175. else:
  176. sections.append((sec, ""))
  177. for table in tables:
  178. tbls.append(((None, markdown(table, extensions=['markdown.extensions.tables'])), ""))
  179. return sections, tbls
  180. def chunk(filename, binary=None, from_page=0, to_page=100000,
  181. lang="Chinese", callback=None, **kwargs):
  182. """
  183. Supported file formats are docx, pdf, excel, txt.
  184. This method apply the naive ways to chunk files.
  185. Successive text will be sliced into pieces using 'delimiter'.
  186. Next, these successive pieces are merge into chunks whose token number is no more than 'Max token number'.
  187. """
  188. is_english = lang.lower() == "english" # is_english(cks)
  189. parser_config = kwargs.get(
  190. "parser_config", {
  191. "chunk_token_num": 128, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  192. doc = {
  193. "docnm_kwd": filename,
  194. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  195. }
  196. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  197. res = []
  198. pdf_parser = None
  199. if re.search(r"\.docx$", filename, re.IGNORECASE):
  200. callback(0.1, "Start to parse.")
  201. sections, tables = Docx()(filename, binary)
  202. res = tokenize_table(tables, doc, is_english) # just for table
  203. callback(0.8, "Finish parsing.")
  204. st = timer()
  205. chunks, images = naive_merge_docx(
  206. sections, int(parser_config.get(
  207. "chunk_token_num", 128)), parser_config.get(
  208. "delimiter", "\n!?。;!?"))
  209. if kwargs.get("section_only", False):
  210. return chunks
  211. res.extend(tokenize_chunks_docx(chunks, doc, is_english, images))
  212. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  213. return res
  214. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  215. layout_recognizer = parser_config.get("layout_recognize", "DeepDOC")
  216. if layout_recognizer == "DeepDOC":
  217. pdf_parser = Pdf()
  218. elif layout_recognizer == "Plain Text":
  219. pdf_parser = PlainParser()
  220. else:
  221. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT, llm_name=layout_recognizer, lang=lang)
  222. pdf_parser = VisionParser(vision_model=vision_model, **kwargs)
  223. sections, tables = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page,
  224. callback=callback)
  225. res = tokenize_table(tables, doc, is_english)
  226. elif re.search(r"\.(csv|xlsx?)$", filename, re.IGNORECASE):
  227. callback(0.1, "Start to parse.")
  228. excel_parser = ExcelParser()
  229. if parser_config.get("html4excel"):
  230. sections = [(_, "") for _ in excel_parser.html(binary, 12) if _]
  231. else:
  232. sections = [(_, "") for _ in excel_parser(binary) if _]
  233. elif re.search(r"\.(txt|py|js|java|c|cpp|h|php|go|ts|sh|cs|kt|sql)$", filename, re.IGNORECASE):
  234. callback(0.1, "Start to parse.")
  235. sections = TxtParser()(filename, binary,
  236. parser_config.get("chunk_token_num", 128),
  237. parser_config.get("delimiter", "\n!?;。;!?"))
  238. callback(0.8, "Finish parsing.")
  239. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  240. callback(0.1, "Start to parse.")
  241. sections, tables = Markdown(int(parser_config.get("chunk_token_num", 128)))(filename, binary)
  242. res = tokenize_table(tables, doc, is_english)
  243. callback(0.8, "Finish parsing.")
  244. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  245. callback(0.1, "Start to parse.")
  246. sections = HtmlParser()(filename, binary)
  247. sections = [(_, "") for _ in sections if _]
  248. callback(0.8, "Finish parsing.")
  249. elif re.search(r"\.json$", filename, re.IGNORECASE):
  250. callback(0.1, "Start to parse.")
  251. chunk_token_num = int(parser_config.get("chunk_token_num", 128))
  252. sections = JsonParser(chunk_token_num)(binary)
  253. sections = [(_, "") for _ in sections if _]
  254. callback(0.8, "Finish parsing.")
  255. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  256. callback(0.1, "Start to parse.")
  257. binary = BytesIO(binary)
  258. doc_parsed = parser.from_buffer(binary)
  259. if doc_parsed.get('content', None) is not None:
  260. sections = doc_parsed['content'].split('\n')
  261. sections = [(_, "") for _ in sections if _]
  262. callback(0.8, "Finish parsing.")
  263. else:
  264. callback(0.8, f"tika.parser got empty content from {filename}.")
  265. logging.warning(f"tika.parser got empty content from {filename}.")
  266. return []
  267. else:
  268. raise NotImplementedError(
  269. "file type not supported yet(pdf, xlsx, doc, docx, txt supported)")
  270. st = timer()
  271. chunks = naive_merge(
  272. sections, int(parser_config.get(
  273. "chunk_token_num", 128)), parser_config.get(
  274. "delimiter", "\n!?。;!?"))
  275. if kwargs.get("section_only", False):
  276. return chunks
  277. res.extend(tokenize_chunks(chunks, doc, is_english, pdf_parser))
  278. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  279. return res
  280. if __name__ == "__main__":
  281. import sys
  282. def dummy(prog=None, msg=""):
  283. pass
  284. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)