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

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