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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 docx import Document
  17. from deepdoc.parser import bullets_category, is_english, tokenize, remove_contents_table, hierarchical_merge, \
  18. make_colon_as_title
  19. from rag.nlp import huqie
  20. from deepdoc.parser import PdfParser, DocxParser
  21. from rag.settings import cron_logger
  22. class Docx(DocxParser):
  23. def __init__(self):
  24. pass
  25. def __clean(self, line):
  26. line = re.sub(r"\u3000", " ", line).strip()
  27. return line
  28. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  29. self.doc = Document(
  30. filename) if not binary else Document(BytesIO(binary))
  31. pn = 0
  32. lines = []
  33. for p in self.doc.paragraphs:
  34. if pn > to_page:break
  35. if from_page <= pn < to_page and p.text.strip(): lines.append(self.__clean(p.text))
  36. for run in p.runs:
  37. if 'lastRenderedPageBreak' in run._element.xml:
  38. pn += 1
  39. continue
  40. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  41. pn += 1
  42. return [l for l in lines if l]
  43. class Pdf(PdfParser):
  44. def __call__(self, filename, binary=None, from_page=0,
  45. to_page=100000, zoomin=3, callback=None):
  46. self.__images__(
  47. filename if not binary else binary,
  48. zoomin,
  49. from_page,
  50. to_page)
  51. callback(0.1, "OCR finished")
  52. from timeit import default_timer as timer
  53. start = timer()
  54. self._layouts_rec(zoomin)
  55. callback(0.77, "Layout analysis finished")
  56. cron_logger.info("paddle layouts:".format((timer()-start)/(self.total_page+0.1)))
  57. self._naive_vertical_merge()
  58. callback(0.8, "Text extraction finished")
  59. return [b["text"] + self._line_tag(b, zoomin) for b in self.boxes]
  60. def chunk(filename, binary=None, from_page=0, to_page=100000, callback=None, **kwargs):
  61. """
  62. Supported file formats are docx, pdf, txt.
  63. """
  64. doc = {
  65. "docnm_kwd": filename,
  66. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  67. }
  68. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  69. pdf_parser = None
  70. sections = []
  71. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  72. callback(0.1, "Start to parse.")
  73. for txt in Docx()(filename, binary):
  74. sections.append(txt)
  75. callback(0.8, "Finish parsing.")
  76. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  77. pdf_parser = Pdf()
  78. for txt in pdf_parser(filename if not binary else binary,
  79. from_page=from_page, to_page=to_page, callback=callback):
  80. sections.append(txt)
  81. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  82. callback(0.1, "Start to parse.")
  83. txt = ""
  84. if binary:txt = binary.decode("utf-8")
  85. else:
  86. with open(filename, "r") as f:
  87. while True:
  88. l = f.readline()
  89. if not l:break
  90. txt += l
  91. sections = txt.split("\n")
  92. sections = txt.split("\n")
  93. sections = [l for l in sections if l]
  94. callback(0.8, "Finish parsing.")
  95. else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)")
  96. # is it English
  97. eng = is_english(sections)
  98. # Remove 'Contents' part
  99. remove_contents_table(sections, eng)
  100. make_colon_as_title(sections)
  101. bull = bullets_category(sections)
  102. cks = hierarchical_merge(bull, sections, 3)
  103. if not cks: callback(0.99, "No chunk parsed out.")
  104. res = []
  105. # wrap up to es documents
  106. for ck in cks:
  107. print("\n-".join(ck))
  108. ck = "\n".join(ck)
  109. d = copy.deepcopy(doc)
  110. if pdf_parser:
  111. d["image"] = pdf_parser.crop(ck)
  112. ck = pdf_parser.remove_tag(ck)
  113. tokenize(d, ck, eng)
  114. res.append(d)
  115. return res
  116. if __name__ == "__main__":
  117. import sys
  118. def dummy(a, b):
  119. pass
  120. chunk(sys.argv[1], callback=dummy)