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.

laws.py 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 rag.nlp import bullets_category, is_english, tokenize, remove_contents_table, hierarchical_merge, \
  18. make_colon_as_title, add_positions
  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. callback(msg="OCR is running...")
  47. self.__images__(
  48. filename if not binary else binary,
  49. zoomin,
  50. from_page,
  51. to_page)
  52. callback(0.1, "OCR finished")
  53. from timeit import default_timer as timer
  54. start = timer()
  55. self._layouts_rec(zoomin)
  56. callback(0.77, "Layout analysis finished")
  57. cron_logger.info("paddle layouts:".format((timer()-start)/(self.total_page+0.1)))
  58. self._naive_vertical_merge()
  59. callback(0.8, "Text extraction finished")
  60. return [b["text"] + self._line_tag(b, zoomin) for b in self.boxes]
  61. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  62. """
  63. Supported file formats are docx, pdf, txt.
  64. """
  65. doc = {
  66. "docnm_kwd": filename,
  67. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  68. }
  69. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  70. pdf_parser = None
  71. sections = []
  72. if re.search(r"\.docx?$", filename, re.IGNORECASE):
  73. callback(0.1, "Start to parse.")
  74. for txt in Docx()(filename, binary):
  75. sections.append(txt)
  76. callback(0.8, "Finish parsing.")
  77. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  78. pdf_parser = Pdf()
  79. for txt in pdf_parser(filename if not binary else binary,
  80. from_page=from_page, to_page=to_page, callback=callback):
  81. sections.append(txt)
  82. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  83. callback(0.1, "Start to parse.")
  84. txt = ""
  85. if binary:txt = binary.decode("utf-8")
  86. else:
  87. with open(filename, "r") as f:
  88. while True:
  89. l = f.readline()
  90. if not l:break
  91. txt += l
  92. sections = txt.split("\n")
  93. sections = txt.split("\n")
  94. sections = [l for l in sections if l]
  95. callback(0.8, "Finish parsing.")
  96. else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)")
  97. # is it English
  98. eng = lang.lower() == "english"#is_english(sections)
  99. # Remove 'Contents' part
  100. remove_contents_table(sections, eng)
  101. make_colon_as_title(sections)
  102. bull = bullets_category(sections)
  103. cks = hierarchical_merge(bull, sections, 3)
  104. if not cks: callback(0.99, "No chunk parsed out.")
  105. res = []
  106. # wrap up to es documents
  107. for ck in cks:
  108. print("\n-".join(ck))
  109. ck = "\n".join(ck)
  110. d = copy.deepcopy(doc)
  111. if pdf_parser:
  112. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  113. add_positions(d, poss)
  114. ck = pdf_parser.remove_tag(ck)
  115. tokenize(d, ck, eng)
  116. res.append(d)
  117. return res
  118. if __name__ == "__main__":
  119. import sys
  120. def dummy(a, b):
  121. pass
  122. chunk(sys.argv[1], callback=dummy)