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 11KB

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