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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 io import BytesIO
  14. from docx import Document
  15. import re
  16. from deepdoc.parser.pdf_parser import PlainParser
  17. from rag.app import laws
  18. from rag.nlp import huqie, is_english, tokenize, naive_merge, tokenize_table, add_positions, tokenize_chunks
  19. from deepdoc.parser import PdfParser, ExcelParser, DocxParser
  20. from rag.settings import cron_logger
  21. class Docx(DocxParser):
  22. def __init__(self):
  23. pass
  24. def __clean(self, line):
  25. line = re.sub(r"\u3000", " ", line).strip()
  26. return line
  27. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  28. self.doc = Document(
  29. filename) if not binary else Document(BytesIO(binary))
  30. pn = 0
  31. lines = []
  32. for p in self.doc.paragraphs:
  33. if pn > to_page:
  34. break
  35. if from_page <= pn < to_page and p.text.strip():
  36. lines.append(self.__clean(p.text))
  37. for run in p.runs:
  38. if 'lastRenderedPageBreak' in run._element.xml:
  39. pn += 1
  40. continue
  41. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  42. pn += 1
  43. tbls = []
  44. for tb in self.doc.tables:
  45. html= "<table>"
  46. for r in tb.rows:
  47. html += "<tr>"
  48. i = 0
  49. while i < len(r.cells):
  50. span = 1
  51. c = r.cells[i]
  52. for j in range(i+1, len(r.cells)):
  53. if c.text == r.cells[j].text:
  54. span += 1
  55. i = j
  56. i += 1
  57. html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
  58. html += "</tr>"
  59. html += "</table>"
  60. tbls.append(((None, html), ""))
  61. return [(l, "") for l in lines if l], tbls
  62. class Pdf(PdfParser):
  63. def __call__(self, filename, binary=None, from_page=0,
  64. to_page=100000, zoomin=3, callback=None):
  65. callback(msg="OCR is running...")
  66. self.__images__(
  67. filename if not binary else binary,
  68. zoomin,
  69. from_page,
  70. to_page,
  71. callback
  72. )
  73. callback(msg="OCR finished")
  74. from timeit import default_timer as timer
  75. start = timer()
  76. self._layouts_rec(zoomin)
  77. callback(0.63, "Layout analysis finished.")
  78. print("paddle layouts:", timer() - start)
  79. self._table_transformer_job(zoomin)
  80. callback(0.65, "Table analysis finished.")
  81. self._text_merge()
  82. callback(0.67, "Text merging finished")
  83. tbls = self._extract_table_figure(True, zoomin, True, True)
  84. #self._naive_vertical_merge()
  85. self._concat_downward()
  86. #self._filter_forpages()
  87. cron_logger.info("paddle layouts:".format(
  88. (timer() - start) / (self.total_page + 0.1)))
  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": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  106. }
  107. doc["title_sm_tks"] = huqie.qieqie(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$", filename, re.IGNORECASE):
  127. callback(0.1, "Start to parse.")
  128. txt = ""
  129. if binary:
  130. txt = binary.decode("utf-8")
  131. else:
  132. with open(filename, "r") as f:
  133. while True:
  134. l = f.readline()
  135. if not l:
  136. break
  137. txt += l
  138. sections = txt.split("\n")
  139. sections = [(l, "") for l in sections if l]
  140. callback(0.8, "Finish parsing.")
  141. else:
  142. raise NotImplementedError(
  143. "file type not supported yet(docx, pdf, txt supported)")
  144. chunks = naive_merge(
  145. sections, parser_config.get(
  146. "chunk_token_num", 128), parser_config.get(
  147. "delimiter", "\n!?。;!?"))
  148. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  149. return res
  150. if __name__ == "__main__":
  151. import sys
  152. def dummy(prog=None, msg=""):
  153. pass
  154. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)