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

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