Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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
  20. from deepdoc.parser import PdfParser, ExcelParser, DocxParser
  21. from rag.settings import cron_logger
  22. class Docx(DocxParser):
  23. def __init__(self):
  24. pass
  25. def __clean(self, line):
  26. line = re.sub(r"\u3000", " ", line).strip()
  27. return line
  28. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  29. self.doc = Document(
  30. filename) if not binary else Document(BytesIO(binary))
  31. pn = 0
  32. lines = []
  33. for p in self.doc.paragraphs:
  34. if pn > to_page:
  35. break
  36. if from_page <= pn < to_page and p.text.strip():
  37. lines.append(self.__clean(p.text))
  38. for run in p.runs:
  39. if 'lastRenderedPageBreak' in run._element.xml:
  40. pn += 1
  41. continue
  42. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  43. pn += 1
  44. tbls = []
  45. for tb in self.doc.tables:
  46. html= "<table>"
  47. for r in tb.rows:
  48. html += "<tr>"
  49. i = 0
  50. while i < len(r.cells):
  51. span = 1
  52. c = r.cells[i]
  53. for j in range(i+1, len(r.cells)):
  54. if c.text == r.cells[j].text:
  55. span += 1
  56. i = j
  57. i += 1
  58. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  59. html += "</tr>"
  60. html += "</table>"
  61. tbls.append(((None, html), ""))
  62. return [(l, "") for l in lines if l], tbls
  63. class Pdf(PdfParser):
  64. def __call__(self, filename, binary=None, from_page=0,
  65. to_page=100000, zoomin=3, callback=None):
  66. start = timer()
  67. callback(msg="OCR is running...")
  68. self.__images__(
  69. filename if not binary else binary,
  70. zoomin,
  71. from_page,
  72. to_page,
  73. callback
  74. )
  75. callback(msg="OCR finished")
  76. cron_logger.info("OCR({}~{}): {}".format(from_page, to_page, timer() - start))
  77. start = timer()
  78. self._layouts_rec(zoomin)
  79. callback(0.63, "Layout analysis finished.")
  80. self._table_transformer_job(zoomin)
  81. callback(0.65, "Table analysis finished.")
  82. self._text_merge()
  83. callback(0.67, "Text merging finished")
  84. tbls = self._extract_table_figure(True, zoomin, True, True)
  85. #self._naive_vertical_merge()
  86. self._concat_downward()
  87. #self._filter_forpages()
  88. cron_logger.info("layouts: {}".format(timer() - start))
  89. return [(b["text"], self._line_tag(b, zoomin))
  90. for b in self.boxes], tbls
  91. def chunk(filename, binary=None, from_page=0, to_page=100000,
  92. lang="Chinese", callback=None, **kwargs):
  93. """
  94. Supported file formats are docx, pdf, excel, txt.
  95. This method apply the naive ways to chunk files.
  96. Successive text will be sliced into pieces using 'delimiter'.
  97. Next, these successive pieces are merge into chunks whose token number is no more than 'Max token number'.
  98. """
  99. eng = lang.lower() == "english" # is_english(cks)
  100. parser_config = kwargs.get(
  101. "parser_config", {
  102. "chunk_token_num": 128, "delimiter": "\n!?。;!?", "layout_recognize": True})
  103. doc = {
  104. "docnm_kwd": filename,
  105. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  106. }
  107. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  108. res = []
  109. pdf_parser = None
  110. sections = []
  111. if re.search(r"\.docx$", filename, re.IGNORECASE):
  112. callback(0.1, "Start to parse.")
  113. sections, tbls = Docx()(filename, binary)
  114. res = tokenize_table(tbls, doc, eng)
  115. callback(0.8, "Finish parsing.")
  116. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  117. pdf_parser = Pdf(
  118. ) if parser_config.get("layout_recognize", True) else PlainParser()
  119. sections, tbls = pdf_parser(filename if not binary else binary,
  120. from_page=from_page, to_page=to_page, callback=callback)
  121. res = tokenize_table(tbls, doc, eng)
  122. elif re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  123. callback(0.1, "Start to parse.")
  124. excel_parser = ExcelParser()
  125. sections = [(excel_parser.html(binary), "")]
  126. elif re.search(r"\.(txt|md)$", filename, re.IGNORECASE):
  127. callback(0.1, "Start to parse.")
  128. txt = ""
  129. if binary:
  130. encoding = find_codec(binary)
  131. txt = binary.decode(encoding, errors="ignore")
  132. else:
  133. with open(filename, "r") as f:
  134. while True:
  135. l = f.readline()
  136. if not l:
  137. break
  138. txt += l
  139. sections = txt.split("\n")
  140. sections = [(l, "") for l in sections if l]
  141. callback(0.8, "Finish parsing.")
  142. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  143. callback(0.1, "Start to parse.")
  144. binary = BytesIO(binary)
  145. doc_parsed = parser.from_buffer(binary)
  146. sections = doc_parsed['content'].split('\n')
  147. sections = [(l, "") for l in sections if l]
  148. callback(0.8, "Finish parsing.")
  149. else:
  150. raise NotImplementedError(
  151. "file type not supported yet(doc, docx, pdf, txt supported)")
  152. st = timer()
  153. chunks = naive_merge(
  154. sections, parser_config.get(
  155. "chunk_token_num", 128), parser_config.get(
  156. "delimiter", "\n!?。;!?"))
  157. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  158. cron_logger.info("naive_merge({}): {}".format(filename, timer() - st))
  159. return res
  160. if __name__ == "__main__":
  161. import sys
  162. def dummy(prog=None, msg=""):
  163. pass
  164. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)