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.

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