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.

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