您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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')
  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 __call__(self, filename, binary=None):
  257. if binary:
  258. encoding = find_codec(binary)
  259. txt = binary.decode(encoding, errors="ignore")
  260. else:
  261. with open(filename, "r") as f:
  262. txt = f.read()
  263. remainder, tables = self.extract_tables_and_remainder(f'{txt}\n')
  264. sections = []
  265. tbls = []
  266. for sec in remainder.split("\n"):
  267. if num_tokens_from_string(sec) > 3 * self.chunk_token_num:
  268. sections.append((sec[:int(len(sec) / 2)], ""))
  269. sections.append((sec[int(len(sec) / 2):], ""))
  270. else:
  271. if sec.strip().find("#") == 0:
  272. sections.append((sec, ""))
  273. elif sections and sections[-1][0].strip().find("#") == 0:
  274. sec_, _ = sections.pop(-1)
  275. sections.append((sec_ + "\n" + sec, ""))
  276. else:
  277. sections.append((sec, ""))
  278. for table in tables:
  279. tbls.append(((None, markdown(table, extensions=['markdown.extensions.tables'])), ""))
  280. return sections, tbls
  281. def chunk(filename, binary=None, from_page=0, to_page=100000,
  282. lang="Chinese", callback=None, **kwargs):
  283. """
  284. Supported file formats are docx, pdf, excel, txt.
  285. This method apply the naive ways to chunk files.
  286. Successive text will be sliced into pieces using 'delimiter'.
  287. Next, these successive pieces are merge into chunks whose token number is no more than 'Max token number'.
  288. """
  289. is_english = lang.lower() == "english" # is_english(cks)
  290. parser_config = kwargs.get(
  291. "parser_config", {
  292. "chunk_token_num": 128, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  293. doc = {
  294. "docnm_kwd": filename,
  295. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  296. }
  297. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  298. res = []
  299. pdf_parser = None
  300. if re.search(r"\.docx$", filename, re.IGNORECASE):
  301. callback(0.1, "Start to parse.")
  302. try:
  303. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT)
  304. callback(0.15, "Visual model detected. Attempting to enhance figure extraction...")
  305. except Exception:
  306. vision_model = None
  307. sections, tables = Docx()(filename, binary)
  308. if vision_model:
  309. figures_data = vision_figure_parser_figure_data_wraper(sections)
  310. try:
  311. docx_vision_parser = VisionFigureParser(vision_model=vision_model, figures_data=figures_data, **kwargs)
  312. boosted_figures = docx_vision_parser(callback=callback)
  313. tables.extend(boosted_figures)
  314. except Exception as e:
  315. callback(0.6, f"Visual model error: {e}. Skipping figure parsing enhancement.")
  316. res = tokenize_table(tables, doc, is_english)
  317. callback(0.8, "Finish parsing.")
  318. st = timer()
  319. chunks, images = naive_merge_docx(
  320. sections, int(parser_config.get(
  321. "chunk_token_num", 128)), parser_config.get(
  322. "delimiter", "\n!?。;!?"))
  323. if kwargs.get("section_only", False):
  324. return chunks
  325. res.extend(tokenize_chunks_docx(chunks, doc, is_english, images))
  326. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  327. return res
  328. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  329. layout_recognizer = parser_config.get("layout_recognize", "DeepDOC")
  330. if isinstance(layout_recognizer, bool):
  331. layout_recognizer = "DeepDOC" if layout_recognizer else "Plain Text"
  332. callback(0.1, "Start to parse.")
  333. if layout_recognizer == "DeepDOC":
  334. pdf_parser = Pdf()
  335. try:
  336. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT)
  337. callback(0.15, "Visual model detected. Attempting to enhance figure extraction...")
  338. except Exception:
  339. vision_model = None
  340. if vision_model:
  341. 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)
  342. callback(0.5, "Basic parsing complete. Proceeding with figure enhancement...")
  343. try:
  344. pdf_vision_parser = VisionFigureParser(vision_model=vision_model, figures_data=figures, **kwargs)
  345. boosted_figures = pdf_vision_parser(callback=callback)
  346. tables.extend(boosted_figures)
  347. except Exception as e:
  348. callback(0.6, f"Visual model error: {e}. Skipping figure parsing enhancement.")
  349. tables.extend(figures)
  350. else:
  351. sections, tables = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page, callback=callback)
  352. res = tokenize_table(tables, doc, is_english)
  353. callback(0.8, "Finish parsing.")
  354. else:
  355. if layout_recognizer == "Plain Text":
  356. pdf_parser = PlainParser()
  357. else:
  358. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT, llm_name=layout_recognizer, lang=lang)
  359. pdf_parser = VisionParser(vision_model=vision_model, **kwargs)
  360. sections, tables = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page,
  361. callback=callback)
  362. res = tokenize_table(tables, doc, is_english)
  363. callback(0.8, "Finish parsing.")
  364. elif re.search(r"\.(csv|xlsx?)$", filename, re.IGNORECASE):
  365. callback(0.1, "Start to parse.")
  366. excel_parser = ExcelParser()
  367. if parser_config.get("html4excel"):
  368. sections = [(_, "") for _ in excel_parser.html(binary, 12) if _]
  369. else:
  370. sections = [(_, "") for _ in excel_parser(binary) if _]
  371. elif re.search(r"\.(txt|py|js|java|c|cpp|h|php|go|ts|sh|cs|kt|sql)$", filename, re.IGNORECASE):
  372. callback(0.1, "Start to parse.")
  373. sections = TxtParser()(filename, binary,
  374. parser_config.get("chunk_token_num", 128),
  375. parser_config.get("delimiter", "\n!?;。;!?"))
  376. callback(0.8, "Finish parsing.")
  377. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  378. callback(0.1, "Start to parse.")
  379. sections, tables = Markdown(int(parser_config.get("chunk_token_num", 128)))(filename, binary)
  380. res = tokenize_table(tables, doc, is_english)
  381. callback(0.8, "Finish parsing.")
  382. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  383. callback(0.1, "Start to parse.")
  384. sections = HtmlParser()(filename, binary)
  385. sections = [(_, "") for _ in sections if _]
  386. callback(0.8, "Finish parsing.")
  387. elif re.search(r"\.json$", filename, re.IGNORECASE):
  388. callback(0.1, "Start to parse.")
  389. chunk_token_num = int(parser_config.get("chunk_token_num", 128))
  390. sections = JsonParser(chunk_token_num)(binary)
  391. sections = [(_, "") for _ in sections if _]
  392. callback(0.8, "Finish parsing.")
  393. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  394. callback(0.1, "Start to parse.")
  395. binary = BytesIO(binary)
  396. doc_parsed = parser.from_buffer(binary)
  397. if doc_parsed.get('content', None) is not None:
  398. sections = doc_parsed['content'].split('\n')
  399. sections = [(_, "") for _ in sections if _]
  400. callback(0.8, "Finish parsing.")
  401. else:
  402. callback(0.8, f"tika.parser got empty content from {filename}.")
  403. logging.warning(f"tika.parser got empty content from {filename}.")
  404. return []
  405. else:
  406. raise NotImplementedError(
  407. "file type not supported yet(pdf, xlsx, doc, docx, txt supported)")
  408. st = timer()
  409. chunks = naive_merge(
  410. sections, int(parser_config.get(
  411. "chunk_token_num", 128)), parser_config.get(
  412. "delimiter", "\n!?。;!?"))
  413. if kwargs.get("section_only", False):
  414. return chunks
  415. res.extend(tokenize_chunks(chunks, doc, is_english, pdf_parser))
  416. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  417. return res
  418. if __name__ == "__main__":
  419. import sys
  420. def dummy(prog=None, msg=""):
  421. pass
  422. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)