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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. import re
  15. from io import BytesIO
  16. from deepdoc.parser.utils import get_text
  17. from rag.nlp import bullets_category, is_english,remove_contents_table, \
  18. hierarchical_merge, make_colon_as_title, naive_merge, random_choices, tokenize_table, \
  19. tokenize_chunks
  20. from rag.nlp import rag_tokenizer
  21. from deepdoc.parser import PdfParser, DocxParser, PlainParser, HtmlParser
  22. from api.utils.log_utils import logger
  23. class Pdf(PdfParser):
  24. def __call__(self, filename, binary=None, from_page=0,
  25. to_page=100000, zoomin=3, callback=None):
  26. callback(msg="OCR is running...")
  27. self.__images__(
  28. filename if not binary else binary,
  29. zoomin,
  30. from_page,
  31. to_page,
  32. callback)
  33. callback(msg="OCR finished")
  34. from timeit import default_timer as timer
  35. start = timer()
  36. self._layouts_rec(zoomin)
  37. callback(0.67, "Layout analysis finished")
  38. logger.info("layouts: {}".format(timer() - start))
  39. self._table_transformer_job(zoomin)
  40. callback(0.68, "Table analysis finished")
  41. self._text_merge()
  42. tbls = self._extract_table_figure(True, zoomin, True, True)
  43. self._naive_vertical_merge()
  44. self._filter_forpages()
  45. self._merge_with_same_bullet()
  46. callback(0.75, "Text merging finished.")
  47. callback(0.8, "Text extraction finished")
  48. return [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", ""))
  49. for b in self.boxes], tbls
  50. def chunk(filename, binary=None, from_page=0, to_page=100000,
  51. lang="Chinese", callback=None, **kwargs):
  52. """
  53. Supported file formats are docx, pdf, txt.
  54. Since a book is long and not all the parts are useful, if it's a PDF,
  55. please setup the page ranges for every book in order eliminate negative effects and save elapsed computing time.
  56. """
  57. doc = {
  58. "docnm_kwd": filename,
  59. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  60. }
  61. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  62. pdf_parser = None
  63. sections, tbls = [], []
  64. if re.search(r"\.docx$", filename, re.IGNORECASE):
  65. callback(0.1, "Start to parse.")
  66. doc_parser = DocxParser()
  67. # TODO: table of contents need to be removed
  68. sections, tbls = doc_parser(
  69. binary if binary else filename, from_page=from_page, to_page=to_page)
  70. remove_contents_table(sections, eng=is_english(
  71. random_choices([t for t, _ in sections], k=200)))
  72. tbls = [((None, lns), None) for lns in tbls]
  73. callback(0.8, "Finish parsing.")
  74. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  75. pdf_parser = Pdf() if kwargs.get(
  76. "parser_config", {}).get(
  77. "layout_recognize", True) else PlainParser()
  78. sections, tbls = pdf_parser(filename if not binary else binary,
  79. from_page=from_page, to_page=to_page, callback=callback)
  80. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  81. callback(0.1, "Start to parse.")
  82. txt = get_text(filename, binary)
  83. sections = txt.split("\n")
  84. sections = [(l, "") for l in sections if l]
  85. remove_contents_table(sections, eng=is_english(
  86. random_choices([t for t, _ in sections], k=200)))
  87. callback(0.8, "Finish parsing.")
  88. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  89. callback(0.1, "Start to parse.")
  90. sections = HtmlParser()(filename, binary)
  91. sections = [(l, "") for l in sections if l]
  92. remove_contents_table(sections, eng=is_english(
  93. random_choices([t for t, _ in sections], k=200)))
  94. callback(0.8, "Finish parsing.")
  95. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  96. callback(0.1, "Start to parse.")
  97. binary = BytesIO(binary)
  98. doc_parsed = parser.from_buffer(binary)
  99. sections = doc_parsed['content'].split('\n')
  100. sections = [(l, "") for l in sections if l]
  101. remove_contents_table(sections, eng=is_english(
  102. random_choices([t for t, _ in sections], k=200)))
  103. callback(0.8, "Finish parsing.")
  104. else:
  105. raise NotImplementedError(
  106. "file type not supported yet(doc, docx, pdf, txt supported)")
  107. make_colon_as_title(sections)
  108. bull = bullets_category(
  109. [t for t in random_choices([t for t, _ in sections], k=100)])
  110. if bull >= 0:
  111. chunks = ["\n".join(ck)
  112. for ck in hierarchical_merge(bull, sections, 5)]
  113. else:
  114. sections = [s.split("@") for s, _ in sections]
  115. sections = [(pr[0], "@" + pr[1]) if len(pr) == 2 else (pr[0], '') for pr in sections ]
  116. chunks = naive_merge(
  117. sections, kwargs.get(
  118. "chunk_token_num", 256), kwargs.get(
  119. "delimer", "\n。;!?"))
  120. # is it English
  121. # is_english(random_choices([t for t, _ in sections], k=218))
  122. eng = lang.lower() == "english"
  123. res = tokenize_table(tbls, doc, eng)
  124. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  125. return res
  126. if __name__ == "__main__":
  127. import sys
  128. def dummy(prog=None, msg=""):
  129. pass
  130. chunk(sys.argv[1], from_page=1, to_page=10, callback=dummy)