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.

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