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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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.figure_parser import VisionFigureParser, vision_figure_parser_figure_data_wraper
  30. from deepdoc.parser.pdf_parser import PlainParser, VisionParser
  31. from rag.nlp import concat_img, find_codec, naive_merge, naive_merge_docx, rag_tokenizer, tokenize_chunks, tokenize_chunks_docx, tokenize_table
  32. from rag.utils import num_tokens_from_string
  33. class Docx(DocxParser):
  34. def __init__(self):
  35. pass
  36. def get_picture(self, document, paragraph):
  37. img = paragraph._element.xpath('.//pic:pic')
  38. if not img:
  39. return None
  40. img = img[0]
  41. embed = img.xpath('.//a:blip/@r:embed')[0]
  42. related_part = document.part.related_parts[embed]
  43. try:
  44. image_blob = related_part.image.blob
  45. except UnrecognizedImageError:
  46. logging.info("Unrecognized image format. Skipping image.")
  47. return None
  48. except UnexpectedEndOfFileError:
  49. logging.info("EOF was unexpectedly encountered while reading an image stream. Skipping image.")
  50. return None
  51. except InvalidImageStreamError:
  52. logging.info("The recognized image stream appears to be corrupted. Skipping image.")
  53. return None
  54. try:
  55. image = Image.open(BytesIO(image_blob)).convert('RGB')
  56. return image
  57. except Exception:
  58. return None
  59. def __clean(self, line):
  60. line = re.sub(r"\u3000", " ", line).strip()
  61. return line
  62. def __get_nearest_title(self, table_index, filename):
  63. """Get the hierarchical title structure before the table"""
  64. import re
  65. from docx.text.paragraph import Paragraph
  66. titles = []
  67. blocks = []
  68. # Get document name from filename parameter
  69. doc_name = re.sub(r"\.[a-zA-Z]+$", "", filename)
  70. if not doc_name:
  71. doc_name = "Untitled Document"
  72. # Collect all document blocks while maintaining document order
  73. try:
  74. # Iterate through all paragraphs and tables in document order
  75. for i, block in enumerate(self.doc._element.body):
  76. if block.tag.endswith('p'): # Paragraph
  77. p = Paragraph(block, self.doc)
  78. blocks.append(('p', i, p))
  79. elif block.tag.endswith('tbl'): # Table
  80. blocks.append(('t', i, None)) # Table object will be retrieved later
  81. except Exception as e:
  82. logging.error(f"Error collecting blocks: {e}")
  83. return ""
  84. # Find the target table position
  85. target_table_pos = -1
  86. table_count = 0
  87. for i, (block_type, pos, _) in enumerate(blocks):
  88. if block_type == 't':
  89. if table_count == table_index:
  90. target_table_pos = pos
  91. break
  92. table_count += 1
  93. if target_table_pos == -1:
  94. return "" # Target table not found
  95. # Find the nearest heading paragraph in reverse order
  96. nearest_title = None
  97. for i in range(len(blocks)-1, -1, -1):
  98. block_type, pos, block = blocks[i]
  99. if pos >= target_table_pos: # Skip blocks after the table
  100. continue
  101. if block_type != 'p':
  102. continue
  103. if block.style and re.search(r"Heading\s*(\d+)", block.style.name, re.I):
  104. try:
  105. level_match = re.search(r"(\d+)", block.style.name)
  106. if level_match:
  107. level = int(level_match.group(1))
  108. if level <= 7: # Support up to 7 heading levels
  109. title_text = block.text.strip()
  110. if title_text: # Avoid empty titles
  111. nearest_title = (level, title_text)
  112. break
  113. except Exception as e:
  114. logging.error(f"Error parsing heading level: {e}")
  115. if nearest_title:
  116. # Add current title
  117. titles.append(nearest_title)
  118. current_level = nearest_title[0]
  119. # Find all parent headings, allowing cross-level search
  120. while current_level > 1:
  121. found = False
  122. for i in range(len(blocks)-1, -1, -1):
  123. block_type, pos, block = blocks[i]
  124. if pos >= target_table_pos: # Skip blocks after the table
  125. continue
  126. if block_type != 'p':
  127. continue
  128. if block.style and re.search(r"Heading\s*(\d+)", block.style.name, re.I):
  129. try:
  130. level_match = re.search(r"(\d+)", block.style.name)
  131. if level_match:
  132. level = int(level_match.group(1))
  133. # Find any heading with a higher level
  134. if level < current_level:
  135. title_text = block.text.strip()
  136. if title_text: # Avoid empty titles
  137. titles.append((level, title_text))
  138. current_level = level
  139. found = True
  140. break
  141. except Exception as e:
  142. logging.error(f"Error parsing parent heading: {e}")
  143. if not found: # Break if no parent heading is found
  144. break
  145. # Sort by level (ascending, from highest to lowest)
  146. titles.sort(key=lambda x: x[0])
  147. # Organize titles (from highest to lowest)
  148. hierarchy = [doc_name] + [t[1] for t in titles]
  149. return " > ".join(hierarchy)
  150. return ""
  151. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  152. self.doc = Document(
  153. filename) if not binary else Document(BytesIO(binary))
  154. pn = 0
  155. lines = []
  156. last_image = None
  157. for p in self.doc.paragraphs:
  158. if pn > to_page:
  159. break
  160. if from_page <= pn < to_page:
  161. if p.text.strip():
  162. if p.style and p.style.name == 'Caption':
  163. former_image = None
  164. if lines and lines[-1][1] and lines[-1][2] != 'Caption':
  165. former_image = lines[-1][1].pop()
  166. elif last_image:
  167. former_image = last_image
  168. last_image = None
  169. lines.append((self.__clean(p.text), [former_image], p.style.name))
  170. else:
  171. current_image = self.get_picture(self.doc, p)
  172. image_list = [current_image]
  173. if last_image:
  174. image_list.insert(0, last_image)
  175. last_image = None
  176. lines.append((self.__clean(p.text), image_list, p.style.name if p.style else ""))
  177. else:
  178. if current_image := self.get_picture(self.doc, p):
  179. if lines:
  180. lines[-1][1].append(current_image)
  181. else:
  182. last_image = current_image
  183. for run in p.runs:
  184. if 'lastRenderedPageBreak' in run._element.xml:
  185. pn += 1
  186. continue
  187. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  188. pn += 1
  189. new_line = [(line[0], reduce(concat_img, line[1]) if line[1] else None) for line in lines]
  190. tbls = []
  191. for i, tb in enumerate(self.doc.tables):
  192. title = self.__get_nearest_title(i, filename)
  193. html = "<table>"
  194. if title:
  195. html += f"<caption>Table Location: {title}</caption>"
  196. for r in tb.rows:
  197. html += "<tr>"
  198. i = 0
  199. while i < len(r.cells):
  200. span = 1
  201. c = r.cells[i]
  202. for j in range(i + 1, len(r.cells)):
  203. if c.text == r.cells[j].text:
  204. span += 1
  205. i = j
  206. else:
  207. break
  208. i += 1
  209. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  210. html += "</tr>"
  211. html += "</table>"
  212. tbls.append(((None, html), ""))
  213. return new_line, tbls
  214. class Pdf(PdfParser):
  215. def __init__(self):
  216. super().__init__()
  217. def __call__(self, filename, binary=None, from_page=0,
  218. to_page=100000, zoomin=3, callback=None, separate_tables_figures=False):
  219. start = timer()
  220. first_start = start
  221. callback(msg="OCR started")
  222. self.__images__(
  223. filename if not binary else binary,
  224. zoomin,
  225. from_page,
  226. to_page,
  227. callback
  228. )
  229. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  230. logging.info("OCR({}~{}): {:.2f}s".format(from_page, to_page, timer() - start))
  231. start = timer()
  232. self._layouts_rec(zoomin)
  233. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  234. start = timer()
  235. self._table_transformer_job(zoomin)
  236. callback(0.65, "Table analysis ({:.2f}s)".format(timer() - start))
  237. start = timer()
  238. self._text_merge()
  239. callback(0.67, "Text merged ({:.2f}s)".format(timer() - start))
  240. if separate_tables_figures:
  241. tbls, figures = self._extract_table_figure(True, zoomin, True, True, True)
  242. self._concat_downward()
  243. logging.info("layouts cost: {}s".format(timer() - first_start))
  244. return [(b["text"], self._line_tag(b, zoomin)) for b in self.boxes], tbls, figures
  245. else:
  246. tbls = self._extract_table_figure(True, zoomin, True, True)
  247. # self._naive_vertical_merge()
  248. self._concat_downward()
  249. # self._filter_forpages()
  250. logging.info("layouts cost: {}s".format(timer() - first_start))
  251. return [(b["text"], self._line_tag(b, zoomin)) for b in self.boxes], tbls
  252. class Markdown(MarkdownParser):
  253. def __call__(self, filename, binary=None):
  254. if binary:
  255. encoding = find_codec(binary)
  256. txt = binary.decode(encoding, errors="ignore")
  257. else:
  258. with open(filename, "r") as f:
  259. txt = f.read()
  260. remainder, tables = self.extract_tables_and_remainder(f'{txt}\n')
  261. sections = []
  262. tbls = []
  263. for sec in remainder.split("\n"):
  264. if num_tokens_from_string(sec) > 3 * self.chunk_token_num:
  265. sections.append((sec[:int(len(sec) / 2)], ""))
  266. sections.append((sec[int(len(sec) / 2):], ""))
  267. else:
  268. if sec.strip().find("#") == 0:
  269. sections.append((sec, ""))
  270. elif sections and sections[-1][0].strip().find("#") == 0:
  271. sec_, _ = sections.pop(-1)
  272. sections.append((sec_ + "\n" + sec, ""))
  273. else:
  274. sections.append((sec, ""))
  275. for table in tables:
  276. tbls.append(((None, markdown(table, extensions=['markdown.extensions.tables'])), ""))
  277. return sections, tbls
  278. def chunk(filename, binary=None, from_page=0, to_page=100000,
  279. lang="Chinese", callback=None, **kwargs):
  280. """
  281. Supported file formats are docx, pdf, excel, txt.
  282. This method apply the naive ways to chunk files.
  283. Successive text will be sliced into pieces using 'delimiter'.
  284. Next, these successive pieces are merge into chunks whose token number is no more than 'Max token number'.
  285. """
  286. is_english = lang.lower() == "english" # is_english(cks)
  287. parser_config = kwargs.get(
  288. "parser_config", {
  289. "chunk_token_num": 128, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  290. doc = {
  291. "docnm_kwd": filename,
  292. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  293. }
  294. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  295. res = []
  296. pdf_parser = None
  297. if re.search(r"\.docx$", filename, re.IGNORECASE):
  298. callback(0.1, "Start to parse.")
  299. try:
  300. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT)
  301. callback(0.15, "Visual model detected. Attempting to enhance figure extraction...")
  302. except Exception:
  303. vision_model = None
  304. sections, tables = Docx()(filename, binary)
  305. if vision_model:
  306. figures_data = vision_figure_parser_figure_data_wraper(sections)
  307. try:
  308. docx_vision_parser = VisionFigureParser(vision_model=vision_model, figures_data=figures_data, **kwargs)
  309. boosted_figures = docx_vision_parser(callback=callback)
  310. tables.extend(boosted_figures)
  311. except Exception as e:
  312. callback(0.6, f"Visual model error: {e}. Skipping figure parsing enhancement.")
  313. res = tokenize_table(tables, doc, is_english)
  314. callback(0.8, "Finish parsing.")
  315. st = timer()
  316. chunks, images = naive_merge_docx(
  317. sections, int(parser_config.get(
  318. "chunk_token_num", 128)), parser_config.get(
  319. "delimiter", "\n!?。;!?"))
  320. if kwargs.get("section_only", False):
  321. return chunks
  322. res.extend(tokenize_chunks_docx(chunks, doc, is_english, images))
  323. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  324. return res
  325. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  326. layout_recognizer = parser_config.get("layout_recognize", "DeepDOC")
  327. if isinstance(layout_recognizer, bool):
  328. layout_recognizer = "DeepDOC" if layout_recognizer else "Plain Text"
  329. callback(0.1, "Start to parse.")
  330. if layout_recognizer == "DeepDOC":
  331. pdf_parser = Pdf()
  332. try:
  333. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT)
  334. callback(0.15, "Visual model detected. Attempting to enhance figure extraction...")
  335. except Exception:
  336. vision_model = None
  337. if vision_model:
  338. sections, tables, figures = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page, callback=callback, separate_tables_figures=True)
  339. callback(0.5, "Basic parsing complete. Proceeding with figure enhancement...")
  340. try:
  341. pdf_vision_parser = VisionFigureParser(vision_model=vision_model, figures_data=figures, **kwargs)
  342. boosted_figures = pdf_vision_parser(callback=callback)
  343. tables.extend(boosted_figures)
  344. except Exception as e:
  345. callback(0.6, f"Visual model error: {e}. Skipping figure parsing enhancement.")
  346. tables.extend(figures)
  347. else:
  348. sections, tables = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page, callback=callback)
  349. res = tokenize_table(tables, doc, is_english)
  350. callback(0.8, "Finish parsing.")
  351. else:
  352. if layout_recognizer == "Plain Text":
  353. pdf_parser = PlainParser()
  354. else:
  355. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT, llm_name=layout_recognizer, lang=lang)
  356. pdf_parser = VisionParser(vision_model=vision_model, **kwargs)
  357. sections, tables = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page,
  358. callback=callback)
  359. res = tokenize_table(tables, doc, is_english)
  360. callback(0.8, "Finish parsing.")
  361. elif re.search(r"\.(csv|xlsx?)$", filename, re.IGNORECASE):
  362. callback(0.1, "Start to parse.")
  363. excel_parser = ExcelParser()
  364. if parser_config.get("html4excel"):
  365. sections = [(_, "") for _ in excel_parser.html(binary, 12) if _]
  366. else:
  367. sections = [(_, "") for _ in excel_parser(binary) if _]
  368. elif re.search(r"\.(txt|py|js|java|c|cpp|h|php|go|ts|sh|cs|kt|sql)$", filename, re.IGNORECASE):
  369. callback(0.1, "Start to parse.")
  370. sections = TxtParser()(filename, binary,
  371. parser_config.get("chunk_token_num", 128),
  372. parser_config.get("delimiter", "\n!?;。;!?"))
  373. callback(0.8, "Finish parsing.")
  374. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  375. callback(0.1, "Start to parse.")
  376. sections, tables = Markdown(int(parser_config.get("chunk_token_num", 128)))(filename, binary)
  377. res = tokenize_table(tables, doc, is_english)
  378. callback(0.8, "Finish parsing.")
  379. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  380. callback(0.1, "Start to parse.")
  381. sections = HtmlParser()(filename, binary)
  382. sections = [(_, "") for _ in sections if _]
  383. callback(0.8, "Finish parsing.")
  384. elif re.search(r"\.json$", filename, re.IGNORECASE):
  385. callback(0.1, "Start to parse.")
  386. chunk_token_num = int(parser_config.get("chunk_token_num", 128))
  387. sections = JsonParser(chunk_token_num)(binary)
  388. sections = [(_, "") for _ in sections if _]
  389. callback(0.8, "Finish parsing.")
  390. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  391. callback(0.1, "Start to parse.")
  392. binary = BytesIO(binary)
  393. doc_parsed = parser.from_buffer(binary)
  394. if doc_parsed.get('content', None) is not None:
  395. sections = doc_parsed['content'].split('\n')
  396. sections = [(_, "") for _ in sections if _]
  397. callback(0.8, "Finish parsing.")
  398. else:
  399. callback(0.8, f"tika.parser got empty content from {filename}.")
  400. logging.warning(f"tika.parser got empty content from {filename}.")
  401. return []
  402. else:
  403. raise NotImplementedError(
  404. "file type not supported yet(pdf, xlsx, doc, docx, txt supported)")
  405. st = timer()
  406. chunks = naive_merge(
  407. sections, int(parser_config.get(
  408. "chunk_token_num", 128)), parser_config.get(
  409. "delimiter", "\n!?。;!?"))
  410. if kwargs.get("section_only", False):
  411. return chunks
  412. res.extend(tokenize_chunks(chunks, doc, is_english, pdf_parser))
  413. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  414. return res
  415. if __name__ == "__main__":
  416. import sys
  417. def dummy(prog=None, msg=""):
  418. pass
  419. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)