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.

naive.py 12KB

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