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.

book.py 5.0KB

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