Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

naive.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 deepdoc.parser import DocxParser, ExcelParser, HtmlParser, JsonParser, MarkdownParser, PdfParser, TxtParser
  27. from deepdoc.parser.pdf_parser import PlainParser
  28. from rag.nlp import concat_img, find_codec, naive_merge, naive_merge_docx, rag_tokenizer, tokenize_chunks, tokenize_chunks_docx, tokenize_table
  29. from rag.utils import num_tokens_from_string
  30. class Docx(DocxParser):
  31. def __init__(self):
  32. pass
  33. def get_picture(self, document, paragraph):
  34. img = paragraph._element.xpath('.//pic:pic')
  35. if not img:
  36. return None
  37. img = img[0]
  38. embed = img.xpath('.//a:blip/@r:embed')[0]
  39. related_part = document.part.related_parts[embed]
  40. try:
  41. image_blob = related_part.image.blob
  42. except UnrecognizedImageError:
  43. logging.info("Unrecognized image format. Skipping image.")
  44. return None
  45. except UnexpectedEndOfFileError:
  46. logging.info("EOF was unexpectedly encountered while reading an image stream. Skipping image.")
  47. return None
  48. except InvalidImageStreamError:
  49. logging.info("The recognized image stream appears to be corrupted. Skipping image.")
  50. return None
  51. try:
  52. image = Image.open(BytesIO(image_blob)).convert('RGB')
  53. return image
  54. except Exception:
  55. return None
  56. def __clean(self, line):
  57. line = re.sub(r"\u3000", " ", line).strip()
  58. return line
  59. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  60. self.doc = Document(
  61. filename) if not binary else Document(BytesIO(binary))
  62. pn = 0
  63. lines = []
  64. last_image = None
  65. for p in self.doc.paragraphs:
  66. if pn > to_page:
  67. break
  68. if from_page <= pn < to_page:
  69. if p.text.strip():
  70. if p.style and p.style.name == 'Caption':
  71. former_image = None
  72. if lines and lines[-1][1] and lines[-1][2] != 'Caption':
  73. former_image = lines[-1][1].pop()
  74. elif last_image:
  75. former_image = last_image
  76. last_image = None
  77. lines.append((self.__clean(p.text), [former_image], p.style.name))
  78. else:
  79. current_image = self.get_picture(self.doc, p)
  80. image_list = [current_image]
  81. if last_image:
  82. image_list.insert(0, last_image)
  83. last_image = None
  84. lines.append((self.__clean(p.text), image_list, p.style.name if p.style else ""))
  85. else:
  86. if current_image := self.get_picture(self.doc, p):
  87. if lines:
  88. lines[-1][1].append(current_image)
  89. else:
  90. last_image = current_image
  91. for run in p.runs:
  92. if 'lastRenderedPageBreak' in run._element.xml:
  93. pn += 1
  94. continue
  95. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  96. pn += 1
  97. new_line = [(line[0], reduce(concat_img, line[1]) if line[1] else None) for line in lines]
  98. tbls = []
  99. for tb in self.doc.tables:
  100. html = "<table>"
  101. for r in tb.rows:
  102. html += "<tr>"
  103. i = 0
  104. while i < len(r.cells):
  105. span = 1
  106. c = r.cells[i]
  107. for j in range(i + 1, len(r.cells)):
  108. if c.text == r.cells[j].text:
  109. span += 1
  110. i = j
  111. else:
  112. break
  113. i += 1
  114. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  115. html += "</tr>"
  116. html += "</table>"
  117. tbls.append(((None, html), ""))
  118. return new_line, tbls
  119. class Pdf(PdfParser):
  120. def __init__(self):
  121. super().__init__()
  122. def __call__(self, filename, binary=None, from_page=0,
  123. to_page=100000, zoomin=3, callback=None):
  124. start = timer()
  125. first_start = start
  126. callback(msg="OCR started")
  127. self.__images__(
  128. filename if not binary else binary,
  129. zoomin,
  130. from_page,
  131. to_page,
  132. callback
  133. )
  134. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  135. logging.info("OCR({}~{}): {:.2f}s".format(from_page, to_page, timer() - start))
  136. start = timer()
  137. self._layouts_rec(zoomin)
  138. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  139. start = timer()
  140. self._table_transformer_job(zoomin)
  141. callback(0.65, "Table analysis ({:.2f}s)".format(timer() - start))
  142. start = timer()
  143. self._text_merge()
  144. callback(0.67, "Text merged ({:.2f}s)".format(timer() - start))
  145. tbls = self._extract_table_figure(True, zoomin, True, True)
  146. # self._naive_vertical_merge()
  147. self._concat_downward()
  148. # self._filter_forpages()
  149. logging.info("layouts cost: {}s".format(timer() - first_start))
  150. return [(b["text"], self._line_tag(b, zoomin))
  151. for b in self.boxes], tbls
  152. class Markdown(MarkdownParser):
  153. def __call__(self, filename, binary=None):
  154. if binary:
  155. encoding = find_codec(binary)
  156. txt = binary.decode(encoding, errors="ignore")
  157. else:
  158. with open(filename, "r") as f:
  159. txt = f.read()
  160. remainder, tables = self.extract_tables_and_remainder(f'{txt}\n')
  161. sections = []
  162. tbls = []
  163. for sec in remainder.split("\n"):
  164. if num_tokens_from_string(sec) > 3 * self.chunk_token_num:
  165. sections.append((sec[:int(len(sec) / 2)], ""))
  166. sections.append((sec[int(len(sec) / 2):], ""))
  167. else:
  168. if sec.strip().find("#") == 0:
  169. sections.append((sec, ""))
  170. elif sections and sections[-1][0].strip().find("#") == 0:
  171. sec_, _ = sections.pop(-1)
  172. sections.append((sec_ + "\n" + sec, ""))
  173. else:
  174. sections.append((sec, ""))
  175. for table in tables:
  176. tbls.append(((None, markdown(table, extensions=['markdown.extensions.tables'])), ""))
  177. return sections, tbls
  178. def chunk(filename, binary=None, from_page=0, to_page=100000,
  179. lang="Chinese", callback=None, **kwargs):
  180. """
  181. Supported file formats are docx, pdf, excel, txt.
  182. This method apply the naive ways to chunk files.
  183. Successive text will be sliced into pieces using 'delimiter'.
  184. Next, these successive pieces are merge into chunks whose token number is no more than 'Max token number'.
  185. """
  186. is_english = lang.lower() == "english" # is_english(cks)
  187. parser_config = kwargs.get(
  188. "parser_config", {
  189. "chunk_token_num": 128, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  190. doc = {
  191. "docnm_kwd": filename,
  192. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  193. }
  194. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  195. res = []
  196. pdf_parser = None
  197. if re.search(r"\.docx$", filename, re.IGNORECASE):
  198. callback(0.1, "Start to parse.")
  199. sections, tables = Docx()(filename, binary)
  200. res = tokenize_table(tables, doc, is_english) # just for table
  201. callback(0.8, "Finish parsing.")
  202. st = timer()
  203. chunks, images = naive_merge_docx(
  204. sections, int(parser_config.get(
  205. "chunk_token_num", 128)), parser_config.get(
  206. "delimiter", "\n!?。;!?"))
  207. if kwargs.get("section_only", False):
  208. return chunks
  209. res.extend(tokenize_chunks_docx(chunks, doc, is_english, images))
  210. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  211. return res
  212. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  213. pdf_parser = Pdf()
  214. if parser_config.get("layout_recognize", "DeepDOC") == "Plain Text":
  215. pdf_parser = PlainParser()
  216. sections, tables = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page,
  217. callback=callback)
  218. res = tokenize_table(tables, doc, is_english)
  219. elif re.search(r"\.(csv|xlsx?)$", filename, re.IGNORECASE):
  220. callback(0.1, "Start to parse.")
  221. excel_parser = ExcelParser()
  222. if parser_config.get("html4excel"):
  223. sections = [(_, "") for _ in excel_parser.html(binary, 12) if _]
  224. else:
  225. sections = [(_, "") for _ in excel_parser(binary) if _]
  226. elif re.search(r"\.(txt|py|js|java|c|cpp|h|php|go|ts|sh|cs|kt|sql)$", filename, re.IGNORECASE):
  227. callback(0.1, "Start to parse.")
  228. sections = TxtParser()(filename, binary,
  229. parser_config.get("chunk_token_num", 128),
  230. parser_config.get("delimiter", "\n!?;。;!?"))
  231. callback(0.8, "Finish parsing.")
  232. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  233. callback(0.1, "Start to parse.")
  234. sections, tables = Markdown(int(parser_config.get("chunk_token_num", 128)))(filename, binary)
  235. res = tokenize_table(tables, doc, is_english)
  236. callback(0.8, "Finish parsing.")
  237. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  238. callback(0.1, "Start to parse.")
  239. sections = HtmlParser()(filename, binary)
  240. sections = [(_, "") for _ in sections if _]
  241. callback(0.8, "Finish parsing.")
  242. elif re.search(r"\.json$", filename, re.IGNORECASE):
  243. callback(0.1, "Start to parse.")
  244. chunk_token_num = int(parser_config.get("chunk_token_num", 128))
  245. sections = JsonParser(chunk_token_num)(binary)
  246. sections = [(_, "") for _ in sections if _]
  247. callback(0.8, "Finish parsing.")
  248. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  249. callback(0.1, "Start to parse.")
  250. binary = BytesIO(binary)
  251. doc_parsed = parser.from_buffer(binary)
  252. if doc_parsed.get('content', None) is not None:
  253. sections = doc_parsed['content'].split('\n')
  254. sections = [(_, "") for _ in sections if _]
  255. callback(0.8, "Finish parsing.")
  256. else:
  257. callback(0.8, f"tika.parser got empty content from {filename}.")
  258. logging.warning(f"tika.parser got empty content from {filename}.")
  259. return []
  260. else:
  261. raise NotImplementedError(
  262. "file type not supported yet(pdf, xlsx, doc, docx, txt supported)")
  263. st = timer()
  264. chunks = naive_merge(
  265. sections, int(parser_config.get(
  266. "chunk_token_num", 128)), parser_config.get(
  267. "delimiter", "\n!?。;!?"))
  268. if kwargs.get("section_only", False):
  269. return chunks
  270. res.extend(tokenize_chunks(chunks, doc, is_english, pdf_parser))
  271. logging.info("naive_merge({}): {}".format(filename, timer() - st))
  272. return res
  273. if __name__ == "__main__":
  274. import sys
  275. def dummy(prog=None, msg=""):
  276. pass
  277. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)