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

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