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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. import copy
  14. import re
  15. from deepdoc.parser.pdf_parser import PlainParser
  16. from rag.app import laws
  17. from rag.nlp import huqie, is_english, tokenize, naive_merge, tokenize_table, add_positions, tokenize_chunks
  18. from deepdoc.parser import PdfParser, ExcelParser
  19. from rag.settings import cron_logger
  20. class Pdf(PdfParser):
  21. def __call__(self, filename, binary=None, from_page=0,
  22. to_page=100000, zoomin=3, callback=None):
  23. callback(msg="OCR is running...")
  24. self.__images__(
  25. filename if not binary else binary,
  26. zoomin,
  27. from_page,
  28. to_page,
  29. callback
  30. )
  31. callback(msg="OCR finished")
  32. from timeit import default_timer as timer
  33. start = timer()
  34. self._layouts_rec(zoomin)
  35. callback(0.63, "Layout analysis finished.")
  36. print("paddle layouts:", timer() - start)
  37. self._table_transformer_job(zoomin)
  38. callback(0.65, "Table analysis finished.")
  39. self._text_merge()
  40. callback(0.67, "Text merging finished")
  41. tbls = self._extract_table_figure(True, zoomin, True, True)
  42. self._naive_vertical_merge()
  43. cron_logger.info("paddle layouts:".format(
  44. (timer() - start) / (self.total_page + 0.1)))
  45. return [(b["text"], self._line_tag(b, zoomin))
  46. for b in self.boxes], tbls
  47. def chunk(filename, binary=None, from_page=0, to_page=100000,
  48. lang="Chinese", callback=None, **kwargs):
  49. """
  50. Supported file formats are docx, pdf, excel, txt.
  51. This method apply the naive ways to chunk files.
  52. Successive text will be sliced into pieces using 'delimiter'.
  53. Next, these successive pieces are merge into chunks whose token number is no more than 'Max token number'.
  54. """
  55. eng = lang.lower() == "english" # is_english(cks)
  56. parser_config = kwargs.get(
  57. "parser_config", {
  58. "chunk_token_num": 128, "delimiter": "\n!?。;!?", "layout_recognize": True})
  59. doc = {
  60. "docnm_kwd": filename,
  61. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  62. }
  63. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  64. res = []
  65. pdf_parser = None
  66. sections = []
  67. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  68. callback(0.1, "Start to parse.")
  69. for txt in laws.Docx()(filename, binary):
  70. sections.append((txt, ""))
  71. callback(0.8, "Finish parsing.")
  72. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  73. pdf_parser = Pdf(
  74. ) if parser_config["layout_recognize"] else PlainParser()
  75. sections, tbls = pdf_parser(filename if not binary else binary,
  76. from_page=from_page, to_page=to_page, callback=callback)
  77. res = tokenize_table(tbls, doc, eng)
  78. elif re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  79. callback(0.1, "Start to parse.")
  80. excel_parser = ExcelParser()
  81. sections = [(excel_parser.html(binary), "")]
  82. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  83. callback(0.1, "Start to parse.")
  84. txt = ""
  85. if binary:
  86. txt = binary.decode("utf-8")
  87. else:
  88. with open(filename, "r") as f:
  89. while True:
  90. l = f.readline()
  91. if not l:
  92. break
  93. txt += l
  94. sections = txt.split("\n")
  95. sections = [(l, "") for l in sections if l]
  96. callback(0.8, "Finish parsing.")
  97. else:
  98. raise NotImplementedError(
  99. "file type not supported yet(docx, pdf, txt supported)")
  100. chunks = naive_merge(
  101. sections, parser_config.get(
  102. "chunk_token_num", 128), parser_config.get(
  103. "delimiter", "\n!?。;!?"))
  104. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  105. return res
  106. if __name__ == "__main__":
  107. import sys
  108. def dummy(prog=None, msg=""):
  109. pass
  110. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)