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.

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