您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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